Files
occupancy-fitting/web/packing.js
T
OpenCode 20567c0781 feat: container packing simulator + Android shell
- web/packing: scan-sweep planner (bottom-up X/Y sweep, all items per cell),
  multi-direction candidates, gap fill, stack/capacity/rigid-body checks,
  theoretical fill bound with red warning, occupancy voxel metrics
- per-item params via right-click menu (upright, stack count, capacity,
  box/voxel fit, mass); simplified left panel
- 3D: pan/zoom/rotate mouse mapping, touch gestures, draggable XYZ compass
- android: offline WebView APK build pipeline (aapt2/javac/d8/apksigner)
- docs: packing preview and mobile screenshots
2026-11-26 15:26:16 +08:00

2019 lines
80 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.
/* Voxel Container Filling — 长方体 / 小立方体混装
*
* 每件货可单独设置:
* - 拟合方式:默认长方体(最小外接盒);显式改成小立方体才按 100 mm 体素占位
* - 正向锁定:锁定只允许绕竖轴 0/90/180/270°;不锁定允许球面任意角度
* - 堆码个数:整数 1–9。1 = 不可再压,2 = 上面还能再堆 1 个……同一竖列取最小值
*
* 体素件的中空 / 内凹区域不占“堆码深度”,所以即使堆码个数是 1,
* 孔洞、框架内部、半开放凹腔里仍然可以继续塞货。
*/
(function () {
"use strict";
const $ = (id) => document.getElementById(id);
if (!window.THREE || !window.CAR_VOXELS) {
const t = $("toast");
if (t) { t.hidden = false; t.textContent = "three.js 或 car-voxels.js 未加载"; }
return;
}
const QUERY = new URLSearchParams(location.search);
const DEBUG = QUERY.has("debug");
const PITCH = 100;
const CLEAR = 1;
const SUPPORT_MIN = 0.6;
const BIG_FOOTPRINT_CELLS = 150; // ≈1.5 m²,大底面积件
const BIG_SUPPORT_MIN = 0.85; // 大件上高层时要求更高支撑
const MAX_STACK = 9;
const BASE_W = { z: 1.0, front: 0.5, support: 0.4, wall: 0.2, upright: 0.12 };
const CONTAINERS = {
"40gp": { key: "40gp", label: "40' GP", L: 12032, W: 2352, H: 2393, payload: 26700, note: "40 尺标准箱" },
"40hc": { key: "40hc", label: "40' HC", L: 12032, W: 2352, H: 2698, payload: 26500, note: "40 尺高箱" },
};
function mulberry32(seed) {
let s = seed >>> 0;
return function () {
s = (s + 0x6D2B79F5) | 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// ---------------------------------------------------------------- rotations
function buildAxisRotations() {
const out = [];
const perms = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]];
for (const p of perms) {
for (const sx of [1, -1]) {
for (const sy of [1, -1]) {
for (const sz of [1, -1]) {
const m = new Array(9).fill(0);
m[p[0]] = sx;
m[3 + p[1]] = sy;
m[6 + p[2]] = sz;
const det = m[0] * (m[4] * m[8] - m[5] * m[7])
- m[1] * (m[3] * m[8] - m[5] * m[6])
+ m[2] * (m[3] * m[7] - m[4] * m[6]);
if (det > 0) out.push(m);
}
}
}
}
return out;
}
const AXIS_ROT = buildAxisRotations();
const UPRIGHT_ROT = AXIS_ROT.filter((m) => m[2] === 0 && m[5] === 0 && m[8] === 1);
function quatToMatrix(x, y, z, w) {
return [
1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w),
2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),
2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y),
];
}
function randomRotation(rng) {
const u1 = rng(), u2 = rng(), u3 = rng();
const a = Math.sqrt(1 - u1);
return quatToMatrix(
a * Math.sin(2 * Math.PI * u2),
a * Math.cos(2 * Math.PI * u2),
Math.sqrt(u1) * Math.sin(2 * Math.PI * u3),
Math.sqrt(u1) * Math.cos(2 * Math.PI * u3)
);
}
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;
}
// ---------------------------------------------------------------- catalog
// fit 默认全部是 box;想按真实轮廓装,就在页面上把那一件切成 voxel
const CATALOG = [
{ id: "car", name: "AURORA A1 概念车", kind: "vehicle", color: "#56e1ff",
dims: [5640, 2002, 965], mass: 780, upright: true, stackCount: 1, fit: "box", shape: "car",
note: "正向 · 车顶不可压" },
{ id: "engine", name: "发动机缸体", kind: "mechanical", color: "#ffb45a",
dims: [900, 700, 800], mass: 420, upright: true, stackCount: 3, fit: "box",
shape: { boxes: [[0, 0, 0, 900, 700, 480], [100, 100, 480, 800, 600, 760], [760, 200, 0, 900, 500, 300]] },
note: "正向(油底壳朝下)" },
{ id: "gearbox", name: "变速箱总成", kind: "mechanical", color: "#f0a25a",
dims: [700, 520, 600], mass: 165, upright: false, stackCount: 3, fit: "box",
shape: { boxes: [[0, 0, 0, 250, 520, 600], [250, 60, 0, 700, 460, 600]] },
note: "可任意角度" },
{ id: "subframe", name: "前副车架", kind: "mechanical", color: "#d98f4a",
dims: [1150, 900, 360], mass: 135, upright: false, stackCount: 4, fit: "box",
shape: { boxes: [[0, 0, 0, 1150, 120, 360], [0, 780, 0, 1150, 900, 360],
[0, 120, 0, 120, 780, 360], [1030, 120, 0, 1150, 780, 360]] },
note: "可任意角度 · 框架内部是空的" },
{ id: "wheelcrate", name: "轮组木箱(4 只)", kind: "crate", color: "#b991ff",
dims: [1200, 1200, 480], mass: 210, upright: true, stackCount: 3, fit: "box",
shape: { boxes: [[0, 0, 0, 1200, 1200, 400]] }, note: "正向 · 敞口箱" },
{ id: "battery", name: "动力电池包", kind: "electrical", color: "#6df5b1",
dims: [1600, 1000, 320], mass: 340, upright: true, stackCount: 1, fit: "box",
shape: { boxes: [[0, 0, 0, 1600, 1000, 280], [120, 260, 280, 420, 380, 340], [1180, 260, 280, 1480, 380, 340]] },
note: "必须正向 · 顶部不可压" },
{ id: "aerokit", name: "空气动力学套件箱", kind: "crate", color: "#9b8cff",
dims: [2400, 820, 620], mass: 95, upright: false, stackCount: 4, fit: "box",
shape: { boxes: [[0, 0, 0, 2400, 820, 620]] }, note: "可任意角度 · 长条箱" },
{ id: "seats", name: "座椅总成(2 只)", kind: "soft", color: "#ff9f7a",
dims: [1250, 720, 900], mass: 70, upright: true, stackCount: 1, fit: "box",
shape: { boxes: [[0, 0, 0, 520, 700, 900], [730, 0, 0, 1250, 700, 900]] },
note: "正向 · 软包不可压" },
{ id: "gearspare", name: "齿轮备件箱", kind: "crate", color: "#7fd4a8",
dims: [820, 620, 520], mass: 85, upright: false, stackCount: 4, fit: "box",
shape: { boxes: [[0, 0, 0, 820, 620, 520]] }, note: "可任意角度" },
{ id: "brackets", name: "钢制支架", kind: "steel", color: "#8fa3bb",
dims: [620, 420, 320], mass: 48, upright: false, stackCount: 9, fit: "box",
shape: { boxes: [[0, 0, 0, 200, 420, 320], [200, 0, 0, 620, 420, 120]] },
note: "可任意角度 · L 形" },
{ id: "hosereel", name: "管线盘", kind: "mechanical", color: "#6fc4d6",
dims: [1000, 1000, 420], mass: 75, upright: true, stackCount: 3, fit: "box",
shape: { cyls: [{ c: [500, 500], z: [0, 420], d: 1000, inner: 620 }] },
note: "正向(盘面水平)· 中间通孔可以塞货" },
{ id: "ballast", name: "配重块", kind: "steel", color: "#9aa8b8",
dims: [520, 520, 420], mass: 130, upright: false, stackCount: 9, fit: "box",
shape: { boxes: [[0, 0, 0, 520, 520, 420]] }, note: "可任意角度 · 随便压" },
{ id: "toolbox", name: "工具柜", kind: "crate", color: "#c9a0ff",
dims: [920, 520, 1120], mass: 115, upright: true, stackCount: 2, fit: "box",
shape: { boxes: [[0, 0, 0, 920, 520, 1000], [60, 40, 1000, 860, 480, 1120]] },
note: "正向(抽屉朝外)" },
{ id: "tyres", name: "轮胎堆(4 条)", kind: "soft", color: "#8fd0a0",
dims: [720, 720, 1040], mass: 62, upright: true, stackCount: 4, fit: "box",
shape: { cyls: [
{ c: [360, 360], z: [0, 250], d: 720, inner: 380 },
{ c: [360, 360], z: [260, 510], d: 720, inner: 380 },
{ c: [360, 360], z: [520, 770], d: 720, inner: 380 },
{ c: [360, 360], z: [780, 1030], d: 720, inner: 380 },
] }, note: "正向 · 中间可套" },
{ id: "glass", name: "玻璃 / 风挡箱", kind: "fragile", color: "#ff7a7a",
dims: [1450, 340, 720], mass: 42, upright: true, stackCount: 1, fit: "box",
shape: { boxes: [[0, 0, 0, 1450, 340, 720]] }, note: "必须正向 · 易碎不可压" },
{ id: "rails", name: "车架纵梁(3 根)", kind: "steel", color: "#a8b6c6",
dims: [3000, 420, 360], mass: 155, upright: false, stackCount: 4, fit: "box",
shape: { boxes: [[0, 0, 0, 3000, 100, 360], [0, 160, 0, 3000, 260, 360], [0, 320, 0, 3000, 420, 360]] },
note: "可任意角度 · 细长" },
{ id: "frontwing", name: "前翼板箱", kind: "crate", color: "#a0e0c0",
dims: [1800, 600, 400], mass: 55, upright: true, stackCount: 2, fit: "box",
shape: { boxes: [[0, 0, 0, 1800, 600, 400]] }, note: "正向" },
{ id: "driveshaft", name: "传动轴", kind: "mechanical", color: "#e0b070",
dims: [2200, 180, 180], mass: 28, upright: false, stackCount: 6, fit: "box",
shape: { boxes: [[0, 0, 0, 2200, 180, 180]] }, note: "可任意角度 · 细长轴" },
{ id: "hubspares", name: "轮毂备件箱", kind: "crate", color: "#b0a0e0",
dims: [600, 500, 400], mass: 45, upright: false, stackCount: 5, fit: "box",
shape: { boxes: [[0, 0, 0, 600, 500, 400]] }, note: "可任意角度" },
{ id: "ecucab", name: "电子控制柜", kind: "electrical", color: "#8fe0d0",
dims: [700, 600, 1200], mass: 95, upright: true, stackCount: 1, fit: "box",
shape: { boxes: [[0, 0, 0, 700, 600, 1200]] }, note: "必须正向 · 顶部不可压" },
{ id: "wiring", name: "线束箱", kind: "crate", color: "#d0b0f0",
dims: [1000, 700, 450], mass: 32, upright: false, stackCount: 4, fit: "box",
shape: { boxes: [[0, 0, 0, 1000, 700, 450]] }, note: "可任意角度 · 轻" },
{ id: "sparewheel", name: "备胎总成", kind: "soft", color: "#9ad0b8",
dims: [720, 720, 260], mass: 22, upright: true, stackCount: 5, fit: "box",
shape: { cyls: [{ c: [360, 360], z: [0, 260], d: 720, inner: 380 }] },
note: "正向 · 扁平" },
{ id: "palletA", name: "托盘箱 A(总成)", kind: "crate", color: "#8fd8ff",
dims: [1200, 1000, 1100], mass: 240, upright: true, stackCount: 3, fit: "box",
shape: { boxes: [[0, 0, 0, 1200, 1000, 1100]] }, note: "正向 · 托盘化" },
{ id: "palletB", name: "托盘箱 B(齿轮组)", kind: "crate", color: "#a9c6ff",
dims: [1200, 1000, 900], mass: 180, upright: true, stackCount: 3, fit: "box",
shape: { boxes: [[0, 0, 0, 1200, 1000, 900]] }, note: "正向 · 托盘化" },
{ id: "longcrate", name: "长条箱(侧箱)", kind: "crate", color: "#b7a6ff",
dims: [2600, 700, 700], mass: 120, upright: false, stackCount: 3, fit: "box",
shape: { boxes: [[0, 0, 0, 2600, 700, 700]] }, note: "可任意角度 · 细长" },
{ id: "coil", name: "钢卷(立放)", kind: "steel", color: "#93a2b3",
dims: [1100, 1100, 800], mass: 900, upright: true, stackCount: 1, fit: "box",
shape: { cyls: [{ c: [550, 550], z: [0, 800], d: 1100 }] },
note: "必须正向 · 重型不可压" },
{ id: "palletC", name: "托盘箱 C(电子件)", kind: "crate", color: "#9be8d6",
dims: [1200, 1000, 1200], mass: 260, upright: true, stackCount: 3, fit: "box",
shape: { boxes: [[0, 0, 0, 1200, 1000, 1200]] }, note: "正向 · 托盘化" },
{ id: "bodypanel", name: "车身覆盖件箱", kind: "fragile", color: "#ffc48f",
dims: [2000, 900, 500], mass: 85, upright: false, stackCount: 3, fit: "box",
shape: { boxes: [[0, 0, 0, 2000, 900, 500]] }, note: "可任意角度 · 薄板箱" },
{ id: "toolchest", name: "工具柜 B", kind: "crate", color: "#c3b7ff",
dims: [700, 500, 950], mass: 90, upright: false, stackCount: 4, fit: "box",
shape: { boxes: [[0, 0, 0, 700, 500, 950]] }, note: "可任意角度" },
{ id: "cabledrum", name: "电缆盘", kind: "mechanical", color: "#8ecfdc",
dims: [900, 900, 700], mass: 110, upright: true, stackCount: 3, fit: "box",
shape: { cyls: [{ c: [450, 450], z: [0, 700], d: 900, inner: 400 }] },
note: "正向(盘面水平)" },
];
const ITEM_BY_ID = {};
CATALOG.forEach(function (it) { ITEM_BY_ID[it.id] = it; });
// 承重上限(kg):该件顶部能承受的总载荷,0 = 不可压。
// 车顶、电池、玻璃、控制柜、钢卷按 0 处理;钢制件能扛更多。
const CAPACITY = {
car: 0, engine: 1500, gearbox: 800, subframe: 700, wheelcrate: 600,
battery: 0, aerokit: 400, seats: 0, gearspare: 500, brackets: 2000,
hosereel: 500, ballast: 5000, toolbox: 300, tyres: 300, glass: 0,
rails: 1500, frontwing: 200, driveshaft: 300, hubspares: 400, ecucab: 0,
wiring: 300, sparewheel: 300, palletA: 700, palletB: 700, palletC: 700,
longcrate: 500, coil: 0, bodypanel: 200, toolchest: 400, cabledrum: 400,
};
CATALOG.forEach(function (it) {
it.capacityKg = CAPACITY[it.id] === undefined ? 500 : CAPACITY[it.id];
});
// ---------------------------------------------------------------- voxelize
function rasterize(item) {
if (item.shape === "car") {
const cv = window.CAR_VOXELS;
const bytes = b64bytes(cv.b64);
const nx = cv.dims[0], ny = cv.dims[1], nz = cv.dims[2];
const cells = [];
for (let i = 0; i < nx; i++) {
for (let j = 0; j < ny; j++) {
const base = (i * ny + j) * nz;
for (let k = 0; k < nz; k++) {
const bit = base + k;
if (bytes[bit >> 3] & (128 >> (bit & 7))) cells.push(i, j, k);
}
}
}
return { cells: Int16Array.from(cells), dims: [nx, ny, nz] };
}
const nx = Math.max(1, Math.round(item.dims[0] / PITCH));
const ny = Math.max(1, Math.round(item.dims[1] / PITCH));
const nz = Math.max(1, Math.round(item.dims[2] / PITCH));
const grid = new Uint8Array(nx * ny * nz);
const at = (i, j, k) => i + nx * (j + ny * k);
(item.shape.boxes || []).forEach(function (b) {
for (let i = 0; i < nx; i++) {
const cx = (i + 0.5) * PITCH;
if (cx < b[0] || cx > b[3]) continue;
for (let j = 0; j < ny; j++) {
const cy = (j + 0.5) * PITCH;
if (cy < b[1] || cy > b[4]) continue;
for (let k = 0; k < nz; k++) {
const cz = (k + 0.5) * PITCH;
if (cz >= b[2] && cz <= b[5]) grid[at(i, j, k)] = 1;
}
}
}
});
(item.shape.cyls || []).forEach(function (c) {
const ox = c.c[0], oy = c.c[1], z0 = c.z[0], z1 = c.z[1];
const ro = c.d / 2, ri = (c.inner || 0) / 2;
for (let i = 0; i < nx; i++) {
const px = (i + 0.5) * PITCH;
for (let j = 0; j < ny; j++) {
const py = (j + 0.5) * PITCH;
const d = Math.hypot(px - ox, py - oy);
if (d > ro || d < ri) continue;
for (let k = 0; k < nz; k++) {
const pz = (k + 0.5) * PITCH;
if (pz >= z0 && pz <= z1) grid[at(i, j, k)] = 1;
}
}
}
});
const cells = [];
for (let k = 0; k < nz; k++) {
for (let j = 0; j < ny; j++) {
for (let i = 0; i < nx; i++) if (grid[at(i, j, k)]) cells.push(i, j, k);
}
}
return { cells: Int16Array.from(cells), dims: [nx, ny, nz] };
}
CATALOG.forEach(function (it) {
const r = rasterize(it);
it.cells = r.cells;
it.voxDims = r.dims;
it.volume = r.cells.length / 3;
it.vAxis = null;
it.vRandom = null;
});
// ---------------------------------------------------------------- variants
function rotateCellsAxis(cells, m) {
const n = cells.length;
const out = new Int16Array(n);
let minX = 1e9, minY = 1e9, minZ = 1e9, maxX = -1e9, maxY = -1e9, maxZ = -1e9;
for (let t = 0; t < n; t += 3) {
const x = cells[t], y = cells[t + 1], z = cells[t + 2];
const nx = m[0] * x + m[1] * y + m[2] * z;
const ny = m[3] * x + m[4] * y + m[5] * z;
const nz = m[6] * x + m[7] * y + m[8] * z;
out[t] = nx; out[t + 1] = ny; out[t + 2] = nz;
if (nx < minX) minX = nx; if (nx > maxX) maxX = nx;
if (ny < minY) minY = ny; if (ny > maxY) maxY = ny;
if (nz < minZ) minZ = nz; if (nz > maxZ) maxZ = nz;
}
for (let t = 0; t < n; t += 3) {
out[t] -= minX; out[t + 1] -= minY; out[t + 2] -= minZ;
}
return { cells: out, dims: [maxX - minX + 1, maxY - minY + 1, maxZ - minZ + 1] };
}
function rotateCellsFree(cells, dims, m) {
const nx = dims[0], ny = dims[1], nz = dims[2];
let minX = 1e9, minY = 1e9, minZ = 1e9, maxX = -1e9, maxY = -1e9, maxZ = -1e9;
[0, nx].forEach(function (x) {
[0, ny].forEach(function (y) {
[0, nz].forEach(function (z) {
const px = m[0] * x + m[1] * y + m[2] * z;
const py = m[3] * x + m[4] * y + m[5] * z;
const pz = m[6] * x + m[7] * y + m[8] * z;
if (px < minX) minX = px; if (px > maxX) maxX = px;
if (py < minY) minY = py; if (py > maxY) maxY = py;
if (pz < minZ) minZ = pz; if (pz > maxZ) maxZ = pz;
});
});
});
const sx = Math.max(1, Math.ceil(maxX - minX));
const sy = Math.max(1, Math.ceil(maxY - minY));
const sz = Math.max(1, Math.ceil(maxZ - minZ));
const grid = new Uint8Array(sx * sy * sz);
for (let t = 0; t < cells.length; t += 3) {
const px = cells[t] + 0.5, py = cells[t + 1] + 0.5, pz = cells[t + 2] + 0.5;
const x = m[0] * px + m[1] * py + m[2] * pz - minX;
const y = m[3] * px + m[4] * py + m[5] * pz - minY;
const z = m[6] * px + m[7] * py + m[8] * pz - minZ;
const i = Math.min(sx - 1, Math.max(0, Math.floor(x)));
const j = Math.min(sy - 1, Math.max(0, Math.floor(y)));
const k = Math.min(sz - 1, Math.max(0, Math.floor(z)));
grid[i + sx * (j + sy * k)] = 1;
}
const out = [];
for (let k = 0; k < sz; k++) {
for (let j = 0; j < sy; j++) {
for (let i = 0; i < sx; i++) if (grid[i + sx * (j + sy * k)]) out.push(i, j, k);
}
}
return { cells: Int16Array.from(out), dims: [sx, sy, sz] };
}
function boxCells(dims) {
const nx = dims[0], ny = dims[1], nz = dims[2];
const cells = [];
for (let k = 0; k < nz; k++) {
for (let j = 0; j < ny; j++) {
for (let i = 0; i < nx; i++) cells.push(i, j, k);
}
}
return Int16Array.from(cells);
}
function makeVariant(cells, dims, identity, label, free) {
const nx = dims[0], ny = dims[1], nz = dims[2];
const mask = new Uint8Array(nx * ny * nz);
const colMap = new Map();
const bx = [], by = [];
let sx = 0, sy = 0, sz = 0;
for (let t = 0; t < cells.length; t += 3) {
const x = cells[t], y = cells[t + 1], z = cells[t + 2];
mask[x + nx * (y + ny * z)] = 1;
const key = x * 4096 + y;
const cur = colMap.get(key);
if (cur === undefined) colMap.set(key, { x: x, y: y, h: z + 1 });
else if (z + 1 > cur.h) cur.h = z + 1;
if (z === 0) { bx.push(x); by.push(y); }
sx += x + 0.5; sy += y + 0.5; sz += z + 0.5;
}
const n = colMap.size;
const nCells = cells.length / 3;
const colX = new Int16Array(n), colY = new Int16Array(n), colH = new Int16Array(n);
let i = 0;
colMap.forEach(function (c) { colX[i] = c.x; colY[i] = c.y; colH[i] = c.h; i++; });
return {
cells: cells, nx: nx, ny: ny, nz: nz, mask: mask, identity: identity,
free: !!free, label: label,
colX: colX, colY: colY, colH: colH,
bottomX: Int16Array.from(bx), bottomY: Int16Array.from(by),
// 体素质心的刚体近似:质心 + 占有体积
comX: sx / nCells, comY: sy / nCells, comZ: sz / nCells,
volume: nCells,
};
}
function sameMask(a, b) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
function isIdentity(m) {
return m[0] === 1 && m[4] === 1 && m[8] === 1
&& m[1] === 0 && m[2] === 0 && m[3] === 0 && m[5] === 0 && m[6] === 0 && m[7] === 0;
}
function baseCells(item) {
if (item.fit === "box") {
const nx = Math.max(1, Math.round(item.dims[0] / PITCH));
const ny = Math.max(1, Math.round(item.dims[1] / PITCH));
const nz = Math.max(1, Math.round(item.dims[2] / PITCH));
return { cells: boxCells([nx, ny, nz]), dims: [nx, ny, nz] };
}
return { cells: item.cells, dims: item.voxDims };
}
function axisVariants(item) {
const key = (item.upright ? "u" : "f") + "|" + item.fit;
if (item.vAxis && item.vAxisKey === key) return item.vAxis;
const base = baseCells(item);
const rots = item.upright ? UPRIGHT_ROT : AXIS_ROT;
const groups = new Map();
const out = [];
for (const m of rots) {
const r = rotateCellsAxis(base.cells, m);
const dk = r.dims.join(",");
const list = groups.get(dk) || [];
const ident = isIdentity(m);
const label = ident ? "原向" : (item.upright ? "水平旋转" : "翻倒");
const v = makeVariant(r.cells, r.dims, ident, label, false);
let dup = false;
for (const other of list) { if (sameMask(other.mask, v.mask)) { dup = true; break; } }
if (dup) continue;
list.push(v);
groups.set(dk, list);
out.push(v);
}
item.vAxis = out;
item.vAxisKey = key;
return out;
}
function randomVariants(item) {
const key = (item.upright ? "u" : "f") + "|" + item.fit;
if (item.vRandom && item.vRandomKey === key) return item.vRandom;
const base = baseCells(item);
const rng = mulberry32(item.id.length * 7919 + 17);
const out = [];
for (let i = 0; i < 12; i++) {
const m = randomRotation(rng);
const r = rotateCellsFree(base.cells, base.dims, m);
out.push(makeVariant(r.cells, r.dims, false, "斜放", true));
}
item.vRandom = out;
item.vRandomKey = key;
return out;
}
function variantsForRound(item, round) {
const axis = axisVariants(item);
if (item.upright || item.fit === "box") return axis;
const pool = randomVariants(item);
const start = (round * 3) % pool.length;
const picks = [];
for (let i = 0; i < 4; i++) picks.push(pool[(start + i) % pool.length]);
return axis.concat(picks);
}
// ------------------------------------------------------------------ packing
function Packer(c) {
this.c = c;
this.L = Math.ceil(c.L / PITCH);
this.W = Math.ceil(c.W / PITCH);
this.H = Math.ceil(c.H / PITCH);
this.LW = this.L * this.W;
this.blocked = new Uint8Array(this.LW * this.H);
this.top = new Int16Array(this.LW);
this.depth = new Uint8Array(this.LW);
this.limit = new Uint8Array(this.LW).fill(MAX_STACK);
this.topOwner = new Int16Array(this.LW).fill(-1);
this.items = [];
this.load = [];
this.points = [[CLEAR, CLEAR]];
this.seen = new Set(["1|1"]);
}
// 体素接触面:只统计“顶面正好在 z”的列,中空/凹腔不传力
Packer.prototype.contacts = function (v, x, y, z) {
const L = this.L;
const map = new Map();
let minX = 1e9, maxX = -1e9, minY = 1e9, maxY = -1e9;
let sx = 0, sy = 0, n = 0;
for (let i = 0; i < v.bottomX.length; i++) {
const bx = v.bottomX[i], by = v.bottomY[i];
const idx = (x + bx) + L * (y + by);
if (this.top[idx] !== z) continue;
const owner = this.topOwner[idx];
if (owner < 0) continue;
map.set(owner, (map.get(owner) || 0) + 1);
const wx = x + bx, wy = y + by;
if (wx < minX) minX = wx; if (wx > maxX) maxX = wx;
if (wy < minY) minY = wy; if (wy > maxY) maxY = wy;
sx += wx; sy += wy; n++;
}
return {
map: map, n: n,
minX: minX, maxX: maxX, minY: minY, maxY: maxY,
cx: n ? sx / n : 0, cy: n ? sy / n : 0,
};
};
// 刚体稳定性:质心必须落在接触区内,偏心率会放大等效载荷(力矩效应)
Packer.prototype.bodyOk = function (v, x, y, z, ct) {
if (z === 0) return 1;
if (!ct || !ct.n) return 0;
const comX = x + v.comX;
const comY = y + v.comY;
if (comX < ct.minX - 0.5 || comX > ct.maxX + 1.5) return 0;
if (comY < ct.minY - 0.5 || comY > ct.maxY + 1.5) return 0;
const halfW = Math.max((ct.maxX - ct.minX + 1) / 2, 0.5);
const halfH = Math.max((ct.maxY - ct.minY + 1) / 2, 0.5);
const half = Math.max(halfW, halfH);
const e = Math.hypot(comX - ct.cx, comY - ct.cy);
return Math.min(2.5, 1 + 1.5 * e / half);
};
Packer.prototype.loadOkCt = function (ct, mass, moment) {
const deltas = [];
const f = moment || 1;
const total = ct.n;
ct.map.forEach(function (cnt, owner) {
deltas.push([owner, mass * f * cnt / total]);
});
return this.propagate(deltas);
};
Packer.prototype.loadOk = function (v, x, y, z, mass, moment) {
if (z === 0) return true;
const ct = this.contacts(v, x, y, z);
if (!ct.n) return false;
return this.loadOkCt(ct, mass, moment || 1);
};
Packer.prototype.propagate = function (deltas) {
for (let k = 0; k < deltas.length; k++) {
const rec = this.items[deltas[k][0]];
if (!rec) return false;
if (rec.capacity <= 0) return false;
if (this.load[deltas[k][0]] + deltas[k][1] > rec.capacity + 1e-6) return false;
}
const next = new Map();
for (let k = 0; k < deltas.length; k++) {
const rec = this.items[deltas[k][0]];
const d = deltas[k][1];
rec.shares.forEach(function (frac, supportIdx) {
next.set(supportIdx, (next.get(supportIdx) || 0) + d * frac);
});
}
if (!next.size) return true;
const arr = [];
next.forEach(function (val, key) { arr.push([key, val]); });
return this.propagate(arr);
};
Packer.prototype.addLoad = function (deltas) {
for (let k = 0; k < deltas.length; k++) {
const idx = deltas[k][0];
const d = deltas[k][1];
this.load[idx] += d;
const next = [];
const rec = this.items[idx];
rec.shares.forEach(function (frac, supportIdx) { next.push([supportIdx, d * frac]); });
if (next.length) this.addLoad(next);
}
};
Packer.prototype.addPoint = function (x, y) {
if (x < CLEAR || y < CLEAR) return;
if (x >= this.L - CLEAR || y >= this.W - CLEAR) return;
const k = x + "|" + y;
if (this.seen.has(k)) return;
this.seen.add(k);
this.points.push([x, y]);
if (this.points.length > 100) {
this.points.sort(function (a, b) { return (a[0] + a[1]) - (b[0] + b[1]); });
this.points.length = 100;
this.seen = new Set(this.points.map(function (p) { return p[0] + "|" + p[1]; }));
}
};
Packer.prototype.drop = function (v, x, y) {
let z = 0;
const L = this.L, top = this.top;
for (let i = 0; i < v.colX.length; i++) {
const t = top[(x + v.colX[i]) + L * (y + v.colY[i])];
if (t > z) z = t;
}
return z;
};
Packer.prototype.support = function (v, x, y, z) {
const n = v.bottomX.length;
if (!n || z === 0) return 1;
let ok = 0;
const L = this.L, top = this.top;
for (let i = 0; i < n; i++) {
if (top[(x + v.bottomX[i]) + L * (y + v.bottomY[i])] === z) ok++;
}
return ok / n;
};
Packer.prototype.stackOk = function (v, x, y) {
const L = this.L, depth = this.depth, limit = this.limit;
for (let i = 0; i < v.colX.length; i++) {
const idx = (x + v.colX[i]) + L * (y + v.colY[i]);
if (depth[idx] + 1 > limit[idx]) return false;
}
return true;
};
Packer.prototype.collides = function (v, x, y, z) {
const L = this.L, LW = this.LW, blocked = this.blocked;
const cx = v.cells;
const base = x + L * y + LW * z;
for (let t = 0; t < cx.length; t += 3) {
if (blocked[base + cx[t] + L * cx[t + 1] + LW * cx[t + 2]]) return true;
}
return false;
};
Packer.prototype.score = function (item, v, x, y, z, sup, w, moment) {
const c = this.c;
let s = 0;
s += w.z * (1 - z / this.H);
s += w.front * (1 - x / this.L);
s += w.support * sup;
let walls = 0;
if (x <= CLEAR + 1) walls++;
if (y <= CLEAR + 1) walls++;
if (x + v.nx >= this.L - CLEAR - 1) walls++;
if (y + v.ny >= this.W - CLEAR - 1) walls++;
s += w.wall * (walls / 2);
if (v.identity) s += w.upright;
if (moment && moment > 1) s -= 0.08 * (moment - 1); // 偏心受力扣分
const dyMm = v.ny * PITCH;
const cy = y * PITCH + dyMm / 2;
if (dyMm > 0.45 * c.W) s += 0.25 * (1 - Math.abs(cy - c.W / 2) / (c.W / 2));
return s;
};
Packer.prototype.best = function (item, round, w) {
const vs = variantsForRound(item, round);
const L = this.L, W = this.W, H = this.H;
let best = null;
for (let vi = 0; vi < vs.length; vi++) {
const v = vs[vi];
if (v.nx + 2 * CLEAR > L || v.ny + 2 * CLEAR > W) continue;
for (let pi = 0; pi < this.points.length; pi++) {
const x = this.points[pi][0], y = this.points[pi][1];
if (x + v.nx + CLEAR > L || y + v.ny + CLEAR > W) continue;
const z = this.drop(v, x, y);
if (z + v.nz > H) continue;
const sup = z === 0 ? 1 : this.support(v, x, y, z);
if (z > 0 && sup < SUPPORT_MIN) continue;
if (z > 0 && v.nx * v.ny >= BIG_FOOTPRINT_CELLS && sup < BIG_SUPPORT_MIN) continue;
if (!this.stackOk(v, x, y)) continue;
if (this.collides(v, x, y, z)) continue;
let moment = 1;
if (z > 0) {
const ct = this.contacts(v, x, y, z);
moment = this.bodyOk(v, x, y, z, ct);
if (!moment) continue;
if (!this.loadOkCt(ct, item.mass, moment)) continue;
}
const s = this.score(item, v, x, y, z, sup, w, moment);
if (!best || s > best.score) best = { item: item, v: v, x: x, y: y, z: z, support: sup, score: s };
}
}
return best;
};
Packer.prototype.apply = function (p) {
const v = p.v;
const x = p.x, y = p.y, z = p.z;
const L = this.L, W = this.W, LW = this.LW;
const blocked = this.blocked, top = this.top, depth = this.depth, limit = this.limit;
const topOwner = this.topOwner;
const cells = v.cells;
// 力学接触:只统计“顶面正好在 z”的列,中空/凹腔不会传力
const ct = this.contacts(v, x, y, z);
const moment = z > 0 ? this.bodyOk(v, x, y, z, ct) : 1;
const fracs = new Map();
if (ct.n > 0) ct.map.forEach(function (n, owner) { fracs.set(owner, n / ct.n); });
for (let t = 0; t < cells.length; t += 3) {
const bx = x + cells[t], by = y + cells[t + 1], bz = z + cells[t + 2];
for (let dx = -CLEAR; dx <= CLEAR; dx++) {
const nx = bx + dx;
if (nx < 0 || nx >= L) continue;
for (let dy = -CLEAR; dy <= CLEAR; dy++) {
const ny = by + dy;
if (ny < 0 || ny >= W) continue;
blocked[nx + L * ny + LW * bz] = 1;
}
}
}
const sc = Math.min(MAX_STACK, Math.max(1, p.item.stackCount | 0));
for (let i = 0; i < v.colX.length; i++) {
const idx = (x + v.colX[i]) + L * (y + v.colY[i]);
const h = z + v.colH[i];
if (h > top[idx]) top[idx] = h;
if (depth[idx] < MAX_STACK) depth[idx] += 1;
if (sc < limit[idx]) limit[idx] = sc;
}
const itemIdx = this.items.length;
this.items.push({
capacity: p.item.capacityKg || 0,
mass: p.item.mass,
shares: fracs,
moment: moment,
});
this.load.push(0);
for (let i = 0; i < v.colX.length; i++) {
topOwner[(x + v.colX[i]) + L * (y + v.colY[i])] = itemIdx;
}
if (fracs.size) {
const deltas = [];
const f = p.item.mass * (moment || 1);
fracs.forEach(function (frac, sIdx) { deltas.push([sIdx, f * frac]); });
this.addLoad(deltas);
}
this.addPoint(x + v.nx + CLEAR, y);
this.addPoint(x, y + v.ny + CLEAR);
this.addPoint(x + v.nx + CLEAR, y + v.ny + CLEAR);
this.addPoint(CLEAR, y + v.ny + CLEAR);
this.addPoint(x + v.nx + CLEAR, CLEAR);
};
function packOrder(items, c, weights, round) {
const packer = new Packer(c);
const placed = [], unplaced = [];
for (let i = 0; i < items.length; i++) {
const p = packer.best(items[i], round, weights);
if (!p) { unplaced.push(items[i]); continue; }
p.order = placed.length;
placed.push(p);
packer.apply(p);
}
return { placed: placed, unplaced: unplaced };
}
function statsOf(res, c) {
const boxVol = (c.L * c.W * c.H) / 1e9;
let vol = 0, mass = 0, topMm = 0;
const cog = [0, 0, 0];
let free = 0, axisRot = 0, voxels = 0, bigHigh = 0;
res.placed.forEach(function (p) {
const v = p.v, cells = v.cells;
let cx = 0, cy = 0, cz = 0;
for (let t = 0; t < cells.length; t += 3) {
cx += cells[t] + 0.5; cy += cells[t + 1] + 0.5; cz += cells[t + 2] + 0.5;
}
const n = v.volume, m = p.item.mass;
voxels += n;
vol += n * (PITCH ** 3) / 1e9;
mass += m;
topMm = Math.max(topMm, (p.z + v.nz) * PITCH);
cog[0] += (p.x + cx / n) * PITCH * m;
cog[1] += (p.y + cy / n) * PITCH * m;
cog[2] += (p.z + cz / n) * PITCH * m;
if (v.free) free++;
else if (!v.identity) axisRot++;
if (p.z > 0 && v.nx * v.ny >= BIG_FOOTPRINT_CELLS) bigHigh++;
});
if (mass > 0) { cog[0] /= mass; cog[1] /= mass; cog[2] /= mass; }
const gridVoxels = Math.ceil(c.L / PITCH) * Math.ceil(c.W / PITCH) * Math.ceil(c.H / PITCH);
return {
vol: vol, mass: mass, topMm: topMm, cog: cog,
count: res.placed.length, fill: vol / boxVol, free: free, axis: axisRot,
voxels: voxels, gridVoxels: gridVoxels, bigHigh: bigHigh,
};
}
function betterPlan(a, b) {
if (!b) return true;
if (Math.abs(a.vol - b.vol) > 1e-9) return a.vol > b.vol;
if (a.count !== b.count) return a.count > b.count;
if (Math.abs(a.topMm - b.topMm) > 1) return a.topMm < b.topMm;
return a.free > b.free;
}
// ---------------------------------------------------------------- optimizer
let rngState = 20261128;
function rnd() {
rngState |= 0;
rngState = (rngState + 0x6D2B79F5) | 0;
let t = rngState;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
// ---------------------------------------------------------------- 扫描铺装
// 从箱底开始逐层沿 X / Y 扫描;每到一个空位,把所有剩余件按体积从大到小试一遍,
// 第一个满足「堆码个数 + 承重 + 支撑 + 间隙 + 不干涉」的就放下,然后继续往后扫,
// 像冒泡排序一样一路铺到箱尾。多组扫描方向并行评估,取填充率最高的方案。
function sortPool(items, mode) {
const pool = items.slice();
if (mode === "shuffle") {
return pool;
}
if (mode === "stability") {
pool.sort(function (a, b) {
const fa = a.dims[0] * a.dims[1];
const fb = b.dims[0] * b.dims[1];
return (fb - fa) || (b.mass - a.mass) || (b.volume - a.volume);
});
} else if (mode === "height") {
pool.sort(function (a, b) { return (b.dims[2] - a.dims[2]) || (b.volume - a.volume); });
} else if (mode === "footprint") {
pool.sort(function (a, b) {
return ((b.dims[0] * b.dims[1]) - (a.dims[0] * a.dims[1])) || (b.volume - a.volume);
});
} else {
pool.sort(function (a, b) { return b.volume - a.volume; });
}
return pool;
}
function sweepCandidates(count) {
const dirs = [
{ label: "X↑Y↑", xAsc: true, yAsc: true, swap: false },
{ label: "X↑Y↓", xAsc: true, yAsc: false, swap: false },
{ label: "X↓Y↑", xAsc: false, yAsc: true, swap: false },
{ label: "X↓Y↓", xAsc: false, yAsc: false, swap: false },
{ label: "Y↑X↑", xAsc: true, yAsc: true, swap: true },
{ label: "Y↓X↓", xAsc: false, yAsc: false, swap: true },
{ label: "Y↑X↓", xAsc: false, yAsc: true, swap: true },
{ label: "Y↓X↑", xAsc: true, yAsc: false, swap: true },
];
const sorts = ["volume", "stability", "height", "footprint"];
const out = [];
const total = Math.max(1, count || 16);
for (let i = 0; i < total; i++) {
const d = dirs[i % dirs.length];
const s = sorts[Math.floor(i / dirs.length) % sorts.length];
const tag = s === "volume" ? "" : (s === "stability" ? "·稳" : (s === "height" ? "·高" : "·底面积"));
out.push({ label: d.label + tag, xAsc: d.xAsc, yAsc: d.yAsc, swap: d.swap, sort: s });
}
return out;
}
function fitAt(pk, item, x, y, z, round) {
const vs = variantsForRound(item, round);
for (let vi = 0; vi < vs.length; vi++) {
const v = vs[vi];
if (x + v.nx + CLEAR > pk.L || y + v.ny + CLEAR > pk.W) continue;
if (z + v.nz > pk.H) continue;
if (pk.drop(v, x, y) !== z) continue;
const sup = z === 0 ? 1 : pk.support(v, x, y, z);
if (z > 0 && sup < SUPPORT_MIN) continue;
if (z > 0 && v.nx * v.ny >= BIG_FOOTPRINT_CELLS && sup < BIG_SUPPORT_MIN) continue;
if (!pk.stackOk(v, x, y)) continue;
if (pk.collides(v, x, y, z)) continue;
let moment = 1;
if (z > 0) {
const ct = pk.contacts(v, x, y, z);
moment = pk.bodyOk(v, x, y, z, ct);
if (!moment) continue;
if (!pk.loadOkCt(ct, item.mass, moment)) continue;
}
return { item: item, v: v, x: x, y: y, z: z, support: sup, moment: moment };
}
return null;
}
function sweepPack(items, c, order, round) {
const pk = new Packer(c);
const L = pk.L, W = pk.W;
const pool = sortPool(items, order.sort);
const placed = [];
const xs = [], ys = [];
for (let x = CLEAR; x < L - CLEAR; x++) xs.push(x);
for (let y = CLEAR; y < W - CLEAR; y++) ys.push(y);
if (!order.xAsc) xs.reverse();
if (!order.yAsc) ys.reverse();
const outer = order.swap ? ys : xs;
const inner = order.swap ? xs : ys;
for (let z = 0; z < pk.H; z++) {
for (let oi = 0; oi < outer.length; oi++) {
for (let ii = 0; ii < inner.length; ii++) {
const x = order.swap ? inner[ii] : outer[oi];
const y = order.swap ? outer[oi] : inner[ii];
if (pk.top[x + L * y] !== z) continue;
for (let k = 0; k < pool.length; k++) {
const pick = fitAt(pk, pool[k], x, y, z, round);
if (!pick) continue;
pick.order = placed.length;
pk.apply(pick);
placed.push(pick);
pool.splice(k, 1);
k--;
}
}
}
}
return { placed: placed, unplaced: pool };
}
// 缝隙补装:在已铺好的方案上把剩下的件再沿空位扫一遍
function gapFill(res, toPlace, c, round) {
if (!toPlace.length) return { placed: res.placed, unplaced: [], added: [] };
const pk = new Packer(c);
res.placed.forEach(function (p) {
pk.apply({ item: p.item, v: p.v, x: p.x, y: p.y, z: p.z, support: p.support });
});
const pool = sortPool(toPlace, "volume");
const added = [];
for (let z = 0; z < pk.H; z++) {
for (let x = CLEAR; x < pk.L - CLEAR; x++) {
for (let y = CLEAR; y < pk.W - CLEAR; y++) {
if (pk.top[x + pk.L * y] !== z) continue;
for (let k = 0; k < pool.length; k++) {
const pick = fitAt(pk, pool[k], x, y, z, round);
if (!pick) continue;
pick.order = res.placed.length + added.length;
pk.apply(pick);
added.push(pick);
pool.splice(k, 1);
k--;
}
}
}
}
return { placed: res.placed.concat(added), unplaced: pool, added: added };
}
function makeFrame() { return new Promise(function (r) { setTimeout(r, 0); }); }
async function runSweeps(items, opts) {
const c = container();
const cands = sweepCandidates(opts.count);
let best = null, bestStats = null, bestLabel = "";
const history = [];
for (let k = 0; k < cands.length; k++) {
if (runToken !== opts.token) return null;
const t0 = DEBUG ? performance.now() : 0;
let res = sweepPack(items, c, cands[k], k);
let st = statsOf(res, c);
const filled = gapFill(res, res.unplaced, c, k);
if (filled.added.length) { res = filled; st = statsOf(res, c); }
if (DEBUG) console.log("[vox] sweep", cands[k].label, "ms", (performance.now() - t0).toFixed(1), "fill", (st.fill * 100).toFixed(1), "gapFill", filled.added.length);
if (!best || betterPlan(st, bestStats)) { best = res; bestStats = st; bestLabel = cands[k].label; }
history.push({ round: k + 1, best: bestStats.fill, cur: st.fill });
onRound(k + 1, cands.length, bestStats, st, history, cands[k].label);
await makeFrame();
}
// 逼近理论极限:差距仍大时补扫若干随机顺序
let boundVol = 0;
items.forEach(function (it) { boundVol += itemVolumeM3(it); });
const boxVol = (c.L * c.W * c.H) / 1e9;
const boundPct = boundVol / boxVol;
let extra = 0;
while (boundPct > 0 && bestStats.fill / boundPct < 0.97 && extra < 8) {
if (runToken !== opts.token) return null;
extra++;
const base = cands[(extra + 2) % cands.length];
const rng = mulberry32(7919 + extra * 131);
const shuffled = items.slice();
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
const t = shuffled[i]; shuffled[i] = shuffled[j]; shuffled[j] = t;
}
let res = sweepPack(shuffled, c, { label: "随机补扫", xAsc: base.xAsc, yAsc: base.yAsc, swap: base.swap, sort: "shuffle" }, extra);
let st = statsOf(res, c);
const filled = gapFill(res, res.unplaced, c, extra);
if (filled.added.length) { res = filled; st = statsOf(res, c); }
if (betterPlan(st, bestStats)) { best = res; bestStats = st; bestLabel = "随机补扫#" + extra; }
history.push({ round: history.length + 1, best: bestStats.fill, cur: st.fill });
onRound(history.length, cands.length + extra, bestStats, st, history, "补扫#" + extra);
await makeFrame();
}
return { best: best, bestStats: bestStats, history: history, label: bestLabel };
}
// ------------------------------------------------------------------- state
const state = {
containerKey: "40gp",
placed: [],
unplaced: [],
stats: null,
rounds: QUERY.has("rounds") ? Math.max(1, Number(QUERY.get("rounds")) || 16) : 16,
priority: new Set(),
excluded: new Set(),
selectedId: null,
display: "ghost",
history: [],
busy: false,
viewMode: "overview",
};
let runToken = 0;
function container() { return CONTAINERS[state.containerKey]; }
function itemsToPack() {
return CATALOG.filter(function (it) { return !state.excluded.has(it.id); });
}
// -------------------------------------------------------------------- three
const viewport = $("viewport");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x060a12);
const camera = new THREE.PerspectiveCamera(45, 1, 0.05, 300);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.rotateSpeed = 0.7;
controls.maxPolarAngle = Math.PI * 0.495;
controls.minDistance = 1.2;
controls.maxDistance = 70;
controls.autoRotateSpeed = 0.9;
// 左键平移、中键拖动旋转、滚轮缩放
controls.mouseButtons = { LEFT: THREE.MOUSE.PAN, MIDDLE: THREE.MOUSE.ROTATE, RIGHT: THREE.MOUSE.PAN };
// 触屏:单指平移、双指缩放/平移;旋转用右上角罗盘
controls.touches = { ONE: THREE.TOUCH.PAN, TWO: THREE.TOUCH.DOLLY_PAN };
controls.addEventListener("change", function () { dirty = true; });
scene.add(new THREE.HemisphereLight(0x9fdcff, 0x0a1420, 0.9));
const keyLight = new THREE.DirectionalLight(0xffffff, 0.8);
keyLight.position.set(10, 16, 7);
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x6ab6ff, 0.35);
fillLight.position.set(-8, 9, -9);
scene.add(fillLight);
const boxGroup = new THREE.Group();
scene.add(boxGroup);
const containerGroup = new THREE.Group();
scene.add(containerGroup);
let objects = [];
let camTween = null;
let dirty = true;
function markDirty() { dirty = true; }
// ------------------------------------------------------------------ 罗盘
const compassEl = $("compass");
const compassRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
compassRenderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
compassRenderer.setSize(108, 108);
compassRenderer.setClearColor(0x000000, 0);
compassEl.appendChild(compassRenderer.domElement);
const compassScene = new THREE.Scene();
const compassCamera = new THREE.PerspectiveCamera(40, 1, 0.1, 30);
const compassGroup = new THREE.Group();
compassScene.add(compassGroup);
function compassLabel(text, hex) {
const cv = document.createElement("canvas");
cv.width = 64;
cv.height = 64;
const ctx = cv.getContext("2d");
ctx.fillStyle = hex;
ctx.font = "700 44px system-ui, -apple-system, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 32, 34);
const tex = new THREE.CanvasTexture(cv);
const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, transparent: true, depthTest: false }));
sp.scale.set(0.42, 0.42, 1);
return sp;
}
function compassAxis(x, y, z, hex, label) {
const dir = new THREE.Vector3(x, y, z).normalize();
const geo = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, 0), dir.clone().multiplyScalar(1.0),
]);
compassGroup.add(new THREE.Line(geo, new THREE.LineBasicMaterial({ color: hex, transparent: true, opacity: 0.95 })));
const sp = compassLabel(label, "#" + hex.toString(16).padStart(6, "0"));
sp.position.copy(dir.clone().multiplyScalar(1.3));
compassGroup.add(sp);
}
compassAxis(1, 0, 0, 0xff6b6b, "X");
compassAxis(0, 1, 0, 0x6df5b1, "Y");
compassAxis(0, 0, 1, 0x56e1ff, "Z");
function updateCompass() {
const dir = camera.position.clone().sub(controls.target);
if (dir.lengthSq() < 1e-6) dir.set(1, 1, 1);
dir.normalize().multiplyScalar(4.4);
compassCamera.position.copy(dir);
compassCamera.up.set(0, 1, 0);
compassCamera.lookAt(0, 0, 0);
compassRenderer.render(compassScene, compassCamera);
}
function orbitBy(dx, dy) {
const target = controls.target;
const offset = camera.position.clone().sub(target);
const sph = new THREE.Spherical().setFromVector3(offset);
sph.theta -= dx * 0.012;
sph.phi -= dy * 0.012;
sph.phi = Math.max(0.08, Math.min(Math.PI - 0.08, sph.phi));
offset.setFromSpherical(sph);
camera.position.copy(target).add(offset);
camera.lookAt(target);
controls.update();
markDirty();
}
let compassDrag = null;
compassEl.addEventListener("pointerdown", function (ev) {
ev.preventDefault();
ev.stopPropagation();
if (compassEl.setPointerCapture) {
try { compassEl.setPointerCapture(ev.pointerId); } catch (e) {}
}
compassDrag = { x: ev.clientX, y: ev.clientY, moved: 0 };
});
compassEl.addEventListener("pointermove", function (ev) {
if (!compassDrag) return;
ev.preventDefault();
const dx = ev.clientX - compassDrag.x;
const dy = ev.clientY - compassDrag.y;
compassDrag.x = ev.clientX;
compassDrag.y = ev.clientY;
compassDrag.moved += Math.abs(dx) + Math.abs(dy);
orbitBy(dx, dy);
});
compassEl.addEventListener("pointerup", function (ev) {
if (!compassDrag) return;
ev.preventDefault();
const moved = compassDrag.moved;
compassDrag = null;
if (moved < 5) setView("overview");
});
compassEl.addEventListener("pointercancel", function () { compassDrag = null; });
// 兜底:Shift + 左键拖动也能旋转(没有中键的笔记本)
let shiftDrag = null;
renderer.domElement.addEventListener("pointerdown", function (ev) {
if (ev.button === 0 && ev.shiftKey) {
shiftDrag = { x: ev.clientX, y: ev.clientY };
ev.stopPropagation();
ev.preventDefault();
}
}, true);
renderer.domElement.addEventListener("pointermove", function (ev) {
if (!shiftDrag) return;
orbitBy(ev.clientX - shiftDrag.x, ev.clientY - shiftDrag.y);
shiftDrag.x = ev.clientX;
shiftDrag.y = ev.clientY;
}, true);
renderer.domElement.addEventListener("pointerup", function () { shiftDrag = null; }, true);
renderer.domElement.addEventListener("pointercancel", function () { shiftDrag = null; }, true);
function disposeAll(root) {
root.traverse(function (o) {
if (o.geometry) o.geometry.dispose();
if (o.material) {
const mats = Array.isArray(o.material) ? o.material : [o.material];
mats.forEach(function (m) { if (m.map) m.map.dispose(); m.dispose(); });
}
});
while (root.children.length) root.remove(root.children[0]);
}
function buildContainerBox() {
disposeAll(containerGroup);
const c = container();
const L = c.L / 1000, Wd = c.W / 1000, H = c.H / 1000;
const geo = new THREE.BoxGeometry(L, H, Wd);
const edges = new THREE.EdgesGeometry(geo);
geo.dispose();
const lines = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({
color: 0x4f92b8, transparent: true, opacity: 1,
}));
lines.position.set(L / 2, H / 2, Wd / 2);
containerGroup.add(lines);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(L, Wd),
new THREE.MeshBasicMaterial({ color: 0x0a1624 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.set(L / 2, -0.002, Wd / 2);
containerGroup.add(floor);
const pts = [];
for (let x = 0; x <= L + 1e-6; x += 1) pts.push(x, 0.002, 0, x, 0.002, Wd);
for (let z = 0; z <= Wd + 1e-6; z += 1) pts.push(0, 0.002, z, L, 0.002, z);
const g = new THREE.BufferGeometry();
g.setAttribute("position", new THREE.Float32BufferAttribute(pts, 3));
containerGroup.add(new THREE.LineSegments(g, new THREE.LineBasicMaterial({
color: 0x18324a, transparent: true, opacity: 0.85,
})));
const y1 = Math.min(H * 0.96, 2.28);
const p0 = [L, 0.02, 0.02], p1 = [L, y1, 0.02], p2 = [L, y1, Wd - 0.02], p3 = [L, 0.02, Wd - 0.02];
const dp = [];
[p0, p1, p1, p2, p2, p3, p3, p0].forEach(function (q) { dp.push(q[0], q[1], q[2]); });
const dg = new THREE.BufferGeometry();
dg.setAttribute("position", new THREE.Float32BufferAttribute(dp, 3));
containerGroup.add(new THREE.LineSegments(dg, new THREE.LineBasicMaterial({
color: 0xffb45a, transparent: true, opacity: 0.55,
})));
}
function makeLabel(text, color) {
const cv = document.createElement("canvas");
cv.width = 128;
cv.height = 128;
const ctx = cv.getContext("2d");
ctx.fillStyle = "rgba(6, 12, 20, 0.78)";
ctx.beginPath();
ctx.arc(64, 64, 44, 0, Math.PI * 2);
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = color;
ctx.stroke();
ctx.fillStyle = "#e9f5ff";
ctx.font = "600 56px system-ui, -apple-system, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 64, 68);
const tex = new THREE.CanvasTexture(cv);
const mat = new THREE.SpriteMaterial({ map: tex, transparent: true });
const sp = new THREE.Sprite(mat);
sp.scale.set(0.3, 0.3, 1);
return sp;
}
function buildBoxes() {
disposeAll(boxGroup);
objects = [];
if (!state.placed.length) { markDirty(); return; }
const mode = state.display;
const cube = (PITCH / 1000) * 0.98;
const P = PITCH / 1000;
state.placed.forEach(function (p, idx) {
const v = p.v;
const item = p.item;
const ex = v.nx * P, ey = v.nz * P, ez = v.ny * P;
const cx = (p.x + v.nx / 2) * P;
const cy = (p.z + v.nz / 2) * P;
const cz = (p.y + v.ny / 2) * P;
let mesh, mat;
if (item.fit === "box") {
mat = new THREE.MeshLambertMaterial({
color: item.color,
transparent: mode !== "solid",
opacity: mode === "solid" ? 0.96 : 0.55,
});
mesh = new THREE.Mesh(new THREE.BoxGeometry(ex, ey, ez), mat);
mesh.position.set(cx, cy, cz);
} else {
mat = new THREE.MeshLambertMaterial({ color: item.color, transparent: mode === "xray", opacity: mode === "xray" ? 0.28 : 1 });
mesh = new THREE.InstancedMesh(new THREE.BoxGeometry(1, 1, 1), mat, v.volume);
const arr = mesh.instanceMatrix.array;
const m4 = new THREE.Matrix4();
for (let t = 0, q = 0; t < v.cells.length; t += 3, q++) {
m4.makeScale(cube, cube, cube);
m4.setPosition(
(p.x + v.cells[t] + 0.5) * P,
(p.z + v.cells[t + 2] + 0.5) * P,
(p.y + v.cells[t + 1] + 0.5) * P
);
m4.toArray(arr, q * 16);
}
mesh.instanceMatrix.needsUpdate = true;
mesh.frustumCulled = false;
}
mesh.userData.index = idx;
boxGroup.add(mesh);
const bg = new THREE.BoxGeometry(ex, ey, ez);
const eg = new THREE.EdgesGeometry(bg);
bg.dispose();
const edgeMat = new THREE.LineBasicMaterial({ color: item.color, transparent: true, opacity: 0.22 });
const edges = new THREE.LineSegments(eg, edgeMat);
edges.position.set(cx, cy, cz);
boxGroup.add(edges);
const label = makeLabel(String(idx + 1), item.color);
label.position.set(cx, cy + ey / 2 + 0.22, cz);
label.visible = state.selectedId === item.id;
boxGroup.add(label);
objects.push({ p: p, mesh: mesh, edges: edges, label: label, mat: mat, edgeMat: edgeMat });
});
markDirty();
}
// ------------------------------------------------------------------- camera
const VIEWS = {
overview: function (m) { return { pos: [m.L * 1.16, m.H * 2.5, m.W * 6.4], target: [m.L * 0.5, m.H * 0.3, m.W * 0.5] }; },
top: function (m) { return { pos: [m.L * 0.5, m.H * 4.6, m.W * 0.52], target: [m.L * 0.5, 0, m.W * 0.5] }; },
side: function (m) { return { pos: [m.L * 0.5, m.H * 1.05, m.W * 5.2], target: [m.L * 0.5, m.H * 0.35, m.W * 0.5] }; },
door: function (m) { return { pos: [m.L * 1.5, m.H * 1.2, m.W * 0.5], target: [m.L * 0.72, m.H * 0.3, m.W * 0.5] }; },
flip: function (m) { return { pos: [-m.L * 0.16, m.H * 2.4, m.W * 6.0], target: [m.L * 0.5, m.H * 0.3, m.W * 0.5] }; },
};
function setView(name) {
const c = container();
const m = { L: c.L / 1000, H: c.H / 1000, W: c.W / 1000 };
const v = VIEWS[name](m);
camTween = {
t0: performance.now(),
fromPos: camera.position.clone(),
toPos: new THREE.Vector3().fromArray(v.pos),
fromTarget: controls.target.clone(),
toTarget: new THREE.Vector3().fromArray(v.target),
};
markDirty();
}
function focusOn(id) {
const obj = objects.find(function (o) { return o.p.item.id === id; });
if (!obj) return;
const p = obj.mesh.position;
const d = 3.2;
camTween = {
t0: performance.now(),
fromPos: camera.position.clone(),
toPos: new THREE.Vector3(p.x + d, p.y + d * 0.7, p.z + d),
fromTarget: controls.target.clone(),
toTarget: new THREE.Vector3(p.x, p.y, p.z),
};
}
function select(id) {
state.selectedId = id;
objects.forEach(function (o) {
const on = o.p.item.id === id;
o.mat.emissive.setHex(on ? 0x1d4a5e : 0x000000);
o.edgeMat.opacity = on ? 0.95 : 0.22;
o.label.visible = on;
o.label.scale.setScalar(on ? 0.42 : 0.3);
});
document.querySelectorAll(".pack-row").forEach(function (el) {
el.classList.toggle("active", el.dataset.id === id);
});
markDirty();
if (id) focusOn(id);
}
// ------------------------------------------------------------------ metrics
function floorCoverage() {
const c = container();
const nx = Math.ceil(c.L / PITCH), ny = Math.ceil(c.W / PITCH);
const grid = new Uint8Array(nx * ny);
state.placed.forEach(function (p) {
const v = p.v;
for (let i = 0; i < v.colX.length; i++) {
const x = p.x + v.colX[i], y = p.y + v.colY[i];
if (x >= 0 && x < nx && y >= 0 && y < ny) grid[x * ny + y] = 1;
}
});
let n = 0;
for (let i = 0; i < grid.length; i++) n += grid[i];
return n / (nx * ny);
}
function itemVolumeM3(item) {
if (item.fit === "box") {
const nx = Math.max(1, Math.round(item.dims[0] / PITCH));
const ny = Math.max(1, Math.round(item.dims[1] / PITCH));
const nz = Math.max(1, Math.round(item.dims[2] / PITCH));
return nx * ny * nz * (PITCH ** 3) / 1e9;
}
return item.volume * (PITCH ** 3) / 1e9;
}
function renderMetrics() {
const c = container();
const boxVol = (c.L * c.W * c.H) / 1e9;
const st = state.stats;
const fill = st ? st.fill : 0;
$("mFill").textContent = (fill * 100).toFixed(1);
$("mCount").textContent = state.placed.length + " / " + CATALOG.length;
$("mMass").textContent = Math.round(st ? st.mass : 0) + " kg";
$("mFloor").textContent = (state.placed.length ? floorCoverage() * 100 : 0).toFixed(1) + "%";
$("mTop").textContent = ((st ? st.topMm : 0) / 1000).toFixed(2) + " m";
$("mCog").textContent = st && st.mass ? (st.cog[2] / 1000).toFixed(2) + " m" : "—";
$("mPayload").textContent = ((st ? st.mass / c.payload : 0) * 100).toFixed(1) + "%";
$("mBox").textContent = boxVol.toFixed(1);
$("mVox").textContent = st
? st.voxels.toLocaleString() + " / " + st.gridVoxels.toLocaleString() +
"(" + ((st.voxels / st.gridVoxels) * 100).toFixed(1) + "%)"
: "—";
let totalCargo = 0;
CATALOG.forEach(function (it) { totalCargo += itemVolumeM3(it); });
$("mCargoRate").textContent = st && totalCargo > 0
? ((st.vol / totalCargo) * 100).toFixed(1) : "—";
const boundItems = itemsToPack();
let boundVol = 0;
boundItems.forEach(function (it) { boundVol += itemVolumeM3(it); });
const boundPct = boxVol > 0 ? boundVol / boxVol : 0;
$("mLimit").textContent = (boundPct * 100).toFixed(1);
const ratio = boundPct > 0 ? fill / boundPct : 0;
const warn = $("limitWarn");
if (state.busy || !state.placed.length || !boundPct) {
warn.hidden = true;
} else {
warn.hidden = false;
if (ratio >= 0.995) {
warn.className = "limit-warn ok";
warn.textContent = "✓ 已达理论上限的 " + (ratio * 100).toFixed(1) + "%(当前 " +
(fill * 100).toFixed(1) + "% / 上限 " + (boundPct * 100).toFixed(1) + "%)";
} else if (ratio >= 0.97) {
warn.className = "limit-warn mid";
warn.textContent = "接近理论上限:" + (fill * 100).toFixed(1) + "% / " +
(boundPct * 100).toFixed(1) + "%,还差 " + ((boundPct - fill) * 100).toFixed(1) + " 个百分点";
} else {
warn.className = "limit-warn";
warn.textContent = "⚠ 未达理论上限:当前 " + (fill * 100).toFixed(1) + "% / 上限 " +
(boundPct * 100).toFixed(1) + "%,差 " + ((boundPct - fill) * 100).toFixed(1) +
" 个百分点 —— 铺装仍有优化空间(已扫 " + state.history.length + " 组 + 缝隙补装)";
if (st.bigHigh) warn.textContent += " · 有 " + st.bigHigh + " 件大底面积货物位于高位,建议下沉";
}
}
$("mRot").textContent = st ? (st.free + " / " + st.axis + " / " + (st.count - st.free - st.axis)) : "—";
$("convFill").style.width = (fill * 100).toFixed(1) + "%";
$("convBest").textContent = (fill * 100).toFixed(1) + "%";
const pool = CATALOG.filter(function (it) {
return !state.placed.some(function (p) { return p.item.id === it.id; });
});
const full = pool.length > 0 && state.unplaced.length > 0;
$("convFill").parentNode.classList.toggle("full", full);
let stText = "IDLE";
if (state.busy) stText = "RUNNING";
else if (state.placed.length) stText = pool.length === 0 ? "ALL IN" : (full ? "FULL" : "PACKED");
$("loadState").textContent = stText;
$("loadState").style.color = stText === "ALL IN" ? "var(--green)"
: (stText === "FULL" ? "var(--amber)" : (stText === "RUNNING" ? "var(--cyan)" : ""));
if (state.busy) {
$("stateNote").textContent = "扫描铺装中:从箱底沿 X/Y 逐格试放所有剩余件,多种扫描方向同时比较…";
} else if (!state.placed.length) {
$("stateNote").textContent = "点「全部装箱」或「重新推理」开始";
} else if (pool.length === 0) {
$("stateNote").textContent = "全部货物已装入,剩余是箱内空隙。";
} else if (full) {
$("stateNote").textContent = "集装箱已满:" + state.unplaced.length + " 件装不下,留在待选。";
} else {
const totalCargo = CATALOG.reduce(function (s, it) { return s + itemVolumeM3(it); }, 0);
$("stateNote").textContent = "已装 " + state.placed.length + " 件;货物总量 " +
totalCargo.toFixed(1) + " m³,填充率理论上限 " + ((totalCargo / boxVol) * 100).toFixed(1) + "%";
}
if (state.excluded.size) $("stateNote").textContent += "(已取出 " + state.excluded.size + " 件)";
}
function drawChart(history) {
const cv = $("convChart");
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const w = cv.clientWidth || 280, h = cv.clientHeight || 92;
if (cv.width !== Math.round(w * dpr) || cv.height !== Math.round(h * dpr)) {
cv.width = Math.round(w * dpr);
cv.height = Math.round(h * dpr);
}
const ctx = cv.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
if (!history.length) return;
const padL = 30, padR = 6, padT = 8, padB = 14;
const iw = w - padL - padR, ih = h - padT - padB;
let maxV = 0.05;
history.forEach(function (d) { maxV = Math.max(maxV, d.best, d.cur); });
maxV *= 1.15;
ctx.strokeStyle = "rgba(45, 82, 116, 0.55)";
ctx.lineWidth = 1;
for (let i = 0; i <= 2; i++) {
const y = padT + (ih * i) / 2;
ctx.beginPath();
ctx.moveTo(padL, y);
ctx.lineTo(w - padR, y);
ctx.stroke();
}
const n = history.length;
const X = function (i) { return padL + (n === 1 ? iw / 2 : (iw * i) / (n - 1)); };
const Y = function (v) { return padT + ih - (v / maxV) * ih; };
ctx.strokeStyle = "rgba(110, 150, 190, 0.5)";
ctx.lineWidth = 1;
ctx.beginPath();
history.forEach(function (d, i) {
const x = X(i), y = Y(d.cur);
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
});
ctx.stroke();
ctx.strokeStyle = "#56e1ff";
ctx.lineWidth = 1.6;
ctx.beginPath();
history.forEach(function (d, i) {
const x = X(i), y = Y(d.best);
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
});
ctx.stroke();
ctx.fillStyle = "#56e1ff";
ctx.beginPath();
ctx.arc(X(n - 1), Y(history[n - 1].best), 2.5, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "#6f88a6";
ctx.font = "9px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "left";
ctx.fillText((maxV * 100).toFixed(0) + "%", 2, padT + 8);
ctx.fillText("0", 20, padT + ih);
ctx.textAlign = "right";
ctx.fillText("扫描 " + n + " 方向", w - padR, h - 3);
}
function onRound(round, rounds, best, cur, history, label) {
state.history = history;
$("convRound").textContent = "扫描 " + round + " / " + rounds +
(label ? "(" + label + ")" : "") + " · 当前 " + (cur.fill * 100).toFixed(1) + "%";
$("convFill").style.width = (best.fill * 100).toFixed(1) + "%";
$("convBest").textContent = (best.fill * 100).toFixed(1) + "%";
$("mFill").textContent = (best.fill * 100).toFixed(1);
drawChart(history);
}
// ---------------------------------------------------------------------- toast
let toastTimer = null;
function toast(msg, ok) {
const el = $("toast");
el.textContent = msg;
el.hidden = false;
el.classList.toggle("ok", !!ok);
requestAnimationFrame(function () { el.classList.add("show"); });
if (toastTimer) clearTimeout(toastTimer);
toastTimer = setTimeout(function () {
el.classList.remove("show");
setTimeout(function () { el.hidden = true; }, 250);
}, 3600);
}
// ------------------------------------------------------------------------ UI
function itemBadges(item) {
return (item.upright ? "正向" : "自由角") + " · 堆码 " + item.stackCount +
" · 承重 " + (item.capacityKg > 0 ? item.capacityKg + "kg" : "不可压") +
" · " + (item.fit === "box" ? "长方体" : "体素");
}
function renderPool() {
const list = $("poolList");
list.innerHTML = "";
const placedIds = new Set(state.placed.map(function (p) { return p.item.id; }));
const failedIds = new Set(state.unplaced.map(function (it) { return it.id; }));
const pool = CATALOG.filter(function (it) { return !placedIds.has(it.id); });
$("poolCount").textContent = pool.length ? pool.length + " 件待选" : "空";
if (!pool.length) {
const div = document.createElement("div");
div.className = "pool-empty";
div.textContent = "全部零件都已装箱";
list.appendChild(div);
return;
}
pool.forEach(function (item) {
const blocked = failedIds.has(item.id);
const row = document.createElement("button");
row.type = "button";
row.className = "pool-row" + (blocked ? " blocked" : "");
row.innerHTML =
'<span class="pool-swatch" style="--swatch:' + item.color + '"></span>' +
'<span class="pool-main">' +
'<span class="pool-name">' + item.name + '</span>' +
'<span class="pool-meta">' + item.dims.join("×") + " mm · " +
Math.round(item.mass) + " kg · " + itemBadges(item) +
(blocked ? " · 装不下" : "") +
'</span>' +
'</span>' +
'<span class="pool-add">+ 装箱</span>';
row.dataset.id = item.id;
row.addEventListener("click", function (ev) { ev.stopPropagation(); select(item.id); });
row.addEventListener("contextmenu", function (ev) { openCtx(ev, item.id); });
row.querySelector(".pool-add").addEventListener("click", function (ev) {
ev.stopPropagation();
addItem(item.id);
});
list.appendChild(row);
});
}
function renderPlaced() {
const list = $("placedList");
list.innerHTML = "";
if (!state.placed.length) {
const div = document.createElement("div");
div.className = "pack-empty";
div.textContent = "还没有装入任何货物";
list.appendChild(div);
return;
}
state.placed.forEach(function (p, idx) {
const v = p.v;
const row = document.createElement("button");
row.type = "button";
row.className = "pack-row" + (state.selectedId === p.item.id ? " active" : "");
row.dataset.id = p.item.id;
row.innerHTML =
'<span class="pack-order">#' + (idx + 1) + '</span>' +
'<span class="pack-swatch" style="--swatch:' + p.item.color + '"></span>' +
'<span class="pack-main">' +
'<span class="pack-name">' + p.item.name + '</span>' +
'<span class="pack-meta">' +
v.label + " · " + (v.nx * PITCH) + "×" + (v.ny * PITCH) + "×" + (v.nz * PITCH) + " · " +
"x " + (p.x * PITCH / 1000).toFixed(2) +
" y " + (p.y * PITCH / 1000).toFixed(2) +
" z " + (p.z * PITCH / 1000).toFixed(2) +
" · 支撑 " + Math.round(p.support * 100) + "%" +
'</span>' +
'</span>' +
'<span class="pack-badges"><span class="badge remove" data-remove="' + p.item.id + '">移除</span></span>';
row.addEventListener("click", function (ev) {
const rm = ev.target.closest("[data-remove]");
if (rm) { ev.stopPropagation(); removeItem(rm.dataset.remove); return; }
select(p.item.id);
});
row.addEventListener("contextmenu", function (ev) { openCtx(ev, p.item.id); });
list.appendChild(row);
});
}
function renderAll() {
renderMetrics();
renderPool();
renderPlaced();
drawChart(state.history);
}
// ------------------------------------------------------------------- actions
function setBusy(on) {
state.busy = on;
["packAll", "optimize", "clearAll", "exportCsv"].forEach(function (id) { $(id).disabled = on; });
document.querySelectorAll("#containerSeg button, #roundsSeg button").forEach(function (b) { b.disabled = on; });
if (on) $("loadState").textContent = "RUNNING";
}
async function runOptimize(opts) {
if (state.busy) return;
const token = ++runToken;
setBusy(true);
state.history = [];
renderMetrics();
drawChart([]);
const items = itemsToPack();
const rounds = opts.rounds || state.rounds;
const result = await runSweeps(items, { count: rounds, token: token });
if (token !== runToken) return;
setBusy(false);
if (!result) return;
commit(result.best, result.bestStats, opts);
}
function commit(res, stats, opts) {
state.placed = res.placed;
state.unplaced = res.unplaced;
state.stats = stats;
state.priority.clear();
buildBoxes();
renderAll();
markDirty();
if (opts && opts.silent) return;
const pool = CATALOG.length - res.placed.length;
if (opts && opts.reason === "remove") {
toast("已取出「" + opts.name + "」,重新推演:" + res.placed.length + " 件,填充率 " +
(stats.fill * 100).toFixed(1) + "%", false);
} else if (pool === 0) {
toast("全部 " + res.placed.length + " 件装入,填充率 " + (stats.fill * 100).toFixed(1) + "%", true);
} else {
toast("推理完成:装入 " + res.placed.length + " / " + CATALOG.length + " 件,填充率 " +
(stats.fill * 100).toFixed(1) + "%;" + pool + " 件装不下,留在待选", false);
}
}
async function addItem(id) {
if (state.busy) { toast("正在推理,稍等", false); return; }
state.excluded.delete(id);
state.priority.add(id);
await runOptimize({ rounds: Math.max(4, Math.min(8, state.rounds)), reason: "add", name: ITEM_BY_ID[id].name });
}
async function removeItem(id) {
if (state.busy) return;
state.excluded.add(id);
state.priority.delete(id);
await runOptimize({ rounds: Math.max(4, Math.min(8, state.rounds)), reason: "remove", name: ITEM_BY_ID[id].name });
}
async function packAll() {
if (state.busy) return;
state.excluded.clear();
state.priority.clear();
await runOptimize({ rounds: 4, reason: "pack" });
}
async function reoptimize() {
if (state.busy) return;
await runOptimize({ rounds: state.rounds, reason: "optimize" });
}
function clearAll() {
if (state.busy) return;
runToken++;
state.placed = [];
state.unplaced = [];
state.stats = null;
state.history = [];
state.excluded.clear();
state.priority.clear();
state.selectedId = null;
buildBoxes();
renderAll();
markDirty();
toast("集装箱已清空", false);
}
function exportCsv() {
if (!state.placed.length) { toast("还没有装箱结果", false); return; }
const c = container();
const rows = [["序号", "零件", "拟合", "尺寸mm", "朝向", "x_mm", "y_mm", "z_mm", "支撑%", "质量kg", "堆码个数"]];
state.placed.forEach(function (p, i) {
rows.push([
i + 1, p.item.name, p.item.fit === "box" ? "长方体" : "体素",
[p.v.nx * PITCH, p.v.ny * PITCH, p.v.nz * PITCH].join("×"),
p.v.label,
Math.round(p.x * PITCH), Math.round(p.y * PITCH), Math.round(p.z * PITCH),
Math.round(p.support * 100), p.item.mass, p.item.stackCount,
]);
});
const st = state.stats;
rows.push([]);
rows.push(["合计", "件数 " + state.placed.length, "填充率 " + (st.fill * 100).toFixed(2) + "%",
"体积 " + st.vol.toFixed(3) + " m³", "总重 " + Math.round(st.mass) + " kg",
"重心mm " + st.cog.map(function (v) { return Math.round(v); }).join("/")]);
const csv = "\uFEFF" + rows.map(function (r) { return r.join(","); }).join("\r\n");
const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "装箱清单-" + c.label.replace(/'/g, "") + ".csv";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function () { URL.revokeObjectURL(url); }, 3000);
toast("装箱清单已导出(" + state.placed.length + " 行)", true);
}
// ------------------------------------------------------------------ 右键菜单
const ctxMenu = $("ctxMenu");
let ctxItemId = null;
function closeCtx() {
ctxMenu.hidden = true;
ctxItemId = null;
}
function openCtx(ev, id) {
ev.preventDefault();
ev.stopPropagation();
const item = ITEM_BY_ID[id];
if (!item) return;
ctxItemId = id;
ctxMenu.innerHTML =
"<h4>" + item.name + " · 参数</h4>" +
'<div class="ctx-row"><span>正向锁定</span><input type="checkbox" id="ctxUpright"' +
(item.upright ? " checked" : "") + " /></div>" +
'<div class="ctx-row"><span>堆码个数</span><input type="number" id="ctxStack" min="1" max="9" step="1" value="' +
item.stackCount + '" /></div>' +
'<div class="ctx-row"><span>承重上限 kg</span><input type="number" id="ctxCap" min="0" max="9999" step="50" value="' +
item.capacityKg + '" /></div>' +
'<div class="ctx-row"><span>拟合方式</span><select id="ctxFit">' +
'<option value="box"' + (item.fit === "box" ? " selected" : "") + ">长方体</option>" +
'<option value="voxel"' + (item.fit === "voxel" ? " selected" : "") + ">小立方体</option>" +
"</select></div>" +
'<div class="ctx-row"><span>自身重量 kg</span><input type="number" id="ctxMass" min="1" max="5000" step="10" value="' +
Math.round(item.mass) + '" /></div>' +
'<div class="ctx-actions"><button id="ctxApply" class="primary">应用并重推</button>' +
'<button id="ctxCancel">取消</button></div>';
ctxMenu.hidden = false;
const w = 258;
const h = ctxMenu.offsetHeight;
let left = ev.clientX + 8;
let top = ev.clientY + 8;
if (left + w > window.innerWidth - 8) left = window.innerWidth - w - 8;
if (top + h > window.innerHeight - 8) top = window.innerHeight - h - 8;
ctxMenu.style.left = Math.max(8, left) + "px";
ctxMenu.style.top = Math.max(8, top) + "px";
$("ctxCancel").addEventListener("click", closeCtx);
$("ctxApply").addEventListener("click", applyCtx);
select(id);
}
function applyCtx() {
const item = ITEM_BY_ID[ctxItemId];
if (!item) { closeCtx(); return; }
item.upright = $("ctxUpright").checked;
item.stackCount = Math.max(1, Math.min(9, Math.round(Number($("ctxStack").value) || 1)));
item.capacityKg = Math.max(0, Math.min(9999, Math.round(Number($("ctxCap").value) || 0)));
item.fit = $("ctxFit").value === "voxel" ? "voxel" : "box";
item.mass = Math.max(1, Math.min(5000, Math.round(Number($("ctxMass").value) || 1)));
item.vAxis = null;
item.vRandom = null;
closeCtx();
toast("已更新「" + item.name + "」:正向 " + (item.upright ? "锁定" : "自由") +
" · 堆码 " + item.stackCount + " · 承重 " + item.capacityKg + " kg · " +
(item.fit === "box" ? "长方体" : "体素") + " · 自重 " + item.mass + " kg,重新扫描…", false);
runOptimize({ rounds: state.rounds, reason: "param" });
}
document.addEventListener("click", function (ev) {
if (!ctxMenu.hidden && !ctxMenu.contains(ev.target)) closeCtx();
});
document.addEventListener("keydown", function (ev) {
if (ev.key === "Escape") closeCtx();
});
// -------------------------------------------------------------------- events
function buildSegments() {
const cs = $("containerSeg");
Object.keys(CONTAINERS).forEach(function (key) {
const c = CONTAINERS[key];
const b = document.createElement("button");
b.type = "button";
b.dataset.key = c.key;
b.textContent = c.label;
b.title = c.note + " · 内尺寸 " + c.L + "×" + c.W + "×" + c.H + " mm";
b.addEventListener("click", function () {
if (state.busy) return;
state.containerKey = c.key;
$("containerOut").textContent = c.L + " × " + c.W + " × " + c.H + " mm";
document.querySelectorAll("#containerSeg button").forEach(function (q) {
q.classList.toggle("active", q.dataset.key === c.key);
});
$("genAt").textContent = "mixed box / voxel · " + c.label;
buildContainerBox();
setView(state.viewMode);
runOptimize({ rounds: state.rounds, reason: "container" });
});
cs.appendChild(b);
});
const rs = $("roundsSeg");
rs.querySelectorAll("button").forEach(function (b) {
b.addEventListener("click", function () {
if (state.busy) return;
state.rounds = Number(b.dataset.rounds);
rs.querySelectorAll("button").forEach(function (q) { q.classList.toggle("active", q === b); });
$("roundsOut").textContent = b.textContent + "(" + state.rounds + " 组扫描)";
});
});
$("roundsOut").textContent = "标准(16 组扫描)";
}
$("packAll").addEventListener("click", packAll);
$("optimize").addEventListener("click", reoptimize);
$("clearAll").addEventListener("click", clearAll);
$("exportCsv").addEventListener("click", exportCsv);
document.querySelectorAll(".cam-buttons button[data-view]").forEach(function (btn) {
btn.addEventListener("click", function () {
document.querySelectorAll(".cam-buttons button[data-view]").forEach(function (b) { b.classList.remove("active"); });
btn.classList.add("active");
state.viewMode = btn.dataset.view;
setView(btn.dataset.view);
});
});
document.querySelectorAll("#displaySeg button").forEach(function (btn) {
btn.addEventListener("click", function () {
document.querySelectorAll("#displaySeg button").forEach(function (b) { b.classList.remove("active"); });
btn.classList.add("active");
state.display = btn.dataset.display;
buildBoxes();
});
});
$("spin").addEventListener("click", function () {
controls.autoRotate = !controls.autoRotate;
$("spin").classList.toggle("spinning", controls.autoRotate);
markDirty();
});
$("recenter").addEventListener("click", function () {
const c = container();
const target = new THREE.Vector3(c.L / 2000, c.H / 3000, c.W / 2000);
const off = camera.position.clone().sub(controls.target);
camTween = {
t0: performance.now(),
fromPos: camera.position.clone(),
toPos: target.clone().add(off),
fromTarget: controls.target.clone(),
toTarget: target,
};
markDirty();
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let downPos = null;
renderer.domElement.addEventListener("pointerdown", function (ev) { downPos = [ev.clientX, ev.clientY]; });
renderer.domElement.addEventListener("pointerup", function (ev) {
if (!downPos) return;
const moved = Math.hypot(ev.clientX - downPos[0], ev.clientY - downPos[1]);
downPos = null;
if (moved > 5) return;
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((ev.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((ev.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(objects.map(function (o) { return o.mesh; }), false);
if (hits.length) select(state.placed[hits[0].object.userData.index].item.id);
else select(null);
});
function resize() {
const w = viewport.clientWidth, h = viewport.clientHeight;
if (!w || !h) return;
renderer.setSize(w, h);
camera.aspect = w / h;
camera.updateProjectionMatrix();
drawChart(state.history);
markDirty();
}
window.addEventListener("resize", resize);
if (window.ResizeObserver) new ResizeObserver(resize).observe(viewport);
function tick() {
requestAnimationFrame(tick);
let tweening = false;
if (camTween) {
const t = Math.min(1, (performance.now() - camTween.t0) / 520);
const e = 1 - Math.pow(1 - t, 3);
camera.position.lerpVectors(camTween.fromPos, camTween.toPos, e);
controls.target.lerpVectors(camTween.fromTarget, camTween.toTarget, e);
if (t >= 1) camTween = null;
tweening = true;
}
if (dirty || tweening || controls.autoRotate) {
dirty = false;
controls.update();
renderer.render(scene, camera);
updateCompass();
}
}
// ---------------------------------------------------------------------- init
window.__vox = {
Packer: Packer,
variantsForRound: variantsForRound,
packOrder: packOrder,
sweepPack: sweepPack,
sweepOrders: sweepCandidates,
sweepCandidates: sweepCandidates,
gapFill: gapFill,
fitAt: fitAt,
runSweeps: runSweeps,
statsOf: statsOf,
CATALOG: CATALOG,
ITEM_BY_ID: ITEM_BY_ID,
container: container,
state: state,
camera: camera,
controls: controls,
};
buildSegments();
const c0 = container();
$("containerOut").textContent = c0.L + " × " + c0.W + " × " + c0.H + " mm";
document.querySelectorAll("#containerSeg button").forEach(function (b) {
b.classList.toggle("active", b.dataset.key === state.containerKey);
});
$("genAt").textContent = "mixed box / voxel · " + c0.label;
if (QUERY.has("rounds")) $("roundsOut").textContent = "自定义(" + state.rounds + " 组扫描)";
buildContainerBox();
resize();
setView("overview");
tick();
updateCompass();
renderAll();
if (!QUERY.has("norun")) runOptimize({ rounds: state.rounds, reason: "init" });
})();