HifiPlanet-Builder/app.js
Maaxxs a670211258 Switch viewport to a bright CAD/3D-design-tool look
Replaced the dark showroom scene (gradient sky, mirror-style reflections,
bloom glow) with a clean white background, light studio ground, and a
visible reference grid (GridHelper) - the classic modeling-software
viewport aesthetic. Dropped the bloom postprocessing pass entirely since
it blew out badly against the white background and doesn't fit a
technical viewport anyway; tuned taillight/trim materials back down to
plain (non-bloom) emissive levels.
2026-09-01 10:56:29 +02:00

1041 lines
37 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.

import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { RoundedBoxGeometry } from "three/addons/geometries/RoundedBoxGeometry.js";
const searchInput = document.getElementById("searchInput");
const suggestionsBox = document.getElementById("suggestions");
const hintBox = document.getElementById("hintBox");
const chipsBox = document.getElementById("chips");
const content = document.getElementById("content");
const emptyState = document.getElementById("emptyState");
const infoPanel = document.getElementById("infoPanel");
const viewerEl = document.getElementById("viewer");
const randomBtn = document.getElementById("randomBtn");
const toggleCase = document.getElementById("toggleCase");
const toggleLid = document.getElementById("toggleLid");
const lidStateLabel = document.getElementById("lidStateLabel");
const toggleFloor = document.getElementById("toggleFloor");
const floorStateLabel = document.getElementById("floorStateLabel");
const floorToggleRow = document.getElementById("floorToggleRow");
const estimateBox = document.getElementById("estimateBox");
const estimateChips = document.getElementById("estimateChips");
const subPresetsBox = document.getElementById("subPresets");
const subW = document.getElementById("subW");
const subH = document.getElementById("subH");
const subD = document.getElementById("subD");
const subApply = document.getElementById("subApply");
const subRemove = document.getElementById("subRemove");
const subStatus = document.getElementById("subStatus");
let cars = [];
let wmiTable = {};
let activeSuggestionIndex = -1;
let currentCar = null;
let showCaseReference = false;
let lidOpen = true;
let lidPivot = null;
let lidAnimId = null;
const LID_OPEN_ANGLE = 0.32;
const LID_CLOSED_ANGLE = Math.PI;
let floorLifted = false;
let floorPivot = null;
let floorAnimId = null;
const FLOOR_DOWN_ANGLE = 0;
const FLOOR_UP_ANGLE = -0.8;
const BODY_PAINT_COLOR = 0x3c4046;
// Näherungswerte je Fahrzeugklasse (Mittelwerte aus der Beispieldatenbank), für Marken/Modelle,
// die nicht in data/cars.json hinterlegt sind. So lässt sich trotzdem jede beliebige Eingabe
// mit einer plausiblen 3D-Näherung darstellen.
const GENERIC_CATEGORIES = [
{ id: "kleinwagen", label: "Kleinwagen", bodyType: "Kleinwagen (Schätzung)", cargoLiters: 300, cargoLitersMax: 950, length_mm: 700, widthFloor_mm: 925, widthShoulder_mm: 1190, height_mm: 490, sillHeight_mm: 690, underFloorDepth_mm: 100 },
{ id: "kompakt", label: "Kompaktklasse", bodyType: "Kompaktklasse (Schätzung)", cargoLiters: 380, cargoLitersMax: 1230, length_mm: 750, widthFloor_mm: 1000, widthShoulder_mm: 1300, height_mm: 500, sillHeight_mm: 700, underFloorDepth_mm: 130 },
{ id: "kombi", label: "Kombi", bodyType: "Kombi (Schätzung)", cargoLiters: 590, cargoLitersMax: 1650, length_mm: 1040, widthFloor_mm: 1040, widthShoulder_mm: 1330, height_mm: 565, sillHeight_mm: 690, underFloorDepth_mm: 170 },
{ id: "limousine", label: "Limousine", bodyType: "Limousine (Schätzung)", cargoLiters: 480, cargoLitersMax: null, length_mm: 850, widthFloor_mm: 1000, widthShoulder_mm: 1320, height_mm: 550, sillHeight_mm: 770, underFloorDepth_mm: 150 },
{ id: "suv-kompakt", label: "Kompakt-SUV", bodyType: "Kompakt-SUV (Schätzung)", cargoLiters: 590, cargoLitersMax: 1700, length_mm: 915, widthFloor_mm: 1040, widthShoulder_mm: 1350, height_mm: 748, sillHeight_mm: 745, underFloorDepth_mm: 190 },
{ id: "suv-mittel", label: "Mittelklasse-SUV", bodyType: "Mittelklasse-SUV (Schätzung)", cargoLiters: 560, cargoLitersMax: 1620, length_mm: 940, widthFloor_mm: 1040, widthShoulder_mm: 1360, height_mm: 750, sillHeight_mm: 765, underFloorDepth_mm: 210 },
{ id: "van", label: "Van / Großraum", bodyType: "Van (Schätzung)", cargoLiters: 700, cargoLitersMax: 1900, length_mm: 1050, widthFloor_mm: 1100, widthShoulder_mm: 1400, height_mm: 800, sillHeight_mm: 680, underFloorDepth_mm: 150 },
];
const VIN_RE = /^[A-HJ-NPR-Z0-9]{17}$/; // ISO 3779: no I, O, Q
const SUB_PRESETS = [
{ id: "sub10", label: '1× 10" geschlossen', w: 35, h: 30, d: 35 },
{ id: "sub12", label: '1× 12" Bassreflex', w: 40, h: 38, d: 45 },
{ id: "sub12x2", label: '2× 12" Bassreflex', w: 75, h: 38, d: 45 },
{ id: "sub15", label: '1× 15" Bassreflex', w: 46, h: 44, d: 50 },
];
init();
async function init() {
const [carsRes, wmiRes] = await Promise.all([
fetch("data/cars.json"),
fetch("data/wmi.json"),
]);
cars = await carsRes.json();
wmiTable = await wmiRes.json();
buildChips();
buildSubPresets();
setupScene();
searchInput.addEventListener("input", onInput);
searchInput.addEventListener("keydown", onKeyDown);
document.addEventListener("click", (e) => {
if (!e.target.closest(".search-panel")) {
suggestionsBox.hidden = true;
estimateBox.hidden = true;
}
});
randomBtn.addEventListener("click", () => {
const car = cars[Math.floor(Math.random() * cars.length)];
searchInput.value = `${car.brand} ${car.model}`;
selectCar(car);
});
subApply.addEventListener("click", () => {
addOrUpdateSub(Number(subW.value), Number(subH.value), Number(subD.value));
});
subRemove.addEventListener("click", removeSub);
toggleCase.addEventListener("change", () => {
showCaseReference = toggleCase.checked;
rebuildTrunkOnly();
});
toggleLid.addEventListener("change", () => {
setLidOpen(toggleLid.checked, true);
});
toggleFloor.addEventListener("change", () => {
setFloorLifted(toggleFloor.checked, true);
});
}
// Animiert den Zwischenboden zwischen abgesenkter und angehobener Stellung
function setFloorLifted(lifted, animate) {
floorLifted = lifted;
floorStateLabel.textContent = lifted ? "angehoben" : "unten";
if (!floorPivot) return;
const target = lifted ? FLOOR_UP_ANGLE : FLOOR_DOWN_ANGLE;
if (!animate) {
floorPivot.rotation.x = target;
return;
}
if (floorAnimId) cancelAnimationFrame(floorAnimId);
const start = floorPivot.rotation.x;
const startTime = performance.now();
const duration = 600;
function step(now) {
const t = Math.min(1, (now - startTime) / duration);
const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
if (floorPivot) floorPivot.rotation.x = start + (target - start) * eased;
if (t < 1) {
floorAnimId = requestAnimationFrame(step);
} else {
floorAnimId = null;
}
}
floorAnimId = requestAnimationFrame(step);
}
// Animiert die Heckklappe zwischen offener und geschlossener Stellung
function setLidOpen(open, animate) {
lidOpen = open;
lidStateLabel.textContent = open ? "offen" : "geschlossen";
if (!lidPivot) return;
const target = open ? LID_OPEN_ANGLE : LID_CLOSED_ANGLE;
if (!animate) {
lidPivot.rotation.x = target;
return;
}
if (lidAnimId) cancelAnimationFrame(lidAnimId);
const start = lidPivot.rotation.x;
const startTime = performance.now();
const duration = 700;
function step(now) {
const t = Math.min(1, (now - startTime) / duration);
const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
if (lidPivot) lidPivot.rotation.x = start + (target - start) * eased;
if (t < 1) {
lidAnimId = requestAnimationFrame(step);
} else {
lidAnimId = null;
}
}
lidAnimId = requestAnimationFrame(step);
}
function buildChips() {
const picks = ["vw-golf8", "vw-tiguan", "bmw-3er", "skoda-superb-combi", "audi-q5", "tesla-model3"];
chipsBox.innerHTML = "";
picks.forEach((id) => {
const car = cars.find((c) => c.id === id);
if (!car) return;
const chip = document.createElement("button");
chip.className = "chip";
chip.textContent = `${car.brand} ${car.model}`;
chip.addEventListener("click", () => {
searchInput.value = `${car.brand} ${car.model}`;
selectCar(car);
suggestionsBox.hidden = true;
estimateBox.hidden = true;
});
chipsBox.appendChild(chip);
});
}
function buildSubPresets() {
subPresetsBox.innerHTML = "";
SUB_PRESETS.forEach((preset) => {
const chip = document.createElement("button");
chip.className = "chip";
chip.type = "button";
chip.textContent = preset.label;
chip.addEventListener("click", () => {
subW.value = preset.w;
subH.value = preset.h;
subD.value = preset.d;
[...subPresetsBox.children].forEach((c) => c.classList.remove("active"));
chip.classList.add("active");
addOrUpdateSub(preset.w, preset.h, preset.d);
});
subPresetsBox.appendChild(chip);
});
}
function onInput() {
const raw = searchInput.value.trim();
hintBox.hidden = true;
estimateBox.hidden = true;
activeSuggestionIndex = -1;
if (raw.length === 0) {
suggestionsBox.hidden = true;
return;
}
const vinCandidate = raw.toUpperCase().replace(/[\s-]/g, "");
if (vinCandidate.length === 17 && VIN_RE.test(vinCandidate)) {
handleVin(vinCandidate);
return;
}
const matches = filterCars(raw);
if (matches.length === 0) {
suggestionsBox.hidden = true;
renderEstimateOption(raw);
return;
}
renderSuggestions(matches);
}
// Für Marken/Modelle ohne hinterlegte Werte: Fahrzeugklasse wählen lassen und daraus
// eine plausible Näherung bauen, damit die Suche nicht auf die Beispiel-Datenbank begrenzt ist.
function renderEstimateOption(query) {
estimateChips.innerHTML = "";
GENERIC_CATEGORIES.forEach((cat) => {
const chip = document.createElement("button");
chip.className = "chip";
chip.type = "button";
chip.textContent = cat.label;
chip.addEventListener("click", () => {
selectCar(buildEstimatedCar(query, cat));
estimateBox.hidden = true;
});
estimateChips.appendChild(chip);
});
estimateBox.hidden = false;
}
function buildEstimatedCar(query, cat) {
return {
id: "estimate-" + cat.id,
brand: query,
model: "",
bodyType: cat.bodyType,
cargoLiters: cat.cargoLiters,
cargoLitersMax: cat.cargoLitersMax,
length_mm: cat.length_mm,
widthFloor_mm: cat.widthFloor_mm,
widthShoulder_mm: cat.widthShoulder_mm,
height_mm: cat.height_mm,
sillHeight_mm: cat.sillHeight_mm,
underFloorDepth_mm: cat.underFloorDepth_mm,
isEstimate: true,
};
}
function handleVin(vin) {
const wmi = vin.slice(0, 3);
const brand = wmiTable[wmi];
if (!brand) {
hintBox.hidden = false;
hintBox.textContent = `VIN erkannt, aber Herstellerkürzel "${wmi}" ist in dieser Demo-Tabelle nicht hinterlegt. Bitte Marke/Modell manuell eingeben.`;
suggestionsBox.hidden = true;
return;
}
const brandCars = cars.filter((c) => c.brand === brand);
hintBox.hidden = false;
hintBox.textContent = `VIN erkannt → Hersteller: ${brand} (aus Kürzel "${wmi}"). Bitte Modell auswählen:`;
renderSuggestions(brandCars);
}
// Gängige Kurzformen/Schreibweisen, damit z. B. "VW Golf" auch "Volkswagen Golf" findet
const BRAND_ALIASES = {
vw: "volkswagen", mb: "mercedes-benz", mercedes: "mercedes-benz", benz: "mercedes-benz",
chevy: "chevrolet", vag: "volkswagen",
};
function normalizeQuery(query) {
return query
.normalize("NFD").replace(/[̀-ͯ]/g, "") // Akzente entfernen, z. B. Citroen statt Citroën
.toLowerCase()
.split(/\s+/)
.map((word) => BRAND_ALIASES[word] || word)
.join(" ");
}
function filterCars(query) {
const q = normalizeQuery(query);
return cars
.filter((c) => normalizeQuery(`${c.brand} ${c.model}`).includes(q))
.slice(0, 8);
}
function renderSuggestions(matches) {
if (matches.length === 0) {
suggestionsBox.hidden = true;
return;
}
suggestionsBox.innerHTML = "";
matches.forEach((car) => {
const item = document.createElement("div");
item.className = "suggestion-item";
item.innerHTML = `<span class="s-name">${car.brand} ${car.model}</span><span class="s-meta">${car.bodyType} · ${car.cargoLiters} L</span>`;
item.addEventListener("click", () => {
searchInput.value = `${car.brand} ${car.model}`;
selectCar(car);
suggestionsBox.hidden = true;
});
suggestionsBox.appendChild(item);
});
suggestionsBox.hidden = false;
}
function onKeyDown(e) {
const items = suggestionsBox.querySelectorAll(".suggestion-item");
if (suggestionsBox.hidden || items.length === 0) return;
if (e.key === "ArrowDown") {
e.preventDefault();
activeSuggestionIndex = Math.min(activeSuggestionIndex + 1, items.length - 1);
updateActiveSuggestion(items);
} else if (e.key === "ArrowUp") {
e.preventDefault();
activeSuggestionIndex = Math.max(activeSuggestionIndex - 1, 0);
updateActiveSuggestion(items);
} else if (e.key === "Enter") {
e.preventDefault();
const idx = activeSuggestionIndex >= 0 ? activeSuggestionIndex : 0;
items[idx].dispatchEvent(new Event("click"));
} else if (e.key === "Escape") {
suggestionsBox.hidden = true;
}
}
function updateActiveSuggestion(items) {
items.forEach((el, i) => el.classList.toggle("active", i === activeSuggestionIndex));
}
// ---------- 3D Szene ----------
let renderer, scene, camera, controls, trunkGroup;
let carpetTexBase = null;
let boxTexBase = null;
let currentTub = null; // Geometrie-Kenndaten des aktuell gewählten Kofferraums
let subMesh = null; // aktuelle Subwoofer-Box (falls platziert)
let subDimsM = null;
function setupScene() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(45, viewerEl.clientWidth / viewerEl.clientHeight || 1, 0.05, 50);
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
// #content ist beim initialen Laden noch [hidden] (kein Auto gewählt), daher hat #viewer hier
// clientWidth/Height von 0 — sichere Fallback-Maße verwenden, echte Größe kommt später via onResize().
renderer.setSize(viewerEl.clientWidth || 800, viewerEl.clientHeight || 600);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
viewerEl.appendChild(renderer.domElement);
// Weiche Studio-Umgebungsreflexion, damit Materialien nicht flach/plastikartig wirken
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
// Heller, neutraler Hintergrund wie in einer 3D-Design-/CAD-Software
scene.background = new THREE.Color(0xf3f4f6);
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.minDistance = 0.5;
controls.maxDistance = 8;
controls.maxPolarAngle = Math.PI * 0.49;
const hemi = new THREE.HemisphereLight(0xffffff, 0xd8dbe0, 1.5);
scene.add(hemi);
const key = new THREE.DirectionalLight(0xfff6e8, 1.8);
key.position.set(2.2, 3.2, 1.8);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.camera.left = -1.6;
key.shadow.camera.right = 1.6;
key.shadow.camera.top = 1.6;
key.shadow.camera.bottom = -1.6;
key.shadow.camera.near = 0.2;
key.shadow.camera.far = 8;
key.shadow.bias = -0.0018;
key.shadow.radius = 3;
scene.add(key);
const fill = new THREE.DirectionalLight(0x9fc8ff, 0.28);
fill.position.set(-2.2, 1.4, -1.6);
scene.add(fill);
// Aufhelllicht, damit der Kofferraum-Innenraum trotz umschließender Heckklappe/Stoßstange gut ablesbar bleibt
// (Ambient statt Punktlicht, da PointLight-Intensität in Lumen/Candela kaum spürbar auf Raumdistanz wirkt)
const interiorFill = new THREE.AmbientLight(0xffffff, 0.9);
scene.add(interiorFill);
trunkGroup = new THREE.Group();
scene.add(trunkGroup);
carpetTexBase = createNoiseTexture("#2c2d30", 190, 40, 0.11);
boxTexBase = createNoiseTexture("#46474b", 210, 35, 0.1);
// Heller Boden mit Referenzgitter, wie im Viewport einer 3D-Design-Software.
// Liegt unterhalb der tiefsten Unterboden-Mulde, sonst würde er sie überdecken.
const groundY = -0.4;
const groundGeo = new THREE.CircleGeometry(18, 64);
const ground = new THREE.Mesh(groundGeo, new THREE.MeshStandardMaterial({ color: 0xf7f7f9, roughness: 1 }));
ground.rotation.x = -Math.PI / 2;
ground.position.y = groundY;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(6, 24, 0xb9bcc3, 0xdcdee2);
grid.position.y = groundY + 0.001;
scene.add(grid);
setupDragging();
window.addEventListener("resize", onResize);
new ResizeObserver(onResize).observe(viewerEl);
animate();
}
function onResize() {
if (!renderer) return;
const w = viewerEl.clientWidth;
const h = viewerEl.clientHeight || 420;
if (w === 0 || h === 0) return;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
// Prozedurale Stoff-/Filz-Textur (feines Rauschen um eine Basisfarbe)
function createNoiseTexture(baseColor, speckleBase, speckleRange, alpha) {
const size = 128;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
ctx.fillStyle = baseColor;
ctx.fillRect(0, 0, size, size);
for (let i = 0; i < 2400; i++) {
const x = Math.random() * size;
const y = Math.random() * size;
const shade = Math.random() * speckleRange;
const v = Math.round(speckleBase + shade);
ctx.fillStyle = `rgba(${v},${v},${v + 4},${Math.random() * alpha})`;
ctx.fillRect(x, y, 1, 1);
}
const tex = new THREE.CanvasTexture(canvas);
tex.wrapS = THREE.RepeatWrapping;
tex.wrapT = THREE.RepeatWrapping;
tex.colorSpace = THREE.SRGBColorSpace;
return tex;
}
function paintMaterial(color) {
return new THREE.MeshStandardMaterial({
color,
metalness: 0.1,
roughness: 0.7,
});
}
function fabricMaterial(base, repeatX, repeatY, roughness = 0.92) {
const tex = base.clone();
tex.needsUpdate = true;
tex.wrapS = THREE.RepeatWrapping;
tex.wrapT = THREE.RepeatWrapping;
tex.repeat.set(Math.max(repeatX, 0.5), Math.max(repeatY, 0.5));
return new THREE.MeshStandardMaterial({
map: tex,
roughness,
metalness: 0.0,
side: THREE.DoubleSide,
});
}
// Quad mit UV-Koordinaten (0..1), damit Texturen korrekt gekachelt werden
function quad(p1, p2, p3, p4, material) {
const geo = new THREE.BufferGeometry();
const verts = new Float32Array([
...p1, ...p2, ...p3,
...p1, ...p3, ...p4,
]);
const uvs = new Float32Array([
0, 0, 1, 0, 1, 1,
0, 0, 1, 1, 0, 1,
]);
geo.setAttribute("position", new THREE.BufferAttribute(verts, 3));
geo.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));
geo.computeVertexNormals();
const mesh = new THREE.Mesh(geo, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
// Heckpartie: Stoßstangen-Rahmen, Rückleuchten und eine aufgeklappte Heckklappe.
// Die Ladeöffnung liegt real am Heck (nicht Richtung Rücksitzbank), daher sitzt diese Baugruppe bei zBack.
function buildRearAssembly(bw, tw, h, zBack) {
const group = new THREE.Group();
const frameDepth = 0.06;
const bumperDrop = Math.max(h * 0.35, 0.18);
const headerH = Math.max(h * 0.32, 0.18);
const bodyTopY = h + headerH;
const paintMat = paintMaterial(BODY_PAINT_COLOR);
const trimMat = new THREE.MeshStandardMaterial({ color: 0x1c1d20, roughness: 0.85 });
const lightMat = new THREE.MeshPhysicalMaterial({
color: 0x7a0f14, emissive: 0x660000, emissiveIntensity: 0.4, metalness: 0.3, roughness: 0.3, clearcoat: 0.8,
});
const zA = zBack;
const zB = zBack + frameDepth;
// Pfosten links/rechts: schließen exakt an die obere Wannenkante an und laufen bis zur Dachkante hoch
[-1, 1].forEach((side) => {
group.add(quad(
[side * tw, h, zA], [side * tw, h, zB], [side * tw, bodyTopY, zB], [side * tw, bodyTopY, zA],
paintMat
));
});
// Oberer Abschluss / Anschlag der Heckklappe
group.add(quad(
[-tw, bodyTopY, zA], [tw, bodyTopY, zA], [tw, bodyTopY, zB], [-tw, bodyTopY, zB],
paintMat
));
// Stoßstange unten (breiter als die Ladefläche, reicht unter den Kofferraumboden)
const bumperHalfWidth = tw * 1.12;
group.add(quad(
[-bumperHalfWidth, -bumperDrop, zA], [bumperHalfWidth, -bumperDrop, zA],
[bumperHalfWidth, 0, zB], [-bumperHalfWidth, 0, zB],
paintMat
));
// Rückleuchten
[-1, 1].forEach((side) => {
const lightW = tw * 0.16, lightH = headerH * 0.6, lightD = 0.03;
const lightGeo = new RoundedBoxGeometry(lightW, lightH, lightD, 2, Math.min(lightW, lightH, lightD) * 0.3);
const light = new THREE.Mesh(lightGeo, lightMat);
light.position.set(side * (tw * 0.94), h + headerH * 0.5, zB + 0.02);
light.castShadow = true;
group.add(light);
});
// Geöffnete Heckklappe: am oberen Rand angeschlagen, steht aufgeklappt nach oben
const lidWidth = tw * 1.9;
const lidLength = Math.max(h * 1.25, 0.55);
const lidThickness = 0.03;
const lidGeo = new RoundedBoxGeometry(lidWidth, lidLength, lidThickness, 2, lidThickness * 0.6);
lidGeo.translate(0, lidLength / 2, 0); // Scharnierkante liegt bei lokal y = 0
const lid = new THREE.Mesh(lidGeo, [paintMat, paintMat, paintMat, paintMat, trimMat, paintMat]);
lid.castShadow = true;
lid.receiveShadow = true;
const pivot = new THREE.Group();
pivot.position.set(0, bodyTopY, zB);
pivot.rotation.x = lidOpen ? LID_OPEN_ANGLE : LID_CLOSED_ANGLE;
pivot.add(lid);
group.add(pivot);
return { group, lidPivot: pivot };
}
// Zwischenboden mit optionaler Mulde darunter (Reserverad-Bereich). Ohne underFloorDepthM
// wird nur ein einfacher fester Boden gebaut (z. B. beim Porsche-Frunk).
function buildFloorAssembly(bw, L, zFront, zBack, underFloorDepthM) {
const group = new THREE.Group();
const floorMat = fabricMaterial(carpetTexBase, bw * 2 * 6, L * 6);
if (!underFloorDepthM) {
group.add(quad(
[-bw, 0, zFront], [bw, 0, zFront], [bw, 0, zBack], [-bw, 0, zBack],
floorMat
));
return { group, floorPivot: null };
}
const wellHalfWidth = bw * 0.82;
const wellZ0 = zFront + L * 0.08;
const wellZ1 = zBack - L * 0.08;
const d = underFloorDepthM;
const trayMat = new THREE.MeshStandardMaterial({ color: 0x54565b, roughness: 0.55, metalness: 0.12, side: THREE.DoubleSide });
// Muldenboden
group.add(quad(
[-wellHalfWidth, -d, wellZ0], [wellHalfWidth, -d, wellZ0],
[wellHalfWidth, -d, wellZ1], [-wellHalfWidth, -d, wellZ1],
trayMat
));
// Muldenwände
group.add(quad([-wellHalfWidth, -d, wellZ0], [-wellHalfWidth, -d, wellZ1], [-wellHalfWidth, 0, wellZ1], [-wellHalfWidth, 0, wellZ0], trayMat));
group.add(quad([wellHalfWidth, -d, wellZ1], [wellHalfWidth, -d, wellZ0], [wellHalfWidth, 0, wellZ0], [wellHalfWidth, 0, wellZ1], trayMat));
group.add(quad([-wellHalfWidth, -d, wellZ0], [wellHalfWidth, -d, wellZ0], [wellHalfWidth, 0, wellZ0], [-wellHalfWidth, 0, wellZ0], trayMat));
group.add(quad([wellHalfWidth, -d, wellZ1], [-wellHalfWidth, -d, wellZ1], [-wellHalfWidth, 0, wellZ1], [wellHalfWidth, 0, wellZ1], trayMat));
// Angedeutete Reserverad-Mulde
const spareRadius = Math.min(wellHalfWidth, (wellZ1 - wellZ0) / 2) * 0.7;
const spareRing = new THREE.Mesh(
new THREE.TorusGeometry(spareRadius, Math.max(d * 0.32, 0.015), 10, 28),
new THREE.MeshStandardMaterial({ color: 0x3a3b3e, roughness: 0.7 })
);
spareRing.rotation.x = Math.PI / 2;
spareRing.position.set(0, -d * 0.5, (wellZ0 + wellZ1) / 2);
group.add(spareRing);
// Ladeboden-Klappe: am zFront-Rand angeschlagen, lässt sich anheben
const floorGeo = new THREE.BoxGeometry(bw * 2, 0.018, L);
floorGeo.translate(0, 0, L / 2); // Scharnierkante liegt bei lokal z = 0
const floorBoard = new THREE.Mesh(floorGeo, floorMat);
floorBoard.castShadow = true;
floorBoard.receiveShadow = true;
const pivot = new THREE.Group();
pivot.position.set(0, 0.001, zFront);
pivot.rotation.x = floorLifted ? FLOOR_UP_ANGLE : FLOOR_DOWN_ANGLE;
pivot.add(floorBoard);
group.add(pivot);
return { group, floorPivot: pivot };
}
function buildTrunkMesh(car) {
const L = car.length_mm / 1000;
const bw = car.widthFloor_mm / 2000;
const tw = car.widthShoulder_mm / 2000;
const h = car.height_mm / 1000;
const group = new THREE.Group();
const zFront = -L / 2; // Richtung Fahrgastraum / Ladeöffnung
const zBack = L / 2; // Heck
const wallMat = fabricMaterial(carpetTexBase, L * 6, h * 8);
const backMat = fabricMaterial(carpetTexBase, tw * 2 * 6, h * 8);
// Zwischenboden (ggf. mit Mulde für Reserverad/Stauraum darunter)
const underFloorDepthM = car.underFloorDepth_mm ? car.underFloorDepth_mm / 1000 : null;
const floorAssembly = buildFloorAssembly(bw, L, zFront, zBack, underFloorDepthM);
group.add(floorAssembly.group);
floorPivot = floorAssembly.floorPivot;
// linke Seitenwand (flared nach oben)
group.add(quad(
[-bw, 0, zFront], [-bw, 0, zBack], [-tw, h, zBack], [-tw, h, zFront],
wallMat
));
// rechte Seitenwand
group.add(quad(
[bw, 0, zFront], [tw, h, zFront], [tw, h, zBack], [bw, 0, zBack],
wallMat
));
// Feste Trennwand Richtung Rücksitzbank (Ladeöffnung liegt am Heck, siehe unten)
group.add(quad(
[-bw, 0, zFront], [bw, 0, zFront], [tw, h, zFront], [-tw, h, zFront],
backMat
));
// Heck: Stoßstangen-Rahmen, Rückleuchten und Heckklappe um die Ladeöffnung
const rear = buildRearAssembly(bw, tw, h, zBack);
group.add(rear.group);
lidPivot = rear.lidPivot;
// Radkästen: zwei carpet-farbene Wölbungen nahe der Ladeöffnung (Rücksitzbank-Seite)
const archRadius = Math.min(h, bw) * 0.4;
const archLength = L * 0.28;
const archZ = zFront + archLength * 0.9;
const archBaseColor = 0x35373b;
const archMeshes = [];
[-1, 1].forEach((side) => {
const archGeo = new THREE.CylinderGeometry(archRadius, archRadius, archLength, 24, 1);
const archMat = fabricMaterial(carpetTexBase, 1.4, 1.4, 0.95);
archMat.color.set(archBaseColor);
const arch = new THREE.Mesh(archGeo, archMat);
arch.rotation.x = Math.PI / 2;
arch.position.set(side * (bw - archRadius * 0.45), archRadius * 0.95, archZ);
arch.castShadow = true;
arch.receiveShadow = true;
group.add(arch);
archMeshes.push(arch);
});
// Referenzobjekt: Kabinentrolley 55 x 40 x 20 cm (optional einblendbar)
if (showCaseReference) {
const caseDims = { w: 0.4, h: 0.55, d: 0.2 };
if (caseDims.w < bw * 2 * 0.9 && caseDims.h < h * 1.4) {
const caseGeo = new RoundedBoxGeometry(caseDims.w, caseDims.h, caseDims.d, 3, Math.min(caseDims.w, caseDims.h, caseDims.d) * 0.14);
const caseMat = new THREE.MeshStandardMaterial({ color: 0xcbb994, roughness: 0.65 });
const caseMesh = new THREE.Mesh(caseGeo, caseMat);
const caseX = Math.min(bw, tw) * 0.55;
caseMesh.position.set(caseX, caseDims.h / 2 + 0.005, zFront + archLength + caseDims.d * 0.8);
caseMesh.castShadow = true;
caseMesh.receiveShadow = true;
group.add(caseMesh);
}
}
currentTub = {
L, bw, tw, h, zFront, zBack, archRadius, archLength, archZ,
archMeshes, archBaseColor,
};
return group;
}
function rebuildTrunkOnly() {
if (!currentCar) return;
if (trunkGroup) scene.remove(trunkGroup);
trunkGroup = buildTrunkMesh(currentCar);
scene.add(trunkGroup);
if (subMesh) updateFitStatus();
}
function selectCar(car) {
content.hidden = false;
emptyState.hidden = true;
currentCar = car;
renderInfoPanel(car);
floorToggleRow.hidden = !car.underFloorDepth_mm;
if (trunkGroup) {
scene.remove(trunkGroup);
}
trunkGroup = buildTrunkMesh(car);
scene.add(trunkGroup);
const L = car.length_mm / 1000;
const W = car.widthShoulder_mm / 1000;
const H = car.height_mm / 1000;
const dist = Math.max(L, W, H) * 2.3 + 0.5;
camera.position.set(dist * 0.7, H * 0.9 + dist * 0.55, dist * 0.95);
controls.target.set(0, H * 0.55, 0);
controls.update();
// vorhandene Subwoofer-Box an neue Kofferraumgröße anpassen (Standardposition)
if (subDimsM) {
placeSub(subDimsM.w, subDimsM.h, subDimsM.d, true);
}
requestAnimationFrame(onResize);
}
function renderInfoPanel(car) {
const maxLine = car.cargoLitersMax
? `<div class="spec-row"><span class="label">Max. (Sitze umgelegt)</span><span class="value">${car.cargoLitersMax} L</span></div>`
: "";
const underFloorLine = car.underFloorDepth_mm
? `<div class="spec-row"><span class="label">Stauraum unter dem Zwischenboden</span><span class="value">ca. ${car.underFloorDepth_mm} mm tief</span></div>`
: "";
const estimateNote = car.isEstimate
? `<p class="legend-note estimate-note">
Für „${car.brand}“ liegen keine spezifischen Werte vor. Die Maße sind eine grobe Schätzung
anhand der Fahrzeugklasse „${car.bodyType.replace(" (Schätzung)", "")}“, keine Angaben zum konkreten Modell.
</p>`
: "";
infoPanel.innerHTML = `
<h2>${`${car.brand} ${car.model}`.trim()}</h2>
<div class="body-type">${car.bodyType}</div>
${estimateNote}
<div class="spec-highlight">
<div class="num">${car.cargoLiters}</div>
<div class="unit">Liter Kofferraumvolumen (VDA)</div>
</div>
${maxLine}
<div class="spec-row"><span class="label">Ladelänge</span><span class="value">${car.length_mm} mm</span></div>
<div class="spec-row"><span class="label">Breite (Boden)</span><span class="value">${car.widthFloor_mm} mm</span></div>
<div class="spec-row"><span class="label">Breite (Schulter)</span><span class="value">${car.widthShoulder_mm} mm</span></div>
<div class="spec-row"><span class="label">Ladehöhe</span><span class="value">${car.height_mm} mm</span></div>
<div class="spec-row"><span class="label">Ladekantenhöhe</span><span class="value">${car.sillHeight_mm} mm</span></div>
${underFloorLine}
<p class="legend-note">
Die beiden Wölbungen im Kofferraum sind die Radkästen der Hinterachse — dort ist real weniger Platz.
Sie färben sich rot, sobald die Subwoofer-Box dort anstößt.
${car.underFloorDepth_mm ? "Über den Schalter „Zwischenboden“ lässt sich die Reserverad-Mulde darunter zeigen — ein beliebter Einbauort für Endstufen." : ""}
</p>
`;
}
// ---------- Subwoofer-Box ----------
function buildSubGroup(wM, hM, dM) {
const group = new THREE.Group();
const wrapMat = fabricMaterial(boxTexBase, (wM + dM), hM * 3, 0.85);
const boxGeo = new RoundedBoxGeometry(wM, hM, dM, 3, Math.min(wM, hM, dM) * 0.07);
const box = new THREE.Mesh(boxGeo, wrapMat);
box.name = "subBoxCore";
box.castShadow = true;
box.receiveShadow = true;
group.add(box);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(box.geometry, 20),
new THREE.LineBasicMaterial({ color: 0x1a1a1c })
);
box.add(edges);
// Treiber-Attrappe (Korb + Sicke + Zierring) auf der Oberseite
const driverRadius = Math.min(wM, dM) * 0.32;
const basket = new THREE.Mesh(
new THREE.CircleGeometry(driverRadius, 32),
new THREE.MeshStandardMaterial({ color: 0x0d0e10, roughness: 0.4, metalness: 0.4 })
);
basket.rotation.x = -Math.PI / 2;
basket.position.set(0, hM / 2 + 0.002, 0);
basket.receiveShadow = true;
group.add(basket);
const surround = new THREE.Mesh(
new THREE.RingGeometry(driverRadius * 0.97, driverRadius * 1.1, 32),
new THREE.MeshStandardMaterial({ color: 0x1c1d20, roughness: 0.7 })
);
surround.rotation.x = -Math.PI / 2;
surround.position.set(0, hM / 2 + 0.0015, 0);
group.add(surround);
const trim = new THREE.Mesh(
new THREE.TorusGeometry(driverRadius * 1.08, driverRadius * 0.035, 12, 40),
new THREE.MeshStandardMaterial({
color: 0xff8a3d, roughness: 0.4, metalness: 0.5,
})
);
trim.rotation.x = Math.PI / 2;
trim.position.set(0, hM / 2 + 0.003, 0);
group.add(trim);
group.userData.core = box;
return group;
}
function addOrUpdateSub(wCm, hCm, dCm) {
if (!currentTub) return;
if (!wCm || !hCm || !dCm || wCm <= 0 || hCm <= 0 || dCm <= 0) return;
placeSub(wCm / 100, hCm / 100, dCm / 100, true);
}
function placeSub(wM, hM, dM, resetPosition) {
const prevPos = subMesh ? subMesh.position.clone() : null;
if (subMesh) {
scene.remove(subMesh);
}
subMesh = buildSubGroup(wM, hM, dM);
subDimsM = { w: wM, h: hM, d: dM };
if (resetPosition || !prevPos) {
// Standard: mittig, an der Heckwand anliegend
const z = currentTub.zBack - dM / 2 - 0.02;
subMesh.position.set(0, hM / 2 + 0.002, z);
} else {
subMesh.position.copy(prevPos);
subMesh.position.y = hM / 2 + 0.002;
}
scene.add(subMesh);
subRemove.hidden = false;
updateFitStatus();
}
function removeSub() {
if (subMesh) scene.remove(subMesh);
subMesh = null;
subDimsM = null;
subRemove.hidden = true;
subStatus.hidden = true;
[...subPresetsBox.children].forEach((c) => c.classList.remove("active"));
resetArchTint();
}
// Verfügbare Halbbreite der Wanne auf Höhe y (lineare Interpolation zwischen Boden- und Schulterbreite)
function tubHalfWidthAt(y) {
const t = Math.max(0, Math.min(1, y / currentTub.h));
return currentTub.bw + (currentTub.tw - currentTub.bw) * t;
}
function resetArchTint() {
if (!currentTub || !currentTub.archMeshes) return;
currentTub.archMeshes.forEach((m) => m.material.color.set(currentTub.archBaseColor));
}
function updateFitStatus() {
if (!subMesh || !currentTub) return;
const { w, h, d } = subDimsM;
const cx = subMesh.position.x;
const cz = subMesh.position.z;
const x0 = cx - w / 2, x1 = cx + w / 2;
const z0 = cz - d / 2, z1 = cz + d / 2;
const problems = [];
const halfAtTop = tubHalfWidthAt(h);
if (x0 < -halfAtTop || x1 > halfAtTop) problems.push("Box ist breiter als der Kofferraum an dieser Stelle");
if (h > currentTub.h * 1.15) problems.push("Box ist höher als der nutzbare Laderaum");
if (z0 < currentTub.zFront - 0.005 || z1 > currentTub.zBack + 0.005) {
problems.push("Box ragt über die Ladeöffnung am Heck oder die Rückwand zur Rücksitzbank hinaus");
}
// Kollision mit Radkästen prüfen (und die betroffene Seite optisch markieren)
const archXLeft = -(currentTub.bw - currentTub.archRadius * 0.45);
const archXRight = currentTub.bw - currentTub.archRadius * 0.45;
const archZ0 = currentTub.archZ - currentTub.archLength / 2;
const archZ1 = currentTub.archZ + currentTub.archLength / 2;
const overlapsArchZ = z0 < archZ1 && z1 > archZ0;
const overlapsArchLeft = overlapsArchZ && x0 < archXLeft + currentTub.archRadius * 0.95 && h < currentTub.archRadius * 1.9;
const overlapsArchRight = overlapsArchZ && x1 > archXRight - currentTub.archRadius * 0.95 && h < currentTub.archRadius * 1.9;
resetArchTint();
if (overlapsArchLeft) currentTub.archMeshes[0].material.color.set(0xcc4a3a);
if (overlapsArchRight) currentTub.archMeshes[1].material.color.set(0xcc4a3a);
if (overlapsArchLeft || overlapsArchRight) problems.push("Box stößt an einen Radkasten");
subStatus.hidden = false;
if (problems.length === 0) {
subStatus.className = "sub-status ok";
const clearance = Math.round((halfAtTop - Math.max(Math.abs(x0), Math.abs(x1))) * 1000);
subStatus.textContent = `Passt – ca. ${Math.max(clearance, 0)} mm Luft zur Seitenwand.`;
setSubTint(false);
} else {
subStatus.className = "sub-status bad";
subStatus.textContent = "Passt so nicht: " + problems.join("; ") + ".";
setSubTint(true);
}
}
function setSubTint(bad) {
const core = subMesh.userData.core;
core.material.emissive = new THREE.Color(bad ? 0x3a0d0d : 0x000000);
}
// ---------- Ziehen der Subwoofer-Box ----------
function setupDragging() {
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const dragOffset = new THREE.Vector3();
let dragging = false;
function setPointer(e) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
}
renderer.domElement.addEventListener("pointerdown", (e) => {
if (!subMesh) return;
setPointer(e);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObject(subMesh, true);
if (hits.length === 0) return;
dragPlane.set(new THREE.Vector3(0, 1, 0), -subMesh.position.y);
const hitPoint = new THREE.Vector3();
raycaster.ray.intersectPlane(dragPlane, hitPoint);
dragOffset.copy(subMesh.position).sub(hitPoint);
dragging = true;
controls.enabled = false;
renderer.domElement.setPointerCapture(e.pointerId);
});
renderer.domElement.addEventListener("pointermove", (e) => {
if (!dragging || !subMesh) return;
setPointer(e);
raycaster.setFromCamera(pointer, camera);
const hitPoint = new THREE.Vector3();
if (raycaster.ray.intersectPlane(dragPlane, hitPoint)) {
subMesh.position.x = hitPoint.x + dragOffset.x;
subMesh.position.z = hitPoint.z + dragOffset.z;
updateFitStatus();
}
});
function endDrag(e) {
if (!dragging) return;
dragging = false;
controls.enabled = true;
try { renderer.domElement.releasePointerCapture(e.pointerId); } catch (_) {}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointerleave", endDrag);
}