-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
824 lines (661 loc) · 30.5 KB
/
script.js
File metadata and controls
824 lines (661 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// Global variables
let scene, camera, renderer, controls;
let loadingElement;
let isAnimating = false;
let needsRender = true;
let instancedMeshes = [];
// Initialize the 3D scene
function init() {
console.log('Initializing advanced instanced rendering...');
loadingElement = document.getElementById('loading');
scene = new THREE.Scene();
scene.background = new THREE.Color(0x222222);
// Get model panel dimensions for proper sizing
const modelPanel = document.getElementById('model-panel');
const rect = modelPanel.getBoundingClientRect();
const panelWidth = rect.width || window.innerWidth / 3;
const panelHeight = rect.height || window.innerHeight;
// Orthographic camera sized to model panel
const frustumSize = 20;
const aspect = panelWidth / panelHeight;
camera = new THREE.OrthographicCamera(
frustumSize * aspect / -2,
frustumSize * aspect / 2,
frustumSize / 2,
frustumSize / -2,
0.1,
1000
);
camera.position.set(5, 5, 5);
camera.lookAt(0, 0, 0);
// Optimized renderer sized to model panel
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById('canvas'),
antialias: false,
alpha: false,
powerPreference: "high-performance",
stencil: false
});
renderer.setSize(panelWidth, panelHeight);
console.log(`Initialized canvas at model panel size: ${panelWidth}x${panelHeight}`);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1));
renderer.shadowMap.enabled = false;
renderer.sortObjects = false;
renderer.autoClear = false;
// Enable GPU instancing extensions
const gl = renderer.getContext();
console.log('GPU Instancing support:', gl.getExtension('ANGLE_instanced_arrays') ? 'YES' : 'NO');
console.log('WebGL2 support:', gl instanceof WebGL2RenderingContext ? 'YES' : 'NO');
// Event-driven controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = false;
controls.addEventListener('start', () => {
isAnimating = true;
needsRender = true;
});
controls.addEventListener('end', () => {
isAnimating = false;
setTimeout(() => {
needsRender = true;
render();
}, 100);
});
controls.addEventListener('change', () => {
needsRender = true;
});
// Minimal lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 1.0);
scene.add(ambientLight);
loadModel();
window.addEventListener('resize', onWindowResize);
console.log('Advanced instancing system initialized');
}
function loadModel() {
console.log('Loading all models for advanced instancing...');
const loader = new GLTFLoader();
// Set up DRACO loader for compressed models
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/');
loader.setDRACOLoader(dracoLoader);
let modelsLoaded = 0;
// Use local models directory - no CORS issues
const modelsBasePath = new URL('./models/', import.meta.url);
const modelsToLoad = [
{ name: 'Architectural System', file: new URL('arch_module_smallest.glb', modelsBasePath).href, isInstanced: true },
{ name: 'Misc Geometry', file: new URL('misc geometry.glb', modelsBasePath).href, isInstanced: false },
{ name: 'Altars', file: new URL('altars.glb', modelsBasePath).href, isInstanced: false },
{ name: 'Circulation', file: new URL('circulation.glb', modelsBasePath).href, isInstanced: false },
{ name: 'Distress', file: new URL('Distress.glb', modelsBasePath).href, isInstanced: false },
{ name: 'Embellishments', file: new URL('embellishments.glb', modelsBasePath).href, isInstanced: false },
{ name: 'Index', file: new URL('Index.glb', modelsBasePath).href, isInstanced: false },
{ name: 'Mirror', file: new URL('mirror.glb', modelsBasePath).href, isInstanced: false },
{ name: 'Moulage', file: new URL('Moulage.glb', modelsBasePath).href, isInstanced: false },
{ name: 'Robot', file: new URL('robot.glb', modelsBasePath).href, isInstanced: false }
];
const totalModels = modelsToLoad.length;
console.log(`Loading ${totalModels} models from local directory (directory cleanup complete)...`);
// Load each model directly
modelsToLoad.forEach((modelInfo, index) => {
loader.load(
modelInfo.file,
function(gltf) {
console.log(`${modelInfo.name} loaded from clean directory structure!`);
if (modelInfo.isInstanced) {
// Handle the main architectural instanced system
const model = gltf.scene;
const box = new THREE.Box3().setFromObject(model);
const size = box.getSize(new THREE.Vector3());
console.log('Architectural model size:', size.x.toFixed(2), '×', size.y.toFixed(2), '×', size.z.toFixed(2));
createAdvancedInstancedSystem(model, size);
console.log('Advanced instanced system complete!');
} else {
// Handle regular models with shared coordinate system
const loadedModel = gltf.scene;
// Apply consistent shading system to all meshes
loadedModel.traverse(function(child) {
if (child.isMesh) {
console.log(`Processing ${modelInfo.name} mesh:`, child.name || 'unnamed');
// Apply baked lighting to geometry
if (child.geometry) {
generateBakedLighting(child.geometry);
}
// Create optimized material matching the instanced system
const optimizedMaterial = new THREE.MeshBasicMaterial({
transparent: false,
alphaTest: 0,
side: THREE.FrontSide,
vertexColors: true,
fog: false
});
// Copy texture if the original material has one
if (child.material && child.material.map) {
const texture = child.material.map.clone();
texture.generateMipmaps = false;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
optimizedMaterial.map = texture;
}
// Apply the optimized material
child.material = optimizedMaterial;
// Apply GPU optimizations
child.castShadow = false;
child.receiveShadow = false;
child.matrixAutoUpdate = false;
}
});
// Position using shared coordinate system with small X-axis offset
// Architectural tower stays at origin, other models shifted -0.3 units on X-axis
loadedModel.position.set(-0.3, 0, 0);
// Add to scene
scene.add(loadedModel);
console.log(`${modelInfo.name} placed in scene with matching shading`);
}
modelsLoaded++;
checkAllModelsLoaded();
},
function(progress) {
const percent = Math.round((progress.loaded / progress.total * 100));
console.log(`Loading ${modelInfo.name} progress: ${percent}%`);
},
function(error) {
console.error(`Error loading ${modelInfo.name}:`, error);
showError(`Failed to load ${modelInfo.name}: ` + error.message);
}
);
});
function checkAllModelsLoaded() {
if (modelsLoaded === totalModels) {
hideLoading();
needsRender = true;
console.log(`All ${totalModels} models loaded successfully - directory cleanup complete!`);
// Dispose of DRACO loader resources
dracoLoader.dispose();
}
}
}
function createAdvancedInstancedSystem(model, size) {
console.log('Creating advanced instanced system with GPU optimizations...');
// Collect all unique geometries and materials
const geometryMaterialPairs = [];
model.traverse(function(child) {
if (child.isMesh) {
geometryMaterialPairs.push({
geometry: child.geometry,
material: child.material
});
}
});
console.log(`Found ${geometryMaterialPairs.length} geometry-material pairs`);
// Create instanced meshes for each unique geometry
geometryMaterialPairs.forEach((pair, index) => {
const { geometry, material } = pair;
// Create optimized material
const optimizedMaterial = createOptimizedMaterial(material);
// Create instanced mesh with advanced optimizations
const instancedMesh = createAdvancedInstancedMesh(geometry, optimizedMaterial);
// Set up transformation matrices using efficient method
setupInstanceMatrices(instancedMesh, size);
// Apply GPU-level optimizations
applyGPUOptimizations(instancedMesh);
scene.add(instancedMesh);
instancedMeshes.push(instancedMesh);
console.log(`Created advanced instanced mesh ${index + 1} with ${instancedMesh.count} instances`);
});
}
function createOptimizedMaterial(originalMaterial) {
// Create efficient material with baked lighting simulation
const optimizedMaterial = new THREE.MeshBasicMaterial({
transparent: false,
alphaTest: 0,
side: THREE.FrontSide,
vertexColors: true, // Enable vertex colors for baked lighting
fog: false
});
// Copy and optimize texture if exists
if (originalMaterial.map) {
const texture = originalMaterial.map.clone();
texture.generateMipmaps = false;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
optimizedMaterial.map = texture;
}
return optimizedMaterial;
}
function createAdvancedInstancedMesh(geometry, material) {
// Optimize geometry first
const optimizedGeometry = optimizeGeometry(geometry);
// Calculate total instances for all 5 floors
const floor1Count = 33 * 33; // 1,089 instances (solid base)
const borderCount = calculateBorderInstances(); // 396 instances per border floor
const borderFloors = 4; // Floors 2, 3, 4, 5
const totalCount = floor1Count + (borderCount * borderFloors); // 1,089 + (396 × 4) = 2,673 total
console.log(`Creating 5-floor tower with ${totalCount} total instances:`);
console.log(`- Floor 1 (solid): ${floor1Count} instances`);
console.log(`- Floors 2-5 (borders): ${borderCount} × ${borderFloors} = ${borderCount * borderFloors} instances`);
// Create instanced mesh with total count for all floors
const instancedMesh = new THREE.InstancedMesh(optimizedGeometry, material, totalCount);
return instancedMesh;
}
function optimizeGeometry(geometry) {
// Clone and optimize geometry
const optimizedGeometry = geometry.clone();
// Remove unnecessary attributes but keep what we need for shading
const attributesToKeep = ['position', 'normal', 'uv'];
Object.keys(optimizedGeometry.attributes).forEach(name => {
if (!attributesToKeep.includes(name)) {
optimizedGeometry.deleteAttribute(name);
}
});
// Generate efficient baked lighting via vertex colors
generateBakedLighting(optimizedGeometry);
// Compute optimized bounding sphere
optimizedGeometry.computeBoundingSphere();
// Dispose of morph attributes if present
if (optimizedGeometry.morphAttributes) {
optimizedGeometry.morphAttributes = {};
}
console.log(`Optimized geometry with baked lighting: ${optimizedGeometry.attributes.position.count} vertices`);
return optimizedGeometry;
}
function generateBakedLighting(geometry) {
// Create baked lighting using vertex colors (super efficient)
const positions = geometry.attributes.position;
const normals = geometry.attributes.normal;
const vertexCount = positions.count;
// Pre-calculate lighting directions (simulating typical architectural lighting)
const lightDir1 = new THREE.Vector3(0.5, 0.8, 0.3).normalize(); // Main light from above-front
const lightDir2 = new THREE.Vector3(-0.3, 0.2, -0.8).normalize(); // Fill light
const ambientLevel = 0.3; // Ambient lighting level
// Create color array for vertex colors
const colors = new Float32Array(vertexCount * 3);
const normal = new THREE.Vector3();
for (let i = 0; i < vertexCount; i++) {
// Get vertex normal
normal.fromBufferAttribute(normals, i);
// Calculate lighting using simple but effective Lambert shading
const lightContrib1 = Math.max(0, normal.dot(lightDir1)) * 0.7;
const lightContrib2 = Math.max(0, normal.dot(lightDir2)) * 0.3;
const totalLight = Math.min(1.0, ambientLevel + lightContrib1 + lightContrib2);
// Apply slight variation for visual interest
const variation = 0.95 + Math.random() * 0.1;
const finalIntensity = totalLight * variation;
// Set RGB color (slight warm tint for architectural feel)
colors[i * 3] = finalIntensity * 0.95; // R - slightly less red
colors[i * 3 + 1] = finalIntensity * 0.97; // G - neutral
colors[i * 3 + 2] = finalIntensity * 1.0; // B - slightly more blue
}
// Add color attribute to geometry
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
console.log('Generated baked lighting with vertex colors');
}
function setupInstanceMatrices(instancedMesh, size) {
// Pre-allocate matrix for reuse (memory optimization)
const matrix = new THREE.Matrix4();
const position = new THREE.Vector3();
const quaternion = new THREE.Quaternion();
const scale = new THREE.Vector3(1, 1, 1);
let instanceIndex = 0;
// Calculate center offset to position world origin at center of first floor
const gridSize = 33;
const centerOffset = (gridSize - 1) * 0.5; // Offset to center the grid
// Calculate total instances needed for all 5 floors
const floor1Instances = 33 * 33; // Full grid: 1,089 instances
const borderInstances = calculateBorderInstances(); // Border only: 396 instances per floor
const totalBorderFloors = 4; // Floors 2, 3, 4, 5
const totalInstances = floor1Instances + (borderInstances * totalBorderFloors);
console.log(`Setting up ${totalInstances} instances across 5 floors:`);
console.log(`- Floor 1 (solid): ${floor1Instances} instances`);
console.log(`- Floors 2-5 (borders): ${borderInstances} instances each (${borderInstances * totalBorderFloors} total)`);
console.log(`- Grid centered at origin with offset: ${centerOffset.toFixed(2)}`);
// Floor 1: Full 33x33 grid at ground level (y = 0) - CENTERED
for (let x = 0; x < 33; x++) {
for (let z = 0; z < 33; z++) {
// Center the grid so origin is at the center of the footprint
position.set(
(x - centerOffset) * size.x,
0,
(z - centerOffset) * size.z
);
matrix.compose(position, quaternion, scale);
instancedMesh.setMatrixAt(instanceIndex, matrix);
instanceIndex++;
}
}
// Floors 2-5: Hollow borders at elevated levels - CENTERED
for (let floor = 2; floor <= 5; floor++) {
const floorY = size.y * (floor - 1); // Direct stacking - each floor sits on top of the previous
for (let x = 0; x < 33; x++) {
for (let z = 0; z < 33; z++) {
// Only place instances in the 3-cell thick border
if (isBorderCell(x, z)) {
// Center the grid so origin is at the center of the footprint
position.set(
(x - centerOffset) * size.x,
floorY,
(z - centerOffset) * size.z
);
matrix.compose(position, quaternion, scale);
instancedMesh.setMatrixAt(instanceIndex, matrix);
instanceIndex++;
}
}
}
console.log(`Floor ${floor} completed at height ${floorY.toFixed(2)} with ${borderInstances} border instances`);
}
console.log(`Placed ${instanceIndex} total instances across 5-floor tower (centered at origin)`);
// Mark for GPU upload
instancedMesh.instanceMatrix.needsUpdate = true;
// Set usage hint for GPU optimization
instancedMesh.instanceMatrix.setUsage(THREE.StaticDrawUsage); // Matrices won't change
}
function isBorderCell(x, z) {
// Check if cell is in the 3-thick border
// Border cells are: x < 3 OR x >= 30 OR z < 3 OR z >= 30
return (x < 3 || x >= 30 || z < 3 || z >= 30);
}
function calculateBorderInstances() {
// Calculate total border cells in a 33x33 grid with 3-thick border
let count = 0;
for (let x = 0; x < 33; x++) {
for (let z = 0; z < 33; z++) {
if (isBorderCell(x, z)) {
count++;
}
}
}
return count;
}
function applyGPUOptimizations(instancedMesh) {
// Apply various GPU-level optimizations
// Frustum culling at instance level
instancedMesh.frustumCulled = true;
// Disable shadows for performance
instancedMesh.castShadow = false;
instancedMesh.receiveShadow = false;
// Set render order for optimal batching
instancedMesh.renderOrder = 0;
// Disable automatic matrix updates
instancedMesh.matrixAutoUpdate = false;
// Set static draw usage for GPU buffer optimization
if (instancedMesh.geometry.attributes.position) {
instancedMesh.geometry.attributes.position.setUsage(THREE.StaticDrawUsage);
}
if (instancedMesh.geometry.index) {
instancedMesh.geometry.index.setUsage(THREE.StaticDrawUsage);
}
console.log('Applied GPU optimizations to instanced mesh');
}
function hideLoading() {
if (loadingElement) {
loadingElement.classList.add('hidden');
setTimeout(() => {
loadingElement.style.display = 'none';
}, 500);
}
}
function showError(message) {
if (loadingElement) {
const loadingText = loadingElement.querySelector('p');
if (loadingText) {
loadingText.textContent = message;
loadingText.style.color = '#ff6b6b';
}
}
}
function onWindowResize() {
// Get the model panel dimensions instead of full window
const modelPanel = document.getElementById('model-panel');
const rect = modelPanel.getBoundingClientRect();
const width = rect.width;
const height = rect.height;
const aspect = width / height;
const frustumSize = 20;
camera.left = frustumSize * aspect / -2;
camera.right = frustumSize * aspect / 2;
camera.top = frustumSize / 2;
camera.bottom = frustumSize / -2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
needsRender = true;
console.log(`Resized canvas to model panel: ${width}x${height}`);
}
// Optimized render function
function render() {
if (needsRender) {
renderer.clear();
renderer.render(scene, camera);
needsRender = false;
// Log render info occasionally for debugging
if (Math.random() < 0.01) { // 1% chance
console.log('Render info:', renderer.info.render);
}
}
}
// Minimal render loop
function animate() {
requestAnimationFrame(animate);
if (isAnimating) {
controls.update();
render();
}
}
// Cleanup function for memory management
function cleanup() {
instancedMeshes.forEach(mesh => {
mesh.geometry.dispose();
mesh.material.dispose();
if (mesh.material.map) {
mesh.material.map.dispose();
}
});
renderer.dispose();
}
// Handle page unload
window.addEventListener('beforeunload', cleanup);
// Start the application
document.addEventListener('DOMContentLoaded', function() {
console.log('Starting advanced instanced rendering system...');
console.log('GPU Optimizations: Static draw usage, matrix composition, geometry optimization, material batching');
init();
animate();
// Initialize LiDAR board with responsive hotspots
initResponsiveLiDARBoard();
// Initial render
render();
});
// ===== RESPONSIVE LIDAR BOARD FUNCTIONALITY =====
function initResponsiveLiDARBoard() {
console.log('Initializing responsive LiDAR board with Figma-style hotspots...');
const lidarBoard = document.getElementById('lidar-board');
const hotspots = document.querySelectorAll('.hotspot');
const highlightBtn = document.getElementById('btnHighlight');
const zoomExtentsBtn = document.getElementById('btnZoomExtents');
let isHighlighting = false;
// Figma SVG reference dimensions (1920x1080)
const REFERENCE_WIDTH = 1920;
const REFERENCE_HEIGHT = 1080;
// Highlight toggle functionality
highlightBtn.addEventListener('click', function() {
isHighlighting = !isHighlighting;
if (isHighlighting) {
lidarBoard.classList.add('highlighting');
highlightBtn.classList.add('active');
// Create CSS mask with holes for hotspots
createMaskWithHoles();
console.log('Highlighting enabled - CSS mask with tight feathered edges');
console.log('Feather radius: 3px for sharp transition');
} else {
lidarBoard.classList.remove('highlighting');
highlightBtn.classList.remove('active');
// Remove CSS mask
removeMask();
console.log('Highlighting disabled - normal bright image restored');
}
});
function createMaskWithHoles() {
const boardRect = lidarBoard.getBoundingClientRect();
const scaleX = boardRect.width / REFERENCE_WIDTH;
const scaleY = boardRect.height / REFERENCE_HEIGHT;
// Build CSS mask using polygon shapes - start with full coverage
let maskPaths = [];
// Create rectangular holes for each hotspot
hotspots.forEach(hotspot => {
const coords = hotspot.dataset.coords.split(',').map(Number);
const [x, y, width, height] = coords;
// Scale coordinates to current container size
const scaledX = (x * scaleX) / boardRect.width * 100; // Convert to percentage
const scaledY = (y * scaleY) / boardRect.height * 100;
const scaledWidth = (width * scaleX) / boardRect.width * 100;
const scaledHeight = (height * scaleY) / boardRect.height * 100;
// Create a rectangular hole (black = hidden in mask)
const holeRect = {
left: scaledX,
top: scaledY,
right: scaledX + scaledWidth,
bottom: scaledY + scaledHeight
};
maskPaths.push(holeRect);
});
// Create an SVG mask with holes
const svgMask = createSVGMask(maskPaths, boardRect.width, boardRect.height);
// Apply the mask to the ::before pseudo-element via CSS custom property
lidarBoard.style.setProperty('--mask-image', `url("data:image/svg+xml,${encodeURIComponent(svgMask)}")`);
// Apply the mask via CSS
const style = document.createElement('style');
style.id = 'lidar-mask-style';
style.textContent = `
#lidar-board.highlighting::before {
mask: var(--mask-image);
-webkit-mask: var(--mask-image);
mask-repeat: no-repeat;
-webkit-mask-repeat: no-repeat;
mask-size: 100% 100%;
-webkit-mask-size: 100% 100%;
}
`;
document.head.appendChild(style);
}
function createSVGMask(holeRects, width, height) {
// Create SVG mask - WHITE shows content, BLACK hides it
let svg = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">`;
svg += `<defs>`;
// Add blur filter for feathered edges
svg += `<filter id="featherBlur">`;
svg += `<feGaussianBlur in="SourceGraphic" stdDeviation="3"/>`;
svg += `</filter>`;
svg += `<mask id="cutoutMask">`;
// White background (visible area - the overlay)
svg += `<rect width="100%" height="100%" fill="white"/>`;
// Black rectangles with feathered edges (hidden areas - holes)
holeRects.forEach(hole => {
const x = (hole.left / 100) * width;
const y = (hole.top / 100) * height;
const w = ((hole.right - hole.left) / 100) * width;
const h = ((hole.bottom - hole.top) / 100) * height;
svg += `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="black" filter="url(#featherBlur)"/>`;
});
svg += `</mask></defs>`;
svg += `<rect width="100%" height="100%" fill="white" mask="url(#cutoutMask)"/>`;
svg += `</svg>`;
return svg;
}
function removeMask() {
// Remove the CSS mask
lidarBoard.style.removeProperty('--mask-image');
// Remove the dynamic style
const maskStyle = document.getElementById('lidar-mask-style');
if (maskStyle) {
maskStyle.remove();
}
}
// Zoom extents functionality (placeholder)
zoomExtentsBtn.addEventListener('click', function() {
console.log('Zoom Extents clicked - reset camera view');
// Future: Reset 3D camera to show full model
syncWith3DModel('zoom-extents');
});
// Position hotspots responsively
function positionHotspots() {
const boardRect = lidarBoard.getBoundingClientRect();
const scaleX = boardRect.width / REFERENCE_WIDTH;
const scaleY = boardRect.height / REFERENCE_HEIGHT;
hotspots.forEach(hotspot => {
const coords = hotspot.dataset.coords.split(',').map(Number);
const rotation = parseFloat(hotspot.dataset.rotation || 0);
const [x, y, width, height] = coords;
// Scale coordinates to current container size
const scaledX = x * scaleX;
const scaledY = y * scaleY;
const scaledWidth = width * scaleX;
const scaledHeight = height * scaleY;
// Apply responsive positioning
hotspot.style.left = scaledX + 'px';
hotspot.style.top = scaledY + 'px';
hotspot.style.width = scaledWidth + 'px';
hotspot.style.height = scaledHeight + 'px';
hotspot.style.transform = `rotate(${rotation}deg)`;
});
console.log(`Positioned ${hotspots.length} hotspots for ${boardRect.width.toFixed(0)}x${boardRect.height.toFixed(0)} container`);
}
// Add click handlers for hotspots
hotspots.forEach(hotspot => {
hotspot.addEventListener('click', function(e) {
e.preventDefault();
handleHotspotClick(this);
});
hotspot.addEventListener('mouseenter', function() {
console.log(`Hovering over ${this.dataset.area} area`);
});
});
function handleHotspotClick(hotspot) {
const area = hotspot.dataset.area;
console.log(`Clicked on ${area} hotspot`);
// Remove active state from all hotspots
hotspots.forEach(h => h.classList.remove('active'));
// Add active state to clicked hotspot
hotspot.classList.add('active');
// Log the interaction (you can expand this to sync with 3D model)
console.log(`Selected area: ${area}`);
// Future: Sync with 3D model camera position/highlighting
syncWith3DModel(area);
}
function syncWith3DModel(area) {
// Placeholder for 3D model synchronization
console.log(`Syncing 3D model with area: ${area}`);
// You can add specific camera movements or highlighting here
// For example:
// - Move camera to specific position
// - Highlight certain model parts
// - Change model visibility layers
}
// Handle window resize for responsive hotspots
let resizeTimeout;
function handleResize() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
positionHotspots();
// Recreate mask if highlighting is active
if (isHighlighting) {
createMaskWithHoles();
}
}, 100); // Debounce resize events
}
// Set up resize listener
window.addEventListener('resize', handleResize);
// Initial positioning
// Wait for layout to be ready
setTimeout(positionHotspots, 100);
// Also reposition when images load (if any)
if (document.readyState === 'complete') {
setTimeout(positionHotspots, 200);
} else {
window.addEventListener('load', () => {
setTimeout(positionHotspots, 200);
});
}
console.log('Responsive LiDAR board initialized with mask-style interaction');
}