Web template: adopt session-evolved features + render-on-demand everywhere

Ported from the test3d-5 session build: in-page variant switching, share
link (full state in URL hash), auto tour, toast, building-grouped floor
toggles, per-(floor,category) geometry merge (draw calls), progressive
overview->standard loading. Hardened during the port: {{BUILD}} placeholder
restored (Date.now() defeated caching), single-GLB deployments skip the
phantom overview.glb phase, building-group fallback now derives from
floor-key prefixes (assemble_campus convention) instead of a hardcoded "A"
test, bookmarks completed (list + restore + remove + hash persistence).

Render-on-demand lands in BOTH the template and the offline viewer: static
scenes rendered at 60fps pegged the GPU/fans for identical frames —
invalidate()-driven rendering + shadowMap.autoUpdate=false (bake per
change). 27号 measured: template web 0 frames over 3s idle, offline viewer
25 frames total through load; features browser-verified (tour, bookmarks,
hash restore), zero console errors. window.__renders is the diagnostic
counter — idle growth must be 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-04 12:55:03 +08:00
parent eb7eea2861
commit 23cf3af678
6 changed files with 757 additions and 114 deletions

View File

@@ -104,6 +104,7 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate
- Use Blender MCP only after the CLI artifact exists, for inspection, scene tuning, or interactive refinement.
6. Generate the Web showcase.
- The template renders ON DEMAND (static scene + 60fps loop = pegged GPU/fans for identical frames): anything that changes the view calls invalidate(); shadows are baked per change (`shadowMap.autoUpdate=false`), and `window.__renders` is the diagnostic frame counter — idle MUST read 0 growth. The offline viewer follows the same contract. Template features: building-grouped floor toggles (metadata.buildings or floor-key prefix fallback), per-(floor,category) geometry merging (draw-call reduction), progressive overview->standard loading (single-GLB deployments skip the swap), in-page variant switching, auto tour, camera bookmarks (list + restore + removable), share-link (full state in the URL hash), toast notices.
- For digital-twin-style Web delivery, keep generated slabs visible by default and create three filtered specs/models:
- `overview`: walls, glazing, roof, columns, beams, and generated slabs.
- `standard`: overview plus railings and doors; use this as the default Web model.

View File

@@ -3,7 +3,9 @@ import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
// ───────────────────────── DOM ─────────────────────────
const canvas = document.querySelector("#scene");
const loading = document.querySelector("#loading");
const loadingFill = document.querySelector("#loading-fill");
@@ -11,6 +13,7 @@ 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 variantControls = document.querySelector("#variant-controls");
const stats = document.querySelector("#stats");
const inspect = document.querySelector("#inspect");
const explodeInput = document.querySelector("#explode");
@@ -18,23 +21,34 @@ const explodeValue = document.querySelector("#explode-value");
const sectionInput = document.querySelector("#section");
const sectionValue = document.querySelector("#section-value");
const autoRotateButton = document.querySelector("#auto-rotate");
const tourButton = document.querySelector("#auto-tour");
const bookmarkButton = document.querySelector("#bookmark");
const shareButton = document.querySelector("#share-link");
const bookmarkList = document.querySelector("#bookmark-list");
// ───────────────────────── Constants ─────────────────────────
const preferredCategoryOrder = [
"slab",
"roof",
"walls",
"glazing",
"columns",
"beams",
"railings",
"doors",
"detail_lines",
"floor_lines",
"grid",
"slab", "roof", "walls", "glazing", "columns", "beams",
"railings", "doors", "detail_lines", "floor_lines", "grid",
];
const CACHE_BUST = "{{BUILD}}";
// Tour presets — cycle through these viewpoints
const TOUR_PRESETS = ["overview", "side", "top", "overview"];
// ───────────────────────── State ─────────────────────────
const objectRegistry = [];
const floorGroups = new Map();
const buildingGroups = new Map(); // building key -> Set of floor keys
const materialByCategory = new Map();
const mergedMeshes = []; // merged geometry meshes for draw-call optimization
const bookmarks = [];
let currentVariant = "standard";
let loadedVariant = null;
let tourActive = false;
let tourIndex = 0;
let tourTimer = null;
const state = {
floors: {},
categories: {},
@@ -43,14 +57,12 @@ const state = {
bounds: null,
};
// ───────────────────────── Scene Setup ─────────────────────────
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x272a2d);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
preserveDrawingBuffer: true,
canvas, antialias: true, alpha: false, preserveDrawingBuffer: true,
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
@@ -58,24 +70,37 @@ renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.2;
renderer.shadowMap.enabled = true;
// Static scene: bake shadows once per change, not per frame.
renderer.shadowMap.autoUpdate = false;
renderer.shadowMap.needsUpdate = 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
camera.up.set(0, 1, 0);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.screenSpacePanning = true;
controls.maxPolarAngle = Math.PI * 0.49;
// Render on demand: a static scene re-rendered at 60 fps pegs the GPU and the
// fans for identical frames. Anything that changes what's on screen calls
// invalidate(); the loop renders only then (or while damping/autoRotate move
// the camera). window.__renders is a diagnostic frame counter.
let renderPending = true;
window.__renders = 0;
function invalidate({ shadows = false } = {}) {
if (shadows) renderer.shadowMap.needsUpdate = true;
renderPending = true;
}
controls.addEventListener("change", () => invalidate());
scene.add(new THREE.HemisphereLight(0xf7f3e8, 0x20262a, 0.9));
// Image-based lighting: cheap, no HDR download, transforms material readability.
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
if ("environmentIntensity" in scene) scene.environmentIntensity = 0.85;
// Y-up scene: the sun must sit ABOVE the model (positive Y) or shadows break.
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-45, 85, 62);
keyLight.castShadow = true;
@@ -93,23 +118,53 @@ 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 sectionPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0), 9999);
const metadata = await fetch("./model_metadata.json?v={{BUILD}}").then((response) => response.json());
// ───────────────────────── Metadata + Init ─────────────────────────
const metadata = await fetch(`./model_metadata.json?v=${CACHE_BUST}`).then((r) => r.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 展示模型";
// Build building->floors mapping
if (metadata.buildings) {
for (const b of metadata.buildings) {
buildingGroups.set(b.key, new Set(b.floors));
}
} else {
// Fallback: group by the campus prefix in front of the floor token
// (assemble_campus keys: 1AF1 / 2-F3 / PDRF ... -> buildings 1A / 2- / PD)
for (const f of metadata.floors || []) {
const m = f.key.match(/^(.*?)(?:B\d+M?|F\d+M?|PH|RF)(?:_\d+)?$/);
const prefix = (m && m[1]) || "";
if (!buildingGroups.has(prefix)) buildingGroups.set(prefix, new Set());
buildingGroups.get(prefix).add(f.key);
}
}
initialiseState(metadata);
buildInterface(metadata);
restoreStateFromHash();
// ───────────────────────── Progressive Loading ─────────────────────────
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("./node_modules/three/examples/jsm/libs/draco/"); // shipped with three; works offline
dracoLoader.setDecoderPath("./node_modules/three/examples/jsm/libs/draco/");
loader.setDRACOLoader(dracoLoader);
// Phase 1: load the lightest model first. Single-GLB deployments have no
// model_variants — go straight to model.glb and skip the phase-2 swap.
const modelVariants = metadata.model_variants || [];
const overviewFile = modelVariants.find((v) => v.key === "overview")?.file || null;
const standardFile = modelVariants.find((v) => v.key === "standard")?.file || "model.glb";
const firstFile = overviewFile || standardFile;
const firstTag = overviewFile ? "overview" : "standard";
loadingText.textContent = overviewFile ? "加载总览模型…" : "加载模型…";
loader.load(
"./model.glb?v={{BUILD}}",
`./${firstFile}?v=${CACHE_BUST}`,
(gltf) => {
ingestModel(gltf.scene, metadata);
ingestModel(gltf.scene, metadata, firstTag);
applyExplode(Number(explodeInput.value));
const maxZ = Math.max(6, Math.ceil((metadata.bounds?.max_z || 12) + 2));
sectionInput.max = String(maxZ);
@@ -120,12 +175,54 @@ loader.load(
updateStats();
updateVisibility();
loading.classList.add("hidden");
loadedVariant = firstTag;
currentVariant = firstTag;
updateVariantUI();
// Phase 2: swap to the full model on idle (variant deployments only)
const swap = () => {
if (!overviewFile || standardFile === firstFile) return;
if (loadedVariant !== "overview") return;
loadingText.textContent = "加载标准模型…";
loading.classList.remove("hidden");
loader.load(
`./${standardFile}?v=${CACHE_BUST}`,
(gltf2) => {
// Clear old overview meshes
clearModel();
ingestModel(gltf2.scene, metadata, "standard");
applyExplode(Number(explodeInput.value));
applySection(Number(sectionInput.value));
updateVisibility();
loadedVariant = "standard";
currentVariant = "standard";
updateVariantUI();
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);
setTimeout(() => loading.classList.add("hidden"), 2000);
},
);
};
if ("requestIdleCallback" in window) {
requestIdleCallback(swap, { timeout: 3000 });
} else {
setTimeout(swap, 1500);
}
},
(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}%`;
loadingText.textContent = `加载总览模型 ${pct}%`;
},
(error) => {
loadingText.textContent = "模型加载失败";
@@ -135,43 +232,19 @@ loader.load(
if (window.lucide) window.lucide.createIcons();
// ───────────────────────── State Init ─────────────────────────
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);
}
// ───────────────────────── Interface Builder ─────────────────────────
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();
},
}),
),
);
buildFloorControls(meta);
buildCategoryControls(meta);
buildDownloadControls(meta);
buildVariantControls(meta);
explodeInput.addEventListener("input", () => {
const value = Number(explodeInput.value);
@@ -179,7 +252,10 @@ function buildInterface(meta) {
applyExplode(value);
});
sectionInput.addEventListener("input", () => applySection(Number(sectionInput.value)));
sectionInput.addEventListener("input", () => {
applySection(Number(sectionInput.value));
serializeStateToHash();
});
document.querySelectorAll("[data-preset]").forEach((button) => {
button.addEventListener("click", () => fitCamera(button.dataset.preset));
@@ -193,6 +269,7 @@ function buildInterface(meta) {
applyExplode(0);
applySection(Number(sectionInput.max));
fitCamera("overview");
serializeStateToHash();
});
autoRotateButton.addEventListener("click", () => {
@@ -202,9 +279,141 @@ function buildInterface(meta) {
controls.autoRotateSpeed = 0.8;
});
// Auto-orbit tour
tourButton?.addEventListener("click", () => {
tourActive = !tourActive;
tourButton.classList.toggle("active", tourActive);
if (tourActive) startTour();
else stopTour();
});
// Camera bookmark: saved views get a clickable list and travel in the URL
bookmarkButton?.addEventListener("click", () => {
bookmarks.push({
p: camera.position.toArray().map((n) => +n.toFixed(1)),
t: controls.target.toArray().map((n) => +n.toFixed(1)),
});
renderBookmarkList();
showToast(`已保存视角 ${bookmarks.length}`);
serializeStateToHash();
});
// Share link
shareButton?.addEventListener("click", () => {
serializeStateToHash();
const url = window.location.href;
navigator.clipboard?.writeText(url).then(() => showToast("链接已复制"));
});
document.querySelector("#snapshot").addEventListener("click", downloadSnapshot);
}
// ───────────────────────── Floor Controls (Building-Grouped) ─────────────────────────
function buildFloorControls(meta) {
let buildings = meta.buildings;
if (!buildings) {
const byPrefix = new Map();
for (const f of meta.floors || []) {
const m = f.key.match(/^(.*?)(?:B\d+M?|F\d+M?|PH|RF)(?:_\d+)?$/);
const prefix = (m && m[1]) || "";
if (!byPrefix.has(prefix)) byPrefix.set(prefix, []);
byPrefix.get(prefix).push(f.key);
}
buildings = [...byPrefix.entries()].map(([prefix, floors]) => ({
key: prefix || "main",
label: prefix || (byPrefix.size > 1 ? "主体" : "全部楼层"),
floors,
}));
}
floorControls.replaceChildren();
for (const building of buildings) {
const groupEl = document.createElement("div");
groupEl.className = "building-group";
// Building header with select-all toggle
const header = document.createElement("label");
header.className = "building-header";
const headerInput = document.createElement("input");
headerInput.type = "checkbox";
headerInput.checked = true;
headerInput.addEventListener("change", () => {
for (const fk of building.floors) {
state.floors[fk] = headerInput.checked;
}
updateVisibility();
updateFloorCheckboxUI();
serializeStateToHash();
});
const headerText = document.createElement("span");
headerText.className = "building-label";
headerText.textContent = building.label;
header.append(headerInput, headerText);
groupEl.append(header);
// Floor toggles
const floorList = document.createElement("div");
floorList.className = "floor-list";
for (const fk of building.floors) {
const floor = (meta.floors || []).find((f) => f.key === fk);
if (!floor) continue;
floorList.append(
createToggle({
key: fk,
label: fk,
checked: state.floors[fk],
onChange: (checked) => {
state.floors[fk] = checked;
updateVisibility();
updateBuildingHeaderState(building, headerInput);
serializeStateToHash();
},
}),
);
}
groupEl.append(floorList);
floorControls.append(groupEl);
}
}
function updateFloorCheckboxUI() {
// Update all floor checkboxes to match state
floorControls.querySelectorAll(".toggle").forEach((toggle) => {
const key = toggle.dataset.key;
const input = toggle.querySelector("input");
if (key && state.floors[key] !== undefined) {
input.checked = state.floors[key];
}
});
}
function updateBuildingHeaderState(building, headerInput) {
const allOn = building.floors.every((fk) => state.floors[fk]);
const allOff = building.floors.every((fk) => !state.floors[fk]);
headerInput.checked = allOn;
headerInput.indeterminate = !allOn && !allOff;
}
// ───────────────────────── Category Controls ─────────────────────────
function buildCategoryControls(meta) {
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();
serializeStateToHash();
},
}),
),
);
}
// ───────────────────────── Download Controls ─────────────────────────
function buildDownloadControls(meta) {
const variants = meta.model_variants?.length
? meta.model_variants
@@ -222,6 +431,64 @@ function buildDownloadControls(meta) {
);
}
// ───────────────────────── Variant Controls ─────────────────────────
function buildVariantControls(meta) {
if (!variantControls) return;
const variants = meta.model_variants || [];
variantControls.replaceChildren(
...variants.map((variant) => {
const btn = document.createElement("button");
btn.className = "variant-btn";
btn.dataset.variant = variant.key;
btn.textContent = variant.label || variant.key;
btn.title = variant.description || "";
if (variant.key === currentVariant) btn.classList.add("active");
btn.addEventListener("click", () => switchVariant(variant.key, variants));
return btn;
}),
);
}
function updateVariantUI() {
variantControls?.querySelectorAll(".variant-btn").forEach((btn) => {
btn.classList.toggle("active", btn.dataset.variant === currentVariant);
});
}
function switchVariant(variantKey, variants) {
if (variantKey === loadedVariant) return;
const variant = variants.find((v) => v.key === variantKey);
if (!variant) return;
loadingText.textContent = `加载${variant.label}…`;
loading.classList.remove("hidden");
loader.load(
`./${variant.file}?v=${CACHE_BUST}`,
(gltf) => {
clearModel();
ingestModel(gltf.scene, metadata, variantKey);
applyExplode(Number(explodeInput.value));
applySection(Number(sectionInput.value));
updateVisibility();
loadedVariant = variantKey;
currentVariant = variantKey;
updateVariantUI();
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 = `加载${variant.label} ${pct}%`;
},
(error) => {
loadingText.textContent = "变体加载失败";
console.error(error);
setTimeout(() => loading.classList.add("hidden"), 2000);
},
);
}
// ───────────────────────── Toggle Factory ─────────────────────────
function createToggle({ key, label, color, checked, onChange }) {
const root = document.createElement("label");
root.className = "toggle";
@@ -243,12 +510,35 @@ function createToggle({ key, label, color, checked, onChange }) {
return root;
}
function ingestModel(gltfScene, meta) {
// ───────────────────────── Model Ingestion + Merge ─────────────────────────
function clearModel() {
for (const mesh of objectRegistry) {
mesh.geometry?.dispose();
}
objectRegistry.length = 0;
for (const [key, group] of floorGroups) {
while (group.children.length > 0) group.remove(group.children[0]);
}
// Remove merged meshes
for (const m of mergedMeshes) {
m.geometry?.dispose();
m.material?.dispose();
m.parent?.remove(m);
}
mergedMeshes.length = 0;
materialByCategory.clear();
}
function ingestModel(gltfScene, meta, variantTag) {
// Create floor groups
for (const floor of meta.floors || []) {
const group = new THREE.Group();
group.name = floor.key;
floorGroups.set(floor.key, group);
modelRoot.add(group);
let group = floorGroups.get(floor.key);
if (!group) {
group = new THREE.Group();
group.name = floor.key;
floorGroups.set(floor.key, group);
modelRoot.add(group);
}
}
gltfScene.updateMatrixWorld(true);
@@ -257,6 +547,9 @@ function ingestModel(gltfScene, meta) {
if (node.isMesh) meshes.push(node);
});
// Collect meshes by (floor, category) for merging
const mergeBuckets = new Map(); // "floor__category" -> { geometries: [], floor, category }
for (const mesh of meshes) {
const parsed = parseObjectName(mesh.name);
mesh.updateWorldMatrix(true, false);
@@ -270,30 +563,75 @@ function ingestModel(gltfScene, meta) {
continue;
}
if (parsed.category === "trees" && meta.site_trees?.length) {
mesh.visible = false; // replaced by instanced trunk+crown trees below
mesh.visible = false;
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);
const category = parsed.category;
if (!categoryOrder.includes(category)) {
floorGroups.get(parsed.floor).add(mesh);
continue;
}
// Assign material before merging
const material = materialForCategory(category, meta);
// For overview variant or small meshes, keep individual; for standard+, merge
const bucketKey = `${parsed.floor}__${category}`;
if (!mergeBuckets.has(bucketKey)) {
mergeBuckets.set(bucketKey, { geometries: [], floor: parsed.floor, category, material });
}
// Clone geometry with material group for merging
const geom = mesh.geometry.clone();
// Ensure normal and position attributes exist
if (!geom.attributes.normal) geom.computeVertexNormals();
mergeBuckets.get(bucketKey).geometries.push(geom);
}
// Merge geometries per (floor, category) — drastically reduces draw calls
for (const [bucketKey, bucket] of mergeBuckets) {
const group = floorGroups.get(bucket.floor);
if (!group) continue;
if (bucket.geometries.length <= 1) {
// Single mesh — no benefit from merging
const mesh = new THREE.Mesh(bucket.geometries[0] || new THREE.BufferGeometry(), bucket.material);
mesh.name = `${bucket.floor}__${bucket.category}`;
mesh.castShadow = !["grid", "floor_lines", "detail_lines", "glazing"].includes(bucket.category);
mesh.receiveShadow = true;
mesh.userData.floor = bucket.floor;
mesh.userData.category = bucket.category;
mesh.userData.label = labelForObject({ floor: bucket.floor, category: bucket.category });
addEdges(mesh, bucket.category);
objectRegistry.push(mesh);
group.add(mesh);
} else {
// Merge all geometries of same material into one mesh
const merged = mergeGeometries(bucket.geometries, false);
// Clean up source geometries
bucket.geometries.forEach((g) => g.dispose());
const mesh = new THREE.Mesh(merged, bucket.material);
mesh.name = `${bucket.floor}__${bucket.category}`;
mesh.castShadow = !["grid", "floor_lines", "detail_lines", "glazing"].includes(bucket.category);
mesh.receiveShadow = true;
mesh.userData.floor = bucket.floor;
mesh.userData.category = bucket.category;
mesh.userData.label = labelForObject({ floor: bucket.floor, category: bucket.category });
mesh.userData.mergedCount = bucket.geometries.length;
addEdges(mesh, bucket.category);
objectRegistry.push(mesh);
mergedMeshes.push(mesh);
group.add(mesh);
}
floorGroups.get(parsed.floor).add(mesh);
}
if (meta.site_trees?.length) addInstancedTrees(meta.site_trees);
state.bounds = new THREE.Box3().setFromObject(modelRoot);
fitShadowsAndGround(state.bounds);
invalidate({ shadows: true });
}
function addInstancedTrees(points) {
// spec plan coords (x, y) -> Y-up world (x, ?, -y), same mapping as the GLB export
const trunk = new THREE.InstancedMesh(
new THREE.CylinderGeometry(0.14, 0.2, 1.4, 6),
new THREE.MeshStandardMaterial({ color: 0x6b4a2e, roughness: 0.9, clippingPlanes: [sectionPlane] }),
@@ -318,7 +656,6 @@ function addInstancedTrees(points) {
}
function fitShadowsAndGround(bounds) {
// Default directional-shadow frustum is ±5 m — useless for buildings.
const center = bounds.getCenter(new THREE.Vector3());
const size = bounds.getSize(new THREE.Vector3());
const radius = Math.max(size.x, size.z, 20) * 0.75;
@@ -333,19 +670,16 @@ function fitShadowsAndGround(bounds) {
new THREE.ShadowMaterial({ opacity: 0.32 }),
);
ground.rotation.x = -Math.PI / 2;
// Grade sits at y=0 by spec convention; bounds.min.y is the BASEMENT floor
// when one exists, and a catcher 5 m below grade shows shadows detached
// from the building. Clamp to grade unless the whole model floats above it.
const groundY = Math.max(bounds.min.y, Math.min(0, bounds.max.y)) - 0.03;
ground.position.set(center.x, groundY, center.z);
ground.receiveShadow = true;
scene.add(ground);
}
// ───────────────────────── Name Parsing ─────────────────────────
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 };
}
@@ -354,11 +688,11 @@ function labelForObject({ floor, category }) {
return `${floor} ${metadata.categories?.[category]?.label || category}`;
}
// ───────────────────────── Materials ─────────────────────────
function materialForCategory(category, meta) {
if (materialByCategory.has(category)) return materialByCategory.get(category);
const color = new THREE.Color(meta.categories[category]?.color || "#cccccc");
if (category === "glazing") {
// Physical glass (transmission) instead of flat alpha — key perceived-quality win.
const glass = new THREE.MeshPhysicalMaterial({
color, metalness: 0, roughness: 0.18, transmission: 0.7, ior: 1.5, thickness: 0.3,
transparent: true, depthWrite: false, side: THREE.DoubleSide, clippingPlanes: [sectionPlane],
@@ -368,26 +702,16 @@ function materialForCategory(category, meta) {
return glass;
}
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;
category === "slab" ? 0.64
: category === "roof" ? 0.95
: 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,
color, transparent: opacity < 1, opacity,
depthWrite: category === "slab" ? true : opacity >= 0.8,
roughness: 0.74,
metalness: 0.02,
roughness: 0.74, metalness: 0.02,
side: category === "slab" || category === "roof" ? THREE.DoubleSide : THREE.FrontSide,
clippingPlanes: [sectionPlane],
});
@@ -404,41 +728,53 @@ function addEdges(mesh, category) {
mesh.add(edges);
}
// ───────────────────────── Explode / Section / Visibility ─────────────────────────
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
if (group) group.position.y = index * distance;
}
updateStats();
invalidate({ shadows: true });
}
function applySection(height) {
const max = Number(sectionInput.max);
sectionPlane.constant = height >= max ? 9999 : height;
sectionValue.textContent = height >= max ? "关闭" : `${height.toFixed(2)}m`;
invalidate({ shadows: true });
}
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()) {
for (const [floorKey, group] of floorGroups) {
group.visible = Boolean(state.floors[floorKey]);
}
updateStats();
invalidate({ shadows: true });
}
// ───────────────────────── Stats (with draw call count) ─────────────────────────
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);
// Estimate draw calls: each visible mesh = 1 draw call (edges add +1 each)
const drawCalls = visibleMeshes.reduce((sum, mesh) => {
let dc = 1;
if (mesh.children.some((c) => c.isLineSegments)) dc++;
return sum + dc;
}, 0);
stats.innerHTML = "";
for (const item of [
["楼层", `${activeFloors}/${(metadata.floors || []).length}`],
["构件", `${activeCategories}/${categoryOrder.length}`],
["顶点", vertices.toLocaleString("zh-CN")],
["Draw Calls", drawCalls.toString()],
]) {
const cell = document.createElement("div");
cell.innerHTML = `<dt>${item[0]}</dt><dd>${item[1]}</dd>`;
@@ -446,6 +782,7 @@ function updateStats() {
}
}
// ───────────────────────── Camera ─────────────────────────
function fitCamera(preset) {
const box = new THREE.Box3().setFromObject(modelRoot);
state.bounds = box;
@@ -457,7 +794,6 @@ function fitCamera(preset) {
} 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);
@@ -467,8 +803,120 @@ function fitCamera(preset) {
camera.updateProjectionMatrix();
controls.target.copy(center);
controls.update();
serializeStateToHash();
invalidate();
}
// ───────────────────────── Auto-Orbit Tour ─────────────────────────
function startTour() {
tourIndex = 0;
const next = () => {
if (!tourActive) return;
fitCamera(TOUR_PRESETS[tourIndex % TOUR_PRESETS.length]);
tourIndex++;
tourTimer = setTimeout(next, 5000);
};
next();
}
function stopTour() {
if (tourTimer) clearTimeout(tourTimer);
tourTimer = null;
}
// ───────────────────────── Bookmark List ─────────────────────────
function renderBookmarkList() {
if (!bookmarkList) return;
bookmarkList.replaceChildren(
...bookmarks.map((bm, index) => {
const item = document.createElement("span");
item.className = "bookmark-item";
const go = document.createElement("button");
go.textContent = `视角${index + 1}`;
go.addEventListener("click", () => {
camera.position.set(...bm.p);
controls.target.set(...bm.t);
controls.update();
invalidate();
});
const remove = document.createElement("button");
remove.className = "bookmark-remove";
remove.textContent = "\u00d7";
remove.title = "删除该视角";
remove.addEventListener("click", () => {
bookmarks.splice(index, 1);
renderBookmarkList();
serializeStateToHash();
});
item.append(go, remove);
return item;
}),
);
}
// ───────────────────────── URL Hash State ─────────────────────────
function serializeStateToHash() {
const hash = {
f: Object.entries(state.floors).filter(([, v]) => !v).map(([k]) => k), // only store disabled
c: Object.entries(state.categories).filter(([, v]) => !v).map(([k]) => k),
s: sectionInput.value,
e: explodeInput.value,
cam: {
p: [camera.position.x, camera.position.y, camera.position.z].map((n) => +n.toFixed(1)),
t: [controls.target.x, controls.target.y, controls.target.z].map((n) => +n.toFixed(1)),
},
b: bookmarks,
};
const encoded = btoa(JSON.stringify(hash)).replace(/=/g, "");
history.replaceState(null, "", `#${encoded}`);
}
function restoreStateFromHash() {
try {
const raw = window.location.hash.slice(1);
if (!raw) return;
const hash = JSON.parse(atob(raw));
if (hash.f) for (const fk of hash.f) { if (fk in state.floors) state.floors[fk] = false; }
if (hash.c) for (const ck of hash.c) { if (ck in state.categories) state.categories[ck] = false; }
if (hash.s) { sectionInput.value = hash.s; applySection(Number(hash.s)); }
if (hash.e) { explodeInput.value = hash.e; applyExplode(Number(hash.e)); explodeValue.textContent = `${Number(hash.e).toFixed(Number(hash.e) % 1 ? 1 : 0)}m`; }
if (Array.isArray(hash.b)) {
bookmarks.push(...hash.b.filter((bm) => Array.isArray(bm.p) && Array.isArray(bm.t)));
renderBookmarkList();
}
if (hash.cam?.p && hash.cam?.t) {
pendingCameraRestore = hash.cam;
}
} catch (e) {
// ignore malformed hash
}
}
let pendingCameraRestore = null;
function applyPendingCamera() {
if (!pendingCameraRestore) return;
camera.position.set(...pendingCameraRestore.p);
controls.target.set(...pendingCameraRestore.t);
controls.update();
pendingCameraRestore = null;
}
// ───────────────────────── Toast ─────────────────────────
function showToast(msg) {
let toast = document.querySelector("#toast");
if (!toast) {
toast = document.createElement("div");
toast.id = "toast";
toast.className = "toast";
document.body.append(toast);
}
toast.textContent = msg;
toast.classList.add("show");
clearTimeout(toast._timer);
toast._timer = setTimeout(() => toast.classList.remove("show"), 2200);
}
// ───────────────────────── Screenshot ─────────────────────────
function downloadSnapshot() {
const link = document.createElement("a");
link.download = "cad-building-showcase.png";
@@ -476,7 +924,10 @@ function downloadSnapshot() {
link.click();
}
// ───────────────────────── Raycast Picking ─────────────────────────
window.addEventListener("pointerdown", (event) => {
// Ignore clicks on UI panels
if (event.target !== canvas) return;
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
@@ -489,19 +940,30 @@ window.addEventListener("pointerdown", (event) => {
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}`;
const mergedInfo = object.userData.mergedCount ? ` (${object.userData.mergedCount} 合并)` : "";
inspect.querySelector(".inspect-body").textContent = `楼层 ${object.userData.floor} / 类别 ${object.userData.category}${mergedInfo}`;
});
// ───────────────────────── Resize ─────────────────────────
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// ───────────────────────── Animation Loop ─────────────────────────
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
const moved = controls.update(); // true while damping/autoRotate move the camera
if (pendingCameraRestore && modelRoot.children.length > 0) {
applyPendingCamera();
invalidate();
}
if (moved || renderPending) {
renderer.render(scene, camera);
window.__renders += 1;
renderPending = false;
}
}
animate();

View File

@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{{TITLE}}</title>
<link rel="icon" href="data:," /><!-- keep the console free of favicon 404s -->
<link rel="icon" href="data:," />
<link rel="stylesheet" href="./styles.css" />
<script type="importmap">
{
@@ -33,7 +33,7 @@
<section class="panel controls-panel" aria-label="控制">
<div class="control-group">
<div class="group-label">楼层</div>
<div class="segmented" id="floor-controls"></div>
<div id="floor-controls"></div>
</div>
<div class="control-group">
@@ -41,6 +41,11 @@
<div class="toggle-grid" id="category-controls"></div>
</div>
<div class="control-group">
<div class="group-label">模型变体</div>
<div class="variant-list" id="variant-controls"></div>
</div>
<div class="control-group">
<div class="group-label">下载</div>
<div class="download-list" id="download-controls"></div>
@@ -76,6 +81,16 @@
<button class="tool-button" id="auto-rotate" title="自动旋转" aria-label="自动旋转">
<i data-lucide="rotate-3d"></i>
</button>
<button class="tool-button" id="auto-tour" title="自动巡航" aria-label="自动巡航">
<i data-lucide="plane"></i>
</button>
<button class="tool-button" id="bookmark" title="保存视角" aria-label="保存视角">
<i data-lucide="bookmark"></i>
</button>
<button class="tool-button" id="share-link" title="复制分享链接" aria-label="复制分享链接">
<i data-lucide="share-2"></i>
</button>
<div id="bookmark-list" class="bookmark-list"></div>
<button class="tool-button" id="reset-view" title="重置视角" aria-label="重置视角">
<i data-lucide="rotate-ccw"></i>
</button>

View File

@@ -85,7 +85,7 @@ p {
.stats-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
margin: 14px 0 0;
}
@@ -100,13 +100,13 @@ p {
.stats-grid dt {
color: var(--muted);
font-size: 11px;
font-size: 10px;
}
.stats-grid dd {
margin: 3px 0 0;
color: var(--ink);
font-size: 14px;
font-size: 13px;
font-weight: 700;
white-space: nowrap;
overflow: hidden;
@@ -117,9 +117,19 @@ p {
left: 20px;
bottom: 20px;
width: min(384px, calc(100vw - 40px));
max-height: calc(100vh - 280px);
overflow-y: auto;
padding: 14px;
}
.controls-panel::-webkit-scrollbar {
width: 6px;
}
.controls-panel::-webkit-scrollbar-thumb {
background: rgba(0,0,0,0.18);
border-radius: 3px;
}
.control-group + .control-group {
margin-top: 13px;
padding-top: 13px;
@@ -140,9 +150,48 @@ p {
margin-bottom: 8px;
}
.segmented,
.toggle-grid,
.download-list {
/* ── Building-grouped floor controls ── */
.building-group {
margin-bottom: 10px;
}
.building-group:last-child {
margin-bottom: 0;
}
.building-header {
display: flex;
align-items: center;
gap: 7px;
padding: 5px 8px;
border-radius: 6px;
background: rgba(47, 125, 112, 0.1);
color: var(--accent);
font-size: 12px;
font-weight: 800;
cursor: pointer;
user-select: none;
margin-bottom: 5px;
}
.building-header input {
width: 13px;
height: 13px;
accent-color: var(--accent);
}
.building-label {
flex: 1;
}
.floor-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding-left: 4px;
}
.toggle-grid {
display: flex;
flex-wrap: wrap;
gap: 6px;
@@ -177,6 +226,36 @@ p {
border: 1px solid rgba(0, 0, 0, 0.2);
}
/* ── Variant controls ── */
.variant-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.variant-btn {
min-height: 32px;
padding: 6px 12px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(255, 255, 255, 0.58);
color: var(--ink);
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: background 0.15s;
}
.variant-btn:hover {
background: rgba(47, 125, 112, 0.12);
}
.variant-btn.active {
background: var(--accent);
color: #fff;
border-color: var(--accent);
}
.download-link {
min-height: 32px;
display: inline-flex;
@@ -205,12 +284,14 @@ input[type="range"] {
right: 20px;
top: 20px;
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 8px;
border-radius: 8px;
background: rgba(32, 35, 38, 0.86);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
max-width: 200px;
}
.tool-button {
@@ -284,6 +365,31 @@ input[type="range"] {
width: 12%;
height: 100%;
background: #d1a445;
transition: width 0.3s;
}
/* ── Toast ── */
.toast {
position: fixed;
bottom: 80px;
left: 50%;
transform: translateX(-50%) translateY(20px);
padding: 10px 20px;
border-radius: 8px;
background: rgba(32, 35, 38, 0.95);
color: #f6f4ec;
font-size: 13px;
font-weight: 600;
box-shadow: var(--shadow);
opacity: 0;
pointer-events: none;
transition: opacity 0.25s, transform 0.25s;
z-index: 9999;
}
.toast.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
@media (max-width: 760px) {
@@ -297,6 +403,7 @@ input[type="range"] {
top: auto;
right: 10px;
bottom: 10px;
max-width: 152px;
}
.controls-panel {
@@ -310,4 +417,42 @@ input[type="range"] {
.inspect-panel {
display: none;
}
.stats-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
/* ── Camera bookmarks ─────────────────────────────── */
.bookmark-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
max-width: 220px;
}
.bookmark-item {
display: inline-flex;
align-items: stretch;
border: 1px solid var(--line);
border-radius: 6px;
overflow: hidden;
background: rgba(255, 255, 255, 0.58);
}
.bookmark-item button {
border: 0;
background: transparent;
color: var(--ink);
font-size: 12px;
font-weight: 700;
padding: 4px 8px;
cursor: pointer;
}
.bookmark-item button:hover {
background: rgba(47, 125, 112, 0.12);
}
.bookmark-item .bookmark-remove {
padding: 4px 6px;
font-weight: 400;
opacity: 0.55;
border-left: 1px solid var(--line);
}

View File

@@ -330,6 +330,16 @@ glazing 在 walls 之前匹配。3.0m×22 层梯(0..66,机房顶69)。
时点名"陌生方言,先自觉建映射"。
三门禁未布防时 SKIP(既有项目零影响),新项目应全部布防。回归 +8 项。
24. **Web 模板功能移植 + 按需渲染**(test3d-5 会话演进版回收进模板,2026-07-04):
变体页内热切换、分享链接(全状态进 URL hash)、自动巡游、toast、建筑分组
楼层控制(无 buildings 字段时按楼层键前缀回退分组)、按(楼层,类别)合并
网格削 draw call、渐进加载(单 GLB 部署自动跳过二段加载);书签补全
(列表+恢复+删除+入 hash)。**按需渲染**根治"网页开着风扇狂转":静态场景
只在变更时渲染(invalidate() + damping/autoRotate 期间连续),阴影
autoUpdate=false 按变更重烤,模板与离线 viewer 同一契约;27号 实测
模板 web 静止 3 秒 0 帧、离线 viewer 加载全程仅 25 帧。`window.__renders`
为诊断计数,DoD 目检可要求"静止时不增长"。
**仍留档**:⑦ 未命名详图簇(核心筒大样)仍靠 clip 带宽人工剔除,标题纯度
只覆盖有名字的辅助框(需要"详图簇 vs 楼层框"的几何判别设计);2# 的
"十九、二十一层平面图"修改单簇(无障碍改造相关)未并入模型(需用户确认

View File

@@ -65,6 +65,7 @@ MAIN_JS = r'''
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.physicallyCorrectLights = true;
renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.shadowMap.autoUpdate = false; renderer.shadowMap.needsUpdate = true; // static scene: bake shadows on change only
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x23272d);
@@ -73,6 +74,10 @@ MAIN_JS = r'''
scene.environment = pmrem.fromScene(new THREE.RoomEnvironment(), 0.04).texture;
const cam = new THREE.PerspectiveCamera(48, innerWidth/innerHeight, 0.5, 4000);
const controls = new THREE.OrbitControls(cam, renderer.domElement); controls.enableDamping = true;
// Render on demand: identical frames at 60fps peg the GPU/fans on a static scene.
let renderPending = true; window.__renders = 0;
const invalidate = (shadows) => { if (shadows) renderer.shadowMap.needsUpdate = true; renderPending = true; };
controls.addEventListener('change', () => invalidate());
const sun = new THREE.DirectionalLight(0xfff3e0, 3.2);
sun.position.set(-120, 180, 140); sun.castShadow = true;
sun.shadow.mapSize.set(2048,2048); sun.shadow.bias = -0.0004;
@@ -129,8 +134,8 @@ MAIN_JS = r'''
}
const tg = document.getElementById('tg');
const state = {fl:{}, ct:{}};
const apply = () => nodes.forEach(o => { const p=(o.name||'').split('__');
o.visible = (state.fl[p[0]]!==false) && (state.ct[p[1]]!==false) && p[1]!=='trees'; });
const apply = () => { nodes.forEach(o => { const p=(o.name||'').split('__');
o.visible = (state.fl[p[0]]!==false) && (state.ct[p[1]]!==false) && p[1]!=='trees'; }); invalidate(true); };
for (const gname in GROUPS) {
const head = document.createElement('div'); head.className='grp';
const btn = document.createElement('button'); btn.textContent='开/关';
@@ -164,7 +169,7 @@ MAIN_JS = r'''
ptr.x=(e.clientX/innerWidth)*2-1; ptr.y=-(e.clientY/innerHeight)*2+1;
ray.setFromCamera(ptr, cam);
const hit = ray.intersectObjects(nodes.filter(o=>o.visible), false)[0];
if (hi) { hi.material = hiMat; hi = null; }
if (hi) { hi.material = hiMat; hi = null; invalidate(); }
if (!hit) { info.style.display='none'; return; }
hi = hit.object; hiMat = hi.material;
hi.material = hiMat.clone(); hi.material.emissive = new THREE.Color(0x2a6bd4); hi.material.emissiveIntensity = 0.55;
@@ -172,10 +177,15 @@ MAIN_JS = r'''
let fname=''; for (const gname in GROUPS) GROUPS[gname].forEach(f => { if (f[0]===p[0]) fname=f[1]; });
info.innerHTML = '<b>'+p[0]+'</b> '+fname+'<br>构件:'+(CATS[p[1]]||p[1])+' 节点:'+hi.name;
info.style.display = 'block';
invalidate();
});
invalidate(true);
renderer.setAnimationLoop(() => {
const moved = controls.update();
if (moved || renderPending) { renderer.render(scene, cam); window.__renders += 1; renderPending = false; }
});
renderer.setAnimationLoop(() => { controls.update(); renderer.render(scene, cam); });
}, e => fail('GLB 解析错误 '+(e && e.message || e)));
addEventListener('resize', () => { cam.aspect=innerWidth/innerHeight; cam.updateProjectionMatrix(); renderer.setSize(innerWidth,innerHeight); });
addEventListener('resize', () => { cam.aspect=innerWidth/innerHeight; cam.updateProjectionMatrix(); renderer.setSize(innerWidth,innerHeight); invalidate(); });
} catch (err) { fail(err.message || String(err)); }
})();
'''