Archived
1010 lines
40 KiB
HTML
1010 lines
40 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Bitua 3D Explorer - Interactive</title>
|
||
<style>
|
||
:root {
|
||
--primary: #007aff;
|
||
--bg: #f5f5f7;
|
||
--card-bg: #ffffff;
|
||
--text: #1d1d1f;
|
||
}
|
||
|
||
body {
|
||
margin: 0;
|
||
font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
|
||
background-color: var(--bg);
|
||
color: var(--text);
|
||
overflow: hidden;
|
||
display: flex;
|
||
flex-direction: column;
|
||
height: 100vh;
|
||
}
|
||
|
||
header {
|
||
padding: 20px;
|
||
text-align: center;
|
||
background: rgba(255, 255, 255, 0.8);
|
||
backdrop-filter: blur(20px);
|
||
z-index: 10;
|
||
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.05);
|
||
}
|
||
|
||
header h1 {
|
||
margin: 0;
|
||
font-size: 24px;
|
||
font-weight: 600;
|
||
}
|
||
|
||
header p {
|
||
margin: 5px 0 0;
|
||
opacity: 0.6;
|
||
font-size: 14px;
|
||
}
|
||
|
||
#container {
|
||
flex: 1;
|
||
position: relative;
|
||
width: 100%;
|
||
}
|
||
|
||
#three-canvas {
|
||
width: 100%;
|
||
height: 100%;
|
||
display: block;
|
||
}
|
||
|
||
/* Loading UI */
|
||
#loader {
|
||
position: absolute;
|
||
top: 0;
|
||
left: 0;
|
||
width: 100%;
|
||
height: 100%;
|
||
background: var(--bg);
|
||
display: flex;
|
||
flex-direction: column;
|
||
justify-content: center;
|
||
align-items: center;
|
||
z-index: 100;
|
||
transition: opacity 0.5s ease;
|
||
}
|
||
|
||
.progress-bar {
|
||
width: 200px;
|
||
height: 4px;
|
||
background: #e0e0e0;
|
||
border-radius: 2px;
|
||
overflow: hidden;
|
||
margin-top: 20px;
|
||
}
|
||
|
||
#progress {
|
||
width: 0%;
|
||
height: 100%;
|
||
background: var(--primary);
|
||
transition: width 0.3s ease;
|
||
}
|
||
|
||
/* Info Overlay */
|
||
.info-panel {
|
||
position: absolute;
|
||
bottom: 30px;
|
||
left: 50%;
|
||
transform: translateX(-50%);
|
||
background: rgba(0, 0, 0, 0.7);
|
||
color: white;
|
||
padding: 12px 24px;
|
||
border-radius: 30px;
|
||
font-size: 14px;
|
||
pointer-events: none;
|
||
backdrop-filter: blur(10px);
|
||
text-align: center;
|
||
z-index: 5;
|
||
}
|
||
|
||
/* Interaction Tooltip (Click to open) */
|
||
#tooltip {
|
||
position: absolute;
|
||
background: white;
|
||
padding: 8px 16px;
|
||
border-radius: 8px;
|
||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
|
||
display: none;
|
||
pointer-events: none;
|
||
font-size: 12px;
|
||
font-weight: 500;
|
||
z-index: 20;
|
||
}
|
||
|
||
#sidebar {
|
||
position: absolute;
|
||
top: 100px;
|
||
right: 20px;
|
||
width: 280px;
|
||
background: rgba(255, 255, 255, 0.9);
|
||
backdrop-filter: blur(20px);
|
||
padding: 0;
|
||
border-radius: 20px;
|
||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
|
||
z-index: 10;
|
||
display: flex;
|
||
flex-direction: column;
|
||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||
overflow: hidden;
|
||
}
|
||
|
||
#sidebar.collapsed {
|
||
width: 60px;
|
||
height: 60px;
|
||
border-radius: 30px;
|
||
cursor: pointer;
|
||
}
|
||
|
||
#sidebar-header {
|
||
padding: 20px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
cursor: pointer;
|
||
user-select: none;
|
||
}
|
||
|
||
#sidebar-header h2 {
|
||
margin: 0;
|
||
font-size: 16px;
|
||
font-weight: 600;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
#sidebar-content {
|
||
padding: 0 24px 24px 24px;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 15px;
|
||
transition: opacity 0.2s;
|
||
}
|
||
|
||
#sidebar.collapsed #sidebar-content {
|
||
opacity: 0;
|
||
pointer-events: none;
|
||
}
|
||
|
||
#sidebar.collapsed #sidebar-header h2 {
|
||
display: none;
|
||
}
|
||
|
||
#sidebar-toggle-icon {
|
||
font-size: 20px;
|
||
transition: transform 0.3s;
|
||
}
|
||
|
||
#sidebar.collapsed #sidebar-toggle-icon {
|
||
transform: rotate(0deg);
|
||
}
|
||
|
||
#sidebar:not(.collapsed) #sidebar-toggle-icon {
|
||
transform: rotate(180deg);
|
||
}
|
||
</style>
|
||
</head>
|
||
|
||
<body>
|
||
|
||
<div id="loader">
|
||
<div style="font-weight: 600;">Initializing Experience...</div>
|
||
<div class="progress-bar">
|
||
<div id="progress"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<header>
|
||
<h1>Bitua 3D Explorer - GREEN V2.1</h1>
|
||
<p>Smart Cabinet Series (Updated)</p>
|
||
</header>
|
||
|
||
|
||
<div id="sidebar" class="collapsed">
|
||
<div id="sidebar-header">
|
||
<h2 id="sidebar-title">Capacity Simulator</h2>
|
||
<span id="sidebar-toggle-icon">📦</span>
|
||
</div>
|
||
<div id="sidebar-content">
|
||
<div class="input-group">
|
||
<label>Product Width (cm)</label>
|
||
<input type="number" id="prod-w" value="10" min="1">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Product Height (cm)</label>
|
||
<input type="number" id="prod-h" value="15" min="1">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Product Depth (cm)</label>
|
||
<input type="number" id="prod-d" value="10" min="1">
|
||
</div>
|
||
<button id="btn-simulate">Run Simulation</button>
|
||
|
||
<div id="result-panel">
|
||
Capacity Estimation: <br>
|
||
<span id="result-count">0</span> units fit inside.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="container">
|
||
<canvas id="three-canvas"></canvas>
|
||
<div id="tooltip">Click to interact</div>
|
||
</div>
|
||
|
||
<div class="info-panel">
|
||
🖱️ Click to interact | Right-click to pan | Simulator on the right
|
||
</div>
|
||
|
||
<!-- Scripts -->
|
||
<script type="importmap">
|
||
{
|
||
"imports": {
|
||
"three": "https://unpkg.com/three@0.162.0/build/three.module.js",
|
||
"three/addons/": "https://unpkg.com/three@0.162.0/examples/jsm/",
|
||
"gsap": "https://cdn.skypack.dev/gsap"
|
||
}
|
||
}
|
||
</script>
|
||
|
||
<script type="module">
|
||
import * as THREE from 'three';
|
||
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
||
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
|
||
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
|
||
import { RectAreaLightUniformsLib } from 'three/addons/lights/RectAreaLightUniformsLib.js';
|
||
import gsap from 'gsap';
|
||
|
||
// Initialize RectAreaLight support
|
||
RectAreaLightUniformsLib.init();
|
||
console.log("🚀 Bitua 3D Explorer - GREEN V2.1 script started");
|
||
alert("3D Experience Updated: Green Trays Version");
|
||
|
||
// --- Setup ---
|
||
const canvas = document.querySelector('#three-canvas');
|
||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
|
||
let internalLight = null; // Global reference for the cabinet light
|
||
renderer.setPixelRatio(window.devicePixelRatio);
|
||
renderer.setSize(window.innerWidth, window.innerHeight);
|
||
renderer.shadowMap.enabled = true;
|
||
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
|
||
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
||
renderer.toneMappingExposure = 1.0;
|
||
|
||
const scene = new THREE.Scene();
|
||
scene.background = new THREE.Color(0xf5f5f7); // Light grey background
|
||
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
|
||
camera.position.set(3, 1.5, 5); // Improved side-front view
|
||
|
||
const controls = new OrbitControls(camera, renderer.domElement);
|
||
controls.enableDamping = true;
|
||
controls.dampingFactor = 0.05;
|
||
|
||
// --- Lighting ---
|
||
const ambientLight = new THREE.AmbientLight(0xffffff, 1.0);
|
||
scene.add(ambientLight);
|
||
|
||
const spotLight = new THREE.SpotLight(0xffffff, 60);
|
||
spotLight.position.set(5, 5, 5);
|
||
spotLight.castShadow = true;
|
||
scene.add(spotLight);
|
||
|
||
const fillLight = new THREE.DirectionalLight(0xffffff, 0.8);
|
||
fillLight.position.set(-5, 2, -5);
|
||
scene.add(fillLight);
|
||
|
||
// Add a basic environment map for reflections (makes metal/glass look real)
|
||
const pmremGenerator = new THREE.PMREMGenerator(renderer);
|
||
pmremGenerator.compileEquirectangularShader();
|
||
const envScene = new THREE.Scene();
|
||
|
||
// Add multiple lights to the environment to create rich reflections
|
||
const envLight1 = new THREE.PointLight(0xffffff, 100);
|
||
envLight1.position.set(5, 10, 5);
|
||
envScene.add(envLight1);
|
||
|
||
const envLight2 = new THREE.PointLight(0xffffff, 80);
|
||
envLight2.position.set(-5, 5, -5);
|
||
envScene.add(envLight2);
|
||
|
||
const envLight3 = new THREE.RectAreaLight(0xffffff, 50, 10, 10);
|
||
envLight3.position.set(0, 10, 0);
|
||
envLight3.lookAt(0, 0, 0);
|
||
envScene.add(envLight3);
|
||
|
||
const renderTarget = pmremGenerator.fromScene(envScene);
|
||
scene.environment = renderTarget.texture;
|
||
|
||
// (Internal lighting is now handled by Barra LED in setupLEDBarLighting)
|
||
|
||
// --- Model Management ---
|
||
const loader = new GLTFLoader();
|
||
const dracoLoader = new DRACOLoader();
|
||
dracoLoader.setDecoderPath('https://www.gstatic.com/draco/versioned/decoders/1.5.6/');
|
||
loader.setDRACOLoader(dracoLoader);
|
||
|
||
let model = null;
|
||
let isDoorOpen = false;
|
||
let hingePivot = null; // THREE.Group at the hinge axis
|
||
let centerOffset = null;
|
||
|
||
// Hinge parameters (derived from model comparison data)
|
||
// The door rotates -120° on Y-axis around the hinge pin
|
||
const DOOR_OPEN_ANGLE = -(Math.PI * 120) / 180; // -120 degrees
|
||
|
||
function setupShadows(m) {
|
||
m.traverse((child) => {
|
||
if (child.isMesh) {
|
||
child.castShadow = true;
|
||
child.receiveShadow = true;
|
||
}
|
||
});
|
||
}
|
||
|
||
function setupGlassMaterials(m) {
|
||
// Polycarbonate Material (Realistic transparent plastic)
|
||
const polycarbonateMaterial = new THREE.MeshPhysicalMaterial({
|
||
color: 0x4caf50, // Green tint
|
||
transmission: 0.95, // Highly transmissive
|
||
opacity: 1, // Solid presence, let transmission handle transparency
|
||
thickness: 0.05, // Material thickness for refraction
|
||
roughness: 0.1,
|
||
metalness: 0,
|
||
ior: 1.58, // Index of Refraction for PC
|
||
depthWrite: true, // Better for Physical materials in many cases
|
||
envMapIntensity: 2.5, // Stronger reflections
|
||
side: THREE.DoubleSide
|
||
});
|
||
|
||
// Highly transparent glass material (Clear)
|
||
const glassMaterial = new THREE.MeshPhysicalMaterial({
|
||
color: 0xffffff,
|
||
transmission: 1.0,
|
||
opacity: 1,
|
||
thickness: 0.02,
|
||
roughness: 0,
|
||
metalness: 0,
|
||
ior: 1.5, // Index of Refraction for Class
|
||
depthWrite: true,
|
||
envMapIntensity: 3.0,
|
||
side: THREE.DoubleSide
|
||
});
|
||
|
||
// White non-transparent acrylic material
|
||
const acrylicMaterial = new THREE.MeshStandardMaterial({
|
||
color: 0xffffff, // White
|
||
roughness: 0.3, // Slightly rough plastic look
|
||
metalness: 0.0,
|
||
transparent: false,
|
||
envMapIntensity: 0.8,
|
||
side: THREE.DoubleSide
|
||
});
|
||
|
||
// Stainless Steel material for the lock
|
||
const stainlessMaterial = new THREE.MeshStandardMaterial({
|
||
color: 0xcccccc,
|
||
metalness: 1.0,
|
||
roughness: 0.2,
|
||
envMapIntensity: 2.0
|
||
});
|
||
|
||
const acrylicTargetNames = [
|
||
'A INTERIOR SEPARADOR IZQUIERDO:1',
|
||
'A INTERIOR SEPARADOR ATRAS:1',
|
||
'A INTERIOR SEPARADOR:1',
|
||
'V2.5 A INTERIOR SEPARADOR SUPERIOR:1',
|
||
'V2.5 A TAPA DE REGISTRO INFERIOR:1'
|
||
];
|
||
|
||
try {
|
||
const meshList = [];
|
||
console.log("🔍 Starting deep hierarchy traversal...");
|
||
|
||
m.traverse((child) => {
|
||
const meshName = child.name || "UNNAMED";
|
||
const parentName = (child.parent && child.parent.name) ? child.parent.name : "";
|
||
|
||
const normMesh = meshName.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||
const normParent = parentName.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||
|
||
// Combine names for matching: if it's in the hierarchy, we want it
|
||
const combinedNorm = normMesh + "_" + normParent;
|
||
|
||
if (child.isMesh) {
|
||
meshList.push({
|
||
mesh: meshName,
|
||
parent: parentName,
|
||
matched: false,
|
||
visible: child.visible
|
||
});
|
||
const lastEntry = meshList[meshList.length - 1];
|
||
|
||
// 1. HIDE THE DOOR: High priority
|
||
const isDoor = combinedNorm.includes('V251PPPVIDRIO') ||
|
||
(combinedNorm.includes('PUERTA') && combinedNorm.includes('VIDRIO')) ||
|
||
(combinedNorm.includes('GLASS') && combinedNorm.includes('DOOR'));
|
||
|
||
if (isDoor) {
|
||
child.visible = false;
|
||
lastEntry.matched = "👻 HIDDEN DOOR";
|
||
console.log(`👻 [HIERARCHY MATCH] Hiding: Mesh="${meshName}" Parent="${parentName}"`);
|
||
}
|
||
|
||
// 2. WHITE SUPPORTS for Trays
|
||
if (combinedNorm.includes('SOPORTE')) {
|
||
child.material = acrylicMaterial;
|
||
lastEntry.matched = "⚪ TRAY SUPPORT";
|
||
console.log(`⚪ [HIERARCHY MATCH] White Support: Mesh="${meshName}" Parent="${parentName}"`);
|
||
}
|
||
// 3. CLEAR GLASS for Glass Trays (Prioritize over green poly)
|
||
else if (combinedNorm.includes('BANDEJA') && (combinedNorm.includes('VIDRIO') || combinedNorm.includes('GLASS'))) {
|
||
child.material = glassMaterial;
|
||
lastEntry.matched = "💎 GLASS TRAY";
|
||
console.log(`💎 [HIERARCHY MATCH] Clear Glass Tray: Mesh="${meshName}" Parent="${parentName}"`);
|
||
}
|
||
// 4. GREEN POLYCARBONATE for other Trays
|
||
else if (combinedNorm.includes('BANDEJA')) {
|
||
child.material = polycarbonateMaterial;
|
||
lastEntry.matched = "🧪 GREEN TRAY";
|
||
console.log(`🧪 [HIERARCHY MATCH] Green Polycarbonate: Mesh="${meshName}" Parent="${parentName}"`);
|
||
}
|
||
// 3. TRANSPARENT GLASS for other glass parts
|
||
else if (combinedNorm.includes('VIDRIO') || combinedNorm.includes('GLASS')) {
|
||
if (child.visible) {
|
||
child.material = glassMaterial;
|
||
lastEntry.matched = "💎 GLASS";
|
||
console.log(`💎 [HIERARCHY MATCH] Glass: Mesh="${meshName}" Parent="${parentName}"`);
|
||
}
|
||
}
|
||
// 4. WHITE ACRYLIC for separators
|
||
else if (combinedNorm.includes('SEPARADOR') || acrylicTargetNames.includes(parentName.trim()) || acrylicTargetNames.includes(meshName.trim())) {
|
||
child.material = acrylicMaterial;
|
||
lastEntry.matched = "⚪ ACRYLIC";
|
||
console.log(`⚪ [HIERARCHY MATCH] White Acrylic: Mesh="${meshName}" Parent="${parentName}"`);
|
||
}
|
||
// 5. STAINLESS STEEL for Lock
|
||
else if (combinedNorm.includes('CILINDRO') || combinedNorm.includes('CERRADURA') || normMesh.includes('SOLID1102')) {
|
||
child.material = stainlessMaterial;
|
||
lastEntry.matched = "🔑 LOCK";
|
||
console.log(`🔑 [HIERARCHY MATCH] Stainless Steel Lock: Mesh="${meshName}" Parent="${parentName}"`);
|
||
}
|
||
}
|
||
});
|
||
|
||
console.log("📊 Model Mesh Inventory (Deep traversal):");
|
||
console.table(meshList);
|
||
|
||
} catch (error) {
|
||
console.error("❌ Critical error in setupGlassMaterials:", error);
|
||
}
|
||
}
|
||
|
||
function setupLEDBarLighting(m) {
|
||
let ledBarMesh = null;
|
||
console.log('--- 🔍 Scanning Model for LED Parts ---');
|
||
|
||
// Flexible name matching
|
||
const isLEDBar = (name) => {
|
||
if (!name) return false;
|
||
const normalized = name.toLowerCase().replace(/\s+/g, '');
|
||
return normalized.includes('barraled') ||
|
||
(normalized.includes('barra') && normalized.includes('led'));
|
||
};
|
||
|
||
m.traverse((child) => {
|
||
if (isLEDBar(child.name)) {
|
||
console.log(' Found Match:', child.name, child.isMesh ? '(Mesh)' : '(Group)');
|
||
|
||
// If it's a group, try to find a mesh inside it
|
||
if (child.isMesh) {
|
||
ledBarMesh = child;
|
||
} else if (child.children.length > 0) {
|
||
// Find the first mesh in the group
|
||
child.traverse((subChild) => {
|
||
if (subChild.isMesh && !ledBarMesh) {
|
||
ledBarMesh = subChild;
|
||
}
|
||
});
|
||
}
|
||
}
|
||
});
|
||
|
||
if (ledBarMesh) {
|
||
console.log('💡 Found Barra LED Mesh:', ledBarMesh.name, 'Applying emissive "ON" effect.');
|
||
|
||
// Set to a bright emissive material to look "ON"
|
||
ledBarMesh.material = new THREE.MeshStandardMaterial({
|
||
color: 0xffffff,
|
||
emissive: 0xffffff,
|
||
emissiveIntensity: 10, // High intensity to simulate glow
|
||
metalness: 0.1,
|
||
roughness: 0.1
|
||
});
|
||
|
||
// Add an actual interior light source to simulate light coming from the LED bar
|
||
const box = new THREE.Box3().setFromObject(ledBarMesh);
|
||
const size = new THREE.Vector3();
|
||
box.getSize(size);
|
||
|
||
const width = Math.max(size.x, 0.05);
|
||
const height = Math.max(size.z, 0.05);
|
||
|
||
const center = new THREE.Vector3();
|
||
box.getCenter(center);
|
||
|
||
// The door rotation logic depends on matrices not being preemptively updated globally.
|
||
// Convert center to local by directly subtracting the model's position since the model has no rotation.
|
||
const localPos = center.clone().sub(m.position);
|
||
|
||
// Use RectAreaLight for a realistic bar light effect
|
||
const rectLight = new THREE.RectAreaLight(0xffffff, 5, width, height);
|
||
rectLight.position.set(localPos.x, localPos.y - 0.02, localPos.z);
|
||
rectLight.rotation.x = -Math.PI / 2; // Point the light downward
|
||
m.add(rectLight);
|
||
|
||
// Add a PointLight for broader interior illumination
|
||
const pointLight = new THREE.PointLight(0xffffff, 3, 5); // Color, Intensity, Distance
|
||
pointLight.position.set(localPos.x, localPos.y - 0.05, localPos.z);
|
||
m.add(pointLight);
|
||
|
||
console.log('💡 Added interior lights at the LED bar position.');
|
||
} else {
|
||
console.warn('⚠️ Could not find "Barra LED" in the model');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Hinge Pivot Logic:
|
||
*
|
||
* From the CAD reference:
|
||
* - Blue side (left) = fixed to cabinet body, NEVER moves
|
||
* - Green side (right) = fixed to the door, moves WITH the door
|
||
* - Red dashed line = rotation axis (vertical, thru center of cylindrical pin)
|
||
*
|
||
* The door + door-side hinge parts rotate together around the
|
||
* hinge pin axis. We create a pivot group at that axis and
|
||
* re-parent the moving nodes into it.
|
||
*/
|
||
function setupHingePivot() {
|
||
// 1. Collect nodes to find the pivot axis position and separation logic
|
||
const hingeAssemblies = [];
|
||
const doorNodes = [];
|
||
let ejeRotacionNode = null;
|
||
let leftPanelNode = null;
|
||
|
||
model.traverse((child) => {
|
||
if (!child.name) return;
|
||
|
||
// Hinge assemblies
|
||
if (child.name.includes('BISAGRA')) {
|
||
// Only push the top-level assembly groups
|
||
if (child.parent && !child.parent.name.includes('BISAGRA')) {
|
||
hingeAssemblies.push(child);
|
||
}
|
||
}
|
||
// Door assembly (top level)
|
||
if (child.name === 'V251_PPP_PUERTA1') {
|
||
doorNodes.push(child);
|
||
}
|
||
// Check for explicit rotation axis part
|
||
if (child.name.toLowerCase().includes('eje') && child.name.toLowerCase().includes('rotaci')) {
|
||
ejeRotacionNode = child;
|
||
} else if (child.name.includes('Eje') && child.name.includes('rotaci')) {
|
||
ejeRotacionNode = child;
|
||
}
|
||
// Match left panel for proximity testing
|
||
if (child.name.toUpperCase().includes('PANEL IZQUIERDO')) {
|
||
leftPanelNode = child;
|
||
}
|
||
});
|
||
|
||
if (hingeAssemblies.length === 0 && doorNodes.length === 0 && !ejeRotacionNode) {
|
||
console.warn('⚠️ Could not find door/hinge nodes by name. Listing all node names:');
|
||
model.traverse((c) => { if (c.name) console.log(' Node:', c.name, '| Type:', c.type); });
|
||
return;
|
||
}
|
||
|
||
console.log(`🔧 Found ${hingeAssemblies.length} hinge assemblies, ${doorNodes.length} door nodes, Left Panel: ${!!leftPanelNode}`);
|
||
|
||
// 1.5 Extract only the moving hinge parts
|
||
const hingeNodes = [];
|
||
let leftPanelBox = new THREE.Box3();
|
||
let doorBox = new THREE.Box3();
|
||
|
||
if (leftPanelNode) leftPanelBox.setFromObject(leftPanelNode);
|
||
if (doorNodes.length > 0) doorBox.setFromObject(doorNodes[0]);
|
||
|
||
hingeAssemblies.forEach(assembly => {
|
||
const allMeshes = [];
|
||
assembly.traverse((child) => {
|
||
if (child.isMesh) {
|
||
allMeshes.push(child);
|
||
}
|
||
});
|
||
|
||
if (allMeshes.length > 0) {
|
||
const centers = new Map();
|
||
let minX = Infinity;
|
||
let maxX = -Infinity;
|
||
|
||
allMeshes.forEach(mesh => {
|
||
const box = new THREE.Box3().setFromObject(mesh);
|
||
const center = new THREE.Vector3();
|
||
box.getCenter(center);
|
||
centers.set(mesh, center);
|
||
if (center.x < minX) minX = center.x;
|
||
if (center.x > maxX) maxX = center.x;
|
||
});
|
||
|
||
// Define the separation line between left (fixed) and right (moving)
|
||
// If minX and maxX are very close, ensure some difference
|
||
const thresholdX = (minX + Math.max(minX + 0.001, maxX)) / 2;
|
||
|
||
let movingCount = 0;
|
||
let fixedCount = 0;
|
||
|
||
allMeshes.forEach(mesh => {
|
||
const center = centers.get(mesh);
|
||
if (center.x > thresholdX) {
|
||
// Right side -> Moving
|
||
hingeNodes.push(mesh);
|
||
movingCount++;
|
||
} else {
|
||
// Left side -> Fixed
|
||
// Make it appear lighter by adding subtle emissive
|
||
const newMat = new THREE.MeshStandardMaterial({
|
||
color: 0x555555, // Base grey
|
||
emissive: 0x333333, // Subtle glow to look "lighter"
|
||
metalness: 0.6,
|
||
roughness: 0.4
|
||
});
|
||
mesh.material = newMat;
|
||
fixedCount++;
|
||
}
|
||
});
|
||
|
||
console.log(` - Assembly split: ${fixedCount} fixed, ${movingCount} moving`);
|
||
} else {
|
||
console.warn('⚠️ Hinge assembly has no meshes:', assembly.name);
|
||
hingeNodes.push(assembly);
|
||
}
|
||
});
|
||
|
||
// 2. Compute the hinge pivot position in world space
|
||
// The pivot is at the center of the "Eje rotación" part, or average X/Z of hinge assemblies.
|
||
let pivotWorldPos = new THREE.Vector3();
|
||
|
||
if (ejeRotacionNode) {
|
||
console.log(`🎯 Using explicit axis part '${ejeRotacionNode.name}'`);
|
||
const box = new THREE.Box3().setFromObject(ejeRotacionNode);
|
||
box.getCenter(pivotWorldPos);
|
||
// Hide the axis part from view
|
||
ejeRotacionNode.visible = false;
|
||
} else if (hingeNodes.length > 0) {
|
||
// Use the world position of hinge nodes to find the axis
|
||
hingeNodes.forEach(h => {
|
||
const worldPos = new THREE.Vector3();
|
||
h.getWorldPosition(worldPos);
|
||
pivotWorldPos.add(worldPos);
|
||
});
|
||
pivotWorldPos.divideScalar(hingeNodes.length);
|
||
} else {
|
||
// Fallback: use the door's left edge
|
||
const doorNode = doorNodes[0];
|
||
const box = new THREE.Box3().setFromObject(doorNode);
|
||
pivotWorldPos.set(box.min.x, (box.min.y + box.max.y) / 2, box.min.z);
|
||
}
|
||
|
||
// We only care about X and Z for the pivot — Y is the rotation axis
|
||
// Set Y to 0 (the pivot group's Y doesn't matter since we rotate around Y)
|
||
pivotWorldPos.y = 0;
|
||
|
||
console.log('📍 Hinge pivot world position:', pivotWorldPos);
|
||
|
||
// 3. Create pivot group in the model's parent coordinate space
|
||
hingePivot = new THREE.Group();
|
||
hingePivot.name = 'HingePivot';
|
||
|
||
// Position the pivot in the model's local space
|
||
// Since model has been offset by centerOffset, we need to account for that
|
||
const pivotLocalPos = pivotWorldPos.clone();
|
||
// The model's world transform is just the position offset we applied
|
||
// So local pos relative to model = worldPos (since model is at scene root level)
|
||
hingePivot.position.copy(pivotLocalPos);
|
||
model.add(hingePivot);
|
||
|
||
// 4. Re-parent door and hinge nodes into the pivot group
|
||
// We must adjust their position so their world position stays the same
|
||
const nodesToReparent = [...doorNodes, ...hingeNodes];
|
||
|
||
nodesToReparent.forEach(node => {
|
||
// Get the node's current world position and quaternion
|
||
const worldPos = new THREE.Vector3();
|
||
const worldQuat = new THREE.Quaternion();
|
||
const worldScale = new THREE.Vector3();
|
||
node.getWorldPosition(worldPos);
|
||
node.getWorldQuaternion(worldQuat);
|
||
node.getWorldScale(worldScale);
|
||
|
||
// Remove from current parent
|
||
const oldParent = node.parent;
|
||
if (oldParent) oldParent.remove(node);
|
||
|
||
// Add to pivot group
|
||
hingePivot.add(node);
|
||
|
||
// Compute new local position relative to pivot
|
||
// newLocalPos = inversePivotWorldMatrix * worldPos
|
||
const pivotWorldMatrix = new THREE.Matrix4();
|
||
hingePivot.updateWorldMatrix(true, false);
|
||
pivotWorldMatrix.copy(hingePivot.matrixWorld).invert();
|
||
|
||
const newWorldMatrix = new THREE.Matrix4().compose(worldPos, worldQuat, worldScale);
|
||
const newLocalMatrix = pivotWorldMatrix.multiply(newWorldMatrix);
|
||
|
||
// Decompose back into position/quaternion/scale
|
||
const newPos = new THREE.Vector3();
|
||
const newQuat = new THREE.Quaternion();
|
||
const newScale = new THREE.Vector3();
|
||
newLocalMatrix.decompose(newPos, newQuat, newScale);
|
||
|
||
node.position.copy(newPos);
|
||
node.quaternion.copy(newQuat);
|
||
node.scale.copy(newScale);
|
||
|
||
console.log(` ↳ Re-parented "${node.name}" into pivot group`);
|
||
});
|
||
|
||
console.log('✅ Hinge pivot setup complete!');
|
||
}
|
||
|
||
// Load the model
|
||
loader.load(
|
||
'Cabinet v2.5 con eje.glb',
|
||
(gltf) => {
|
||
model = gltf.scene;
|
||
|
||
// Center using bounding box
|
||
const box = new THREE.Box3().setFromObject(model);
|
||
centerOffset = box.getCenter(new THREE.Vector3());
|
||
model.position.sub(centerOffset);
|
||
|
||
setupShadows(model);
|
||
setupGlassMaterials(model);
|
||
setupLEDBarLighting(model);
|
||
scene.add(model);
|
||
|
||
// Set up hinge pivot after model is in the scene
|
||
setupHingePivot();
|
||
|
||
// Hide loader
|
||
document.getElementById('progress').style.width = '100%';
|
||
document.getElementById('loader').style.opacity = '0';
|
||
setTimeout(() => document.getElementById('loader').style.display = 'none', 500);
|
||
|
||
console.log('✅ Model loaded and hinge pivot configured');
|
||
console.log('Model World Position:', model.position);
|
||
const bBox = new THREE.Box3().setFromObject(model);
|
||
console.log('Model Bounding Box Size:', bBox.getSize(new THREE.Vector3()));
|
||
console.log('Model Bounding Box Center:', bBox.getCenter(new THREE.Vector3()));
|
||
},
|
||
(progress) => {
|
||
if (progress.total > 0) {
|
||
const percent = (progress.loaded / progress.total) * 100;
|
||
document.getElementById('progress').style.width = percent + '%';
|
||
}
|
||
},
|
||
(error) => console.error('Error loading model:', error)
|
||
);
|
||
|
||
// --- Interaction ---
|
||
const raycaster = new THREE.Raycaster();
|
||
const mouse = new THREE.Vector2();
|
||
|
||
window.addEventListener('click', (event) => {
|
||
if (event.target.closest('#sidebar') || event.target.closest('#dev-sidebar')) return;
|
||
|
||
const rect = canvas.getBoundingClientRect();
|
||
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
|
||
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
|
||
|
||
raycaster.setFromCamera(mouse, camera);
|
||
const intersects = raycaster.intersectObjects(scene.children, true);
|
||
|
||
if (intersects.length > 0) {
|
||
const object = intersects[0].object;
|
||
|
||
console.log('Clicked:', object.name);
|
||
const normName = object.name.toUpperCase();
|
||
|
||
// Check if clicking door or hinge area (traverse ancestors including pivot)
|
||
let isDoorClick = false;
|
||
object.traverseAncestors((ancestor) => {
|
||
if (ancestor.name && (
|
||
ancestor.name.includes('PUERTA') ||
|
||
ancestor.name.includes('BISAGRA') ||
|
||
ancestor.name === 'HingePivot'
|
||
)) {
|
||
isDoorClick = true;
|
||
}
|
||
});
|
||
|
||
if (object.name.includes('PUERTA') || object.name.includes('BISAGRA') || isDoorClick) {
|
||
toggleDoor();
|
||
} else if (normName.includes('CILINDRO') || normName.includes('CERRADURA') || normName.includes('SOLID1_102')) {
|
||
if (!isDoorOpen) toggleDoor();
|
||
showInfo("Abrir con llave", "Ante cortes de energía, la maquina permanece cerrada");
|
||
} else if (object.name.includes('LECTOR') || object.name.includes('BIOMETRICO')) {
|
||
showInfo("Face Recognition Security", "Our AI-powered volumetric face recognition identifies users in under 0.5 seconds, ensuring hands-free, high-security access.");
|
||
} else {
|
||
showInfo("Interactive Display & Navigation", "Navigate through stored inventory, track usage logs, and manage permissions directly from this integrated touchscreen.");
|
||
}
|
||
} else {
|
||
hideInfo();
|
||
}
|
||
});
|
||
|
||
// Add hover effect
|
||
window.addEventListener('mousemove', (event) => {
|
||
const rect = canvas.getBoundingClientRect();
|
||
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
|
||
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
|
||
|
||
raycaster.setFromCamera(mouse, camera);
|
||
const intersects = raycaster.intersectObjects(scene.children, true);
|
||
|
||
if (intersects.length > 0) {
|
||
const name = intersects[0].object.name.toLowerCase();
|
||
if (name.includes('puerta') || name.includes('bisagra') || name.includes('lector') || name.includes('solid') || name.includes('cilindro') || name.includes('cerradura') || name.includes('solid1_102')) {
|
||
canvas.style.cursor = 'pointer';
|
||
return;
|
||
}
|
||
}
|
||
canvas.style.cursor = 'default';
|
||
});
|
||
|
||
function showInfo(title, text) {
|
||
const panel = document.querySelector('.info-panel');
|
||
panel.innerHTML = `<strong>${title}</strong><br>${text}`;
|
||
panel.style.background = 'rgba(0, 122, 255, 0.9)';
|
||
}
|
||
|
||
function hideInfo() {
|
||
const panel = document.querySelector('.info-panel');
|
||
panel.innerHTML = '🖱️ Click components to explore | Right-click to pan | Scroll to zoom';
|
||
panel.style.background = 'rgba(0, 0, 0, 0.7)';
|
||
}
|
||
|
||
function toggleDoor() {
|
||
if (!hingePivot) return;
|
||
isDoorOpen = !isDoorOpen;
|
||
|
||
// Rotate the entire pivot group around Y-axis
|
||
// This swings the door + hinge parts around the hinge pin
|
||
const targetAngle = isDoorOpen ? DOOR_OPEN_ANGLE : 0;
|
||
|
||
gsap.to(hingePivot.rotation, {
|
||
y: targetAngle,
|
||
duration: 1.2,
|
||
ease: "power2.inOut"
|
||
});
|
||
|
||
console.log('🚪 Door animating to:', isDoorOpen ? 'OPEN (−120°)' : 'CLOSED (0°)');
|
||
}
|
||
|
||
// --- UI Logic ---
|
||
const sidebar = document.getElementById('sidebar');
|
||
const sidebarHeader = document.getElementById('sidebar-header');
|
||
|
||
sidebarHeader.addEventListener('click', () => {
|
||
sidebar.classList.toggle('collapsed');
|
||
const icon = document.getElementById('sidebar-toggle-icon');
|
||
icon.textContent = sidebar.classList.contains('collapsed') ? '📦' : '✕';
|
||
});
|
||
|
||
// --- Simulator Logic ---
|
||
let simBoxes = [];
|
||
// Approximate interior dimensions (to be refined after model analysis)
|
||
const INTERIOR_SIZE = { x: 0.8, y: 1.6, z: 0.5 }; // meters
|
||
const INTERIOR_OFFSET = { x: 0, y: 0.5, z: 0 };
|
||
|
||
document.getElementById('btn-simulate').addEventListener('click', runSimulation);
|
||
|
||
function runSimulation() {
|
||
// 1. Clear previous simulation
|
||
simBoxes.forEach(box => scene.remove(box));
|
||
simBoxes = [];
|
||
|
||
// 2. Get inputs (convert cm to m)
|
||
const pw = parseFloat(document.getElementById('prod-w').value) / 100;
|
||
const ph = parseFloat(document.getElementById('prod-h').value) / 100;
|
||
const pd = parseFloat(document.getElementById('prod-d').value) / 100;
|
||
|
||
if (isNaN(pw) || isNaN(ph) || isNaN(pd) || pw <= 0 || ph <= 0 || pd <= 0) return;
|
||
|
||
// 3. Simple Packing (Grid based)
|
||
const gap = 0.005; // 5mm gap between items
|
||
|
||
const nx = Math.floor(INTERIOR_SIZE.x / (pw + gap));
|
||
const ny = Math.floor(INTERIOR_SIZE.y / (ph + gap));
|
||
const nz = Math.floor(INTERIOR_SIZE.z / (pd + gap));
|
||
|
||
const totalCapacity = nx * ny * nz;
|
||
|
||
// 4. Update UI
|
||
document.getElementById('result-panel').style.display = 'block';
|
||
document.getElementById('result-count').innerText = totalCapacity;
|
||
|
||
// 5. Spawn Preview (Limited to max 500 visual boxes)
|
||
const visualLimit = Math.min(totalCapacity, 500);
|
||
|
||
const boxGeo = new THREE.BoxGeometry(pw, ph, pd);
|
||
const boxMat = new THREE.MeshPhongMaterial({
|
||
color: 0x007aff,
|
||
transparent: true,
|
||
opacity: 0.7,
|
||
shininess: 50
|
||
});
|
||
|
||
let spawned = 0;
|
||
for (let z = 0; z < nz; z++) {
|
||
for (let y = 0; y < ny; y++) {
|
||
for (let x = 0; x < nx; x++) {
|
||
if (spawned >= visualLimit) break;
|
||
|
||
const mesh = new THREE.Mesh(boxGeo, boxMat);
|
||
|
||
mesh.position.x = (x * (pw + gap)) - (INTERIOR_SIZE.x / 2) + (pw / 2);
|
||
mesh.position.y = (y * (ph + gap)) - (INTERIOR_SIZE.y / 2) + (ph / 2) + INTERIOR_OFFSET.y;
|
||
mesh.position.z = (z * (pd + gap)) - (INTERIOR_SIZE.z / 2) + (pd / 2);
|
||
|
||
scene.add(mesh);
|
||
simBoxes.push(mesh);
|
||
spawned++;
|
||
}
|
||
if (spawned >= visualLimit) break;
|
||
}
|
||
if (spawned >= visualLimit) break;
|
||
}
|
||
|
||
// Animate boxes appearing
|
||
if (simBoxes.length > 0) {
|
||
gsap.from(simBoxes.map(b => b.scale), {
|
||
x: 0, y: 0, z: 0,
|
||
duration: 0.5,
|
||
stagger: 0.01,
|
||
ease: "back.out(1.7)"
|
||
});
|
||
}
|
||
|
||
// If door is closed, open it to show the interior
|
||
if (!isDoorOpen) toggleDoor();
|
||
}
|
||
|
||
// --- Render Loop ---
|
||
function animate() {
|
||
requestAnimationFrame(animate);
|
||
controls.update();
|
||
renderer.render(scene, camera);
|
||
}
|
||
|
||
animate();
|
||
|
||
// --- Resize ---
|
||
window.addEventListener('resize', () => {
|
||
camera.aspect = window.innerWidth / window.innerHeight;
|
||
camera.updateProjectionMatrix();
|
||
renderer.setSize(window.innerWidth, window.innerHeight);
|
||
});
|
||
|
||
</script>
|
||
</body>
|
||
|
||
</html> |