Agent-led CAD-drawing → 3D web showcase pipeline. Inspects CAD reports, maps layers/floors, extracts a normalized building spec (with block-probed glazing and audit gates), builds Blender/trimesh GLB variants, and assembles a Three.js web viewer. Includes XREF-shell detection and a regression test. Large inputs/outputs (work/, outputs/, source_cad/, renders) are gitignored. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
432 lines
14 KiB
JavaScript
432 lines
14 KiB
JavaScript
import * as THREE from "three";
|
|
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
|
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
|
|
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
|
|
|
|
const canvas = document.querySelector("#scene");
|
|
const loading = document.querySelector("#loading");
|
|
const loadingFill = document.querySelector("#loading-fill");
|
|
const loadingText = document.querySelector("#loading-text");
|
|
const floorControls = document.querySelector("#floor-controls");
|
|
const categoryControls = document.querySelector("#category-controls");
|
|
const downloadControls = document.querySelector("#download-controls");
|
|
const stats = document.querySelector("#stats");
|
|
const inspect = document.querySelector("#inspect");
|
|
const explodeInput = document.querySelector("#explode");
|
|
const explodeValue = document.querySelector("#explode-value");
|
|
const sectionInput = document.querySelector("#section");
|
|
const sectionValue = document.querySelector("#section-value");
|
|
const autoRotateButton = document.querySelector("#auto-rotate");
|
|
|
|
const preferredCategoryOrder = [
|
|
"slab",
|
|
"roof",
|
|
"walls",
|
|
"glazing",
|
|
"columns",
|
|
"beams",
|
|
"railings",
|
|
"doors",
|
|
"detail_lines",
|
|
"floor_lines",
|
|
"grid",
|
|
];
|
|
const objectRegistry = [];
|
|
const floorGroups = new Map();
|
|
const materialByCategory = new Map();
|
|
const state = {
|
|
floors: {},
|
|
categories: {},
|
|
autoRotate: false,
|
|
selected: null,
|
|
bounds: null,
|
|
};
|
|
|
|
const scene = new THREE.Scene();
|
|
scene.background = new THREE.Color(0x272a2d);
|
|
|
|
const renderer = new THREE.WebGLRenderer({
|
|
canvas,
|
|
antialias: true,
|
|
alpha: false,
|
|
preserveDrawingBuffer: true,
|
|
});
|
|
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
|
renderer.setSize(window.innerWidth, window.innerHeight);
|
|
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
|
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
|
renderer.toneMappingExposure = 1.2;
|
|
renderer.shadowMap.enabled = true;
|
|
renderer.localClippingEnabled = true;
|
|
|
|
const camera = new THREE.PerspectiveCamera(36, window.innerWidth / window.innerHeight, 0.1, 1000);
|
|
camera.up.set(0, 1, 0); // glTF-standard Y-up; required so OrbitControls.maxPolarAngle allows bird's-eye angles
|
|
const controls = new OrbitControls(camera, renderer.domElement);
|
|
controls.enableDamping = true;
|
|
controls.dampingFactor = 0.08;
|
|
controls.screenSpacePanning = true;
|
|
controls.maxPolarAngle = Math.PI * 0.49;
|
|
|
|
scene.add(new THREE.HemisphereLight(0xf7f3e8, 0x20262a, 1.45));
|
|
|
|
const keyLight = new THREE.DirectionalLight(0xffffff, 3.6);
|
|
keyLight.position.set(-45, -62, 85);
|
|
keyLight.castShadow = true;
|
|
scene.add(keyLight);
|
|
|
|
const fillLight = new THREE.DirectionalLight(0x9fd4ff, 1.15);
|
|
fillLight.position.set(80, 55, 48);
|
|
scene.add(fillLight);
|
|
|
|
const modelRoot = new THREE.Group();
|
|
modelRoot.name = "cad_web_model";
|
|
scene.add(modelRoot);
|
|
|
|
const raycaster = new THREE.Raycaster();
|
|
const pointer = new THREE.Vector2();
|
|
const sectionPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0), 9999); // Y-up: clip above section height on Y
|
|
|
|
const metadata = await fetch("./model_metadata.json?v={{BUILD}}").then((response) => response.json());
|
|
const categoryOrder = preferredCategoryOrder.filter((key) => metadata.categories?.[key]);
|
|
document.querySelector("#project-name").textContent = metadata.project?.name || "CAD 建筑模型";
|
|
document.querySelector("#project-description").textContent = metadata.project?.description || "Web 展示模型";
|
|
initialiseState(metadata);
|
|
buildInterface(metadata);
|
|
|
|
const loader = new GLTFLoader();
|
|
const dracoLoader = new DRACOLoader();
|
|
dracoLoader.setDecoderPath("./node_modules/three/examples/jsm/libs/draco/"); // shipped with three; works offline
|
|
loader.setDRACOLoader(dracoLoader);
|
|
loader.load(
|
|
"./model.glb?v={{BUILD}}",
|
|
(gltf) => {
|
|
ingestModel(gltf.scene, metadata);
|
|
applyExplode(Number(explodeInput.value));
|
|
const maxZ = Math.max(6, Math.ceil((metadata.bounds?.max_z || 12) + 2));
|
|
sectionInput.max = String(maxZ);
|
|
sectionInput.value = String(maxZ);
|
|
sectionValue.textContent = "关闭";
|
|
applySection(maxZ);
|
|
fitCamera("overview");
|
|
updateStats();
|
|
updateVisibility();
|
|
loading.classList.add("hidden");
|
|
},
|
|
(event) => {
|
|
if (!event.total) return;
|
|
const pct = Math.max(8, Math.min(100, Math.round((event.loaded / event.total) * 100)));
|
|
loadingFill.style.width = `${pct}%`;
|
|
loadingText.textContent = `加载模型 ${pct}%`;
|
|
},
|
|
(error) => {
|
|
loadingText.textContent = "模型加载失败";
|
|
console.error(error);
|
|
},
|
|
);
|
|
|
|
if (window.lucide) window.lucide.createIcons();
|
|
|
|
function initialiseState(meta) {
|
|
const disabledCategories = new Set(meta.viewer_defaults?.disabled_categories || []);
|
|
for (const floor of meta.floors || []) state.floors[floor.key] = true;
|
|
for (const key of categoryOrder) state.categories[key] = !disabledCategories.has(key);
|
|
}
|
|
|
|
function buildInterface(meta) {
|
|
floorControls.replaceChildren(
|
|
...(meta.floors || []).map((floor) =>
|
|
createToggle({
|
|
key: floor.key,
|
|
label: floor.key,
|
|
checked: state.floors[floor.key],
|
|
onChange: (checked) => {
|
|
state.floors[floor.key] = checked;
|
|
updateVisibility();
|
|
},
|
|
}),
|
|
),
|
|
);
|
|
|
|
categoryControls.replaceChildren(
|
|
...categoryOrder.map((key) =>
|
|
createToggle({
|
|
key,
|
|
label: meta.categories[key].label || key,
|
|
color: meta.categories[key].color,
|
|
checked: state.categories[key],
|
|
onChange: (checked) => {
|
|
state.categories[key] = checked;
|
|
updateVisibility();
|
|
},
|
|
}),
|
|
),
|
|
);
|
|
|
|
buildDownloadControls(meta);
|
|
|
|
explodeInput.addEventListener("input", () => {
|
|
const value = Number(explodeInput.value);
|
|
explodeValue.textContent = `${value.toFixed(value % 1 ? 1 : 0)}m`;
|
|
applyExplode(value);
|
|
});
|
|
|
|
sectionInput.addEventListener("input", () => applySection(Number(sectionInput.value)));
|
|
|
|
document.querySelectorAll("[data-preset]").forEach((button) => {
|
|
button.addEventListener("click", () => fitCamera(button.dataset.preset));
|
|
});
|
|
|
|
document.querySelector("#reset-view").addEventListener("click", () => {
|
|
explodeInput.value = "0";
|
|
explodeValue.textContent = "0m";
|
|
sectionInput.value = sectionInput.max;
|
|
sectionValue.textContent = "关闭";
|
|
applyExplode(0);
|
|
applySection(Number(sectionInput.max));
|
|
fitCamera("overview");
|
|
});
|
|
|
|
autoRotateButton.addEventListener("click", () => {
|
|
state.autoRotate = !state.autoRotate;
|
|
autoRotateButton.classList.toggle("active", state.autoRotate);
|
|
controls.autoRotate = state.autoRotate;
|
|
controls.autoRotateSpeed = 0.8;
|
|
});
|
|
|
|
document.querySelector("#snapshot").addEventListener("click", downloadSnapshot);
|
|
}
|
|
|
|
function buildDownloadControls(meta) {
|
|
const variants = meta.model_variants?.length
|
|
? meta.model_variants
|
|
: [{ key: "current", label: "当前 GLB", file: meta.files?.glb || "model.glb" }];
|
|
downloadControls.replaceChildren(
|
|
...variants.map((variant) => {
|
|
const link = document.createElement("a");
|
|
link.className = "download-link";
|
|
link.href = variant.file;
|
|
link.download = variant.file.split("/").pop() || "model.glb";
|
|
link.title = variant.description || variant.label || variant.key;
|
|
link.textContent = variant.label || variant.key;
|
|
return link;
|
|
}),
|
|
);
|
|
}
|
|
|
|
function createToggle({ key, label, color, checked, onChange }) {
|
|
const root = document.createElement("label");
|
|
root.className = "toggle";
|
|
root.dataset.key = key;
|
|
const input = document.createElement("input");
|
|
input.type = "checkbox";
|
|
input.checked = checked;
|
|
input.addEventListener("change", () => onChange(input.checked));
|
|
root.append(input);
|
|
if (color) {
|
|
const swatch = document.createElement("span");
|
|
swatch.className = "swatch";
|
|
swatch.style.background = color;
|
|
root.append(swatch);
|
|
}
|
|
const text = document.createElement("span");
|
|
text.textContent = label;
|
|
root.append(text);
|
|
return root;
|
|
}
|
|
|
|
function ingestModel(gltfScene, meta) {
|
|
for (const floor of meta.floors || []) {
|
|
const group = new THREE.Group();
|
|
group.name = floor.key;
|
|
floorGroups.set(floor.key, group);
|
|
modelRoot.add(group);
|
|
}
|
|
|
|
gltfScene.updateMatrixWorld(true);
|
|
const meshes = [];
|
|
gltfScene.traverse((node) => {
|
|
if (node.isMesh) meshes.push(node);
|
|
});
|
|
|
|
for (const mesh of meshes) {
|
|
const parsed = parseObjectName(mesh.name);
|
|
mesh.updateWorldMatrix(true, false);
|
|
mesh.geometry.applyMatrix4(mesh.matrixWorld);
|
|
mesh.position.set(0, 0, 0);
|
|
mesh.rotation.set(0, 0, 0);
|
|
mesh.scale.set(1, 1, 1);
|
|
mesh.updateMatrix();
|
|
if (!parsed || !floorGroups.has(parsed.floor)) {
|
|
modelRoot.add(mesh);
|
|
continue;
|
|
}
|
|
mesh.castShadow = !["grid", "floor_lines", "detail_lines", "glazing"].includes(parsed.category);
|
|
mesh.receiveShadow = true;
|
|
mesh.userData.floor = parsed.floor;
|
|
mesh.userData.category = parsed.category;
|
|
mesh.userData.label = labelForObject(parsed);
|
|
if (categoryOrder.includes(parsed.category)) {
|
|
mesh.material = materialForCategory(parsed.category, meta);
|
|
addEdges(mesh, parsed.category);
|
|
objectRegistry.push(mesh);
|
|
}
|
|
floorGroups.get(parsed.floor).add(mesh);
|
|
}
|
|
|
|
state.bounds = new THREE.Box3().setFromObject(modelRoot);
|
|
}
|
|
|
|
function parseObjectName(name) {
|
|
const match = name.match(/^(.+)__(.+)$/);
|
|
if (!match) return null;
|
|
// strip Blender's auto de-dup suffix (e.g. "1F__slab.001" -> category "slab")
|
|
const category = match[2].replace(/\.\d+$/, "");
|
|
return { floor: match[1], category };
|
|
}
|
|
|
|
function labelForObject({ floor, category }) {
|
|
return `${floor} ${metadata.categories?.[category]?.label || category}`;
|
|
}
|
|
|
|
function materialForCategory(category, meta) {
|
|
if (materialByCategory.has(category)) return materialByCategory.get(category);
|
|
const color = new THREE.Color(meta.categories[category]?.color || "#cccccc");
|
|
const opacity =
|
|
category === "slab"
|
|
? 0.64
|
|
: category === "roof"
|
|
? 0.95
|
|
: category === "glazing"
|
|
? 0.36
|
|
: category === "detail_lines"
|
|
? 0.72
|
|
: category === "grid" || category === "floor_lines"
|
|
? 0.88
|
|
: category === "doors"
|
|
? 0.90
|
|
: 1;
|
|
const material = new THREE.MeshStandardMaterial({
|
|
color,
|
|
transparent: opacity < 1,
|
|
opacity,
|
|
depthWrite: category === "slab" ? true : opacity >= 0.8,
|
|
roughness: 0.74,
|
|
metalness: 0.02,
|
|
side: category === "slab" || category === "roof" ? THREE.DoubleSide : THREE.FrontSide,
|
|
clippingPlanes: [sectionPlane],
|
|
});
|
|
materialByCategory.set(category, material);
|
|
return material;
|
|
}
|
|
|
|
function addEdges(mesh, category) {
|
|
if (["grid", "floor_lines", "detail_lines", "glazing"].includes(category)) return;
|
|
const edges = new THREE.LineSegments(
|
|
new THREE.EdgesGeometry(mesh.geometry, 35),
|
|
new THREE.LineBasicMaterial({ color: 0x101214, transparent: true, opacity: 0.28 }),
|
|
);
|
|
mesh.add(edges);
|
|
}
|
|
|
|
function applyExplode(distance) {
|
|
const floors = metadata.floors || [];
|
|
for (const [index, floor] of floors.entries()) {
|
|
const group = floorGroups.get(floor.key);
|
|
if (group) group.position.y = index * distance; // Y-up: explode floors along Y
|
|
}
|
|
updateStats();
|
|
}
|
|
|
|
function applySection(height) {
|
|
const max = Number(sectionInput.max);
|
|
sectionPlane.constant = height >= max ? 9999 : height;
|
|
sectionValue.textContent = height >= max ? "关闭" : `${height.toFixed(2)}m`;
|
|
}
|
|
|
|
function updateVisibility() {
|
|
for (const mesh of objectRegistry) {
|
|
mesh.visible = Boolean(state.floors[mesh.userData.floor] && state.categories[mesh.userData.category]);
|
|
}
|
|
for (const [floorKey, group] of floorGroups.entries()) {
|
|
group.visible = Boolean(state.floors[floorKey]);
|
|
}
|
|
updateStats();
|
|
}
|
|
|
|
function updateStats() {
|
|
const activeFloors = Object.values(state.floors).filter(Boolean).length;
|
|
const activeCategories = Object.values(state.categories).filter(Boolean).length;
|
|
const visibleMeshes = objectRegistry.filter((mesh) => mesh.visible !== false);
|
|
const vertices = visibleMeshes.reduce((sum, mesh) => sum + mesh.geometry.attributes.position.count, 0);
|
|
stats.innerHTML = "";
|
|
for (const item of [
|
|
["楼层", `${activeFloors}/${(metadata.floors || []).length}`],
|
|
["构件", `${activeCategories}/${categoryOrder.length}`],
|
|
["顶点", vertices.toLocaleString("zh-CN")],
|
|
]) {
|
|
const cell = document.createElement("div");
|
|
cell.innerHTML = `<dt>${item[0]}</dt><dd>${item[1]}</dd>`;
|
|
stats.append(cell);
|
|
}
|
|
}
|
|
|
|
function fitCamera(preset) {
|
|
const box = new THREE.Box3().setFromObject(modelRoot);
|
|
state.bounds = box;
|
|
const center = box.getCenter(new THREE.Vector3());
|
|
const size = box.getSize(new THREE.Vector3());
|
|
const maxSize = Math.max(size.x, size.y, size.z, 1);
|
|
if (preset === "top") {
|
|
camera.position.set(center.x, center.y + maxSize * 1.45, center.z);
|
|
} else if (preset === "side") {
|
|
camera.position.set(center.x, center.y + maxSize * 0.18, center.z + maxSize * 1.35);
|
|
} else {
|
|
// bird's-eye 3/4 aerial (~55° looking down); Y is up (glTF standard)
|
|
const d = maxSize * 1.4;
|
|
const L = Math.hypot(0.55, 1.0, 0.7);
|
|
camera.position.set(center.x - (0.55 / L) * d, center.y + (1.0 / L) * d, center.z + (0.7 / L) * d);
|
|
}
|
|
camera.near = 0.1;
|
|
camera.far = maxSize * 8;
|
|
camera.updateProjectionMatrix();
|
|
controls.target.copy(center);
|
|
controls.update();
|
|
}
|
|
|
|
function downloadSnapshot() {
|
|
const link = document.createElement("a");
|
|
link.download = "cad-building-showcase.png";
|
|
link.href = renderer.domElement.toDataURL("image/png");
|
|
link.click();
|
|
}
|
|
|
|
window.addEventListener("pointerdown", (event) => {
|
|
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
|
|
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
|
|
raycaster.setFromCamera(pointer, camera);
|
|
const hit = raycaster.intersectObjects(objectRegistry, true)[0];
|
|
if (!hit) {
|
|
inspect.querySelector(".inspect-title").textContent = "未选择";
|
|
inspect.querySelector(".inspect-body").textContent = "点击模型中的楼层或构件类型";
|
|
return;
|
|
}
|
|
const object = objectRegistry.find((mesh) => mesh === hit.object || mesh.children.includes(hit.object));
|
|
if (!object) return;
|
|
inspect.querySelector(".inspect-title").textContent = object.userData.label;
|
|
inspect.querySelector(".inspect-body").textContent = `楼层 ${object.userData.floor} / 类别 ${object.userData.category}`;
|
|
});
|
|
|
|
window.addEventListener("resize", () => {
|
|
camera.aspect = window.innerWidth / window.innerHeight;
|
|
camera.updateProjectionMatrix();
|
|
renderer.setSize(window.innerWidth, window.innerHeight);
|
|
});
|
|
|
|
function animate() {
|
|
requestAnimationFrame(animate);
|
|
controls.update();
|
|
renderer.render(scene, camera);
|
|
}
|
|
|
|
animate();
|