-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathanything2.html
More file actions
846 lines (716 loc) · 32.8 KB
/
anything2.html
File metadata and controls
846 lines (716 loc) · 32.8 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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>webXOS ANYTHING2</title>
<style>
:root {
--neon: #39ff14;
--bg: #0a0a0a;
--panel: #111;
--accent: #8a2be2;
--warning: #ff6666;
--success: #7fffb1;
}
* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Courier New', monospace; }
html, body { height: 100%; overflow: hidden; }
body { background: var(--bg); color: var(--neon); }
.wrap { display: grid; grid-template-columns: 360px 1fr; height: 100vh; gap: 1px; background: var(--neon); }
.panel { background: var(--panel); display: flex; flex-direction: column; }
.head { padding: 12px; border-bottom: 1px solid var(--neon); display: flex; justify-content: space-between; align-items: center; }
.head h1 { font-size: 1.05rem; text-shadow: 0 0 6px var(--neon); }
.left { padding: 12px; display: flex; flex-direction: column; gap: 10px; overflow: hidden; }
.note { font-size: 0.9rem; color: #bbb; }
.controls { display: flex; flex-direction: column; gap: 8px; }
.btn { padding: 10px; border: 1px solid var(--neon); background: transparent; color: var(--neon); cursor: pointer; border-radius: 6px; text-align: left; }
.btn:hover { background: var(--neon); color: #000; }
.tab-container { display: flex; border-bottom: 1px solid rgba(57,255,20,0.2); margin-bottom: 10px; }
.tab { padding: 8px 12px; cursor: pointer; border-bottom: 2px solid transparent; }
.tab.active { border-bottom: 2px solid var(--neon); }
.tab-content { display: none; flex: 1; overflow: auto; }
.tab-content.active { display: flex; flex-direction: column; }
.terminal { flex: 1; overflow: auto; padding: 8px; border: 1px solid rgba(57,255,20,0.06); background: rgba(0,0,0,0.15); }
.line { margin-bottom: 8px; display: flex; }
.prompt { color: var(--accent); margin-right: 8px; }
.right { position: relative; display: flex; flex-direction: column; }
#threeContainer { width: 100%; height: 100%; display: block; background: #050505; }
.editor { position: absolute; top: 16px; right: 16px; background: rgba(6,6,6,0.92); padding: 12px; border: 1px solid var(--neon); border-radius: 6px; width: 340px; max-height: 80vh; overflow: auto; }
.drop { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; border: 2px dashed rgba(57,255,20,0.06); pointer-events: none; opacity: 0; transition: opacity .18s; }
.drop.active { pointer-events: all; opacity: 1; background: rgba(57,255,20,0.02); }
.small { font-size: 0.85rem; color: #bbb; }
.status-bar { display: flex; justify-content: space-between; padding: 6px 0; border-top: 1px solid rgba(57,255,20,0.1); margin-top: 8px; }
.color-picker { display: flex; gap: 8px; margin-top: 8px; }
.color-option { width: 24px; height: 24px; border-radius: 50%; cursor: pointer; border: 1px solid rgba(255,255,255,0.3); }
.color-option.active { border: 2px solid white; }
.point-info { margin-top: 8px; padding: 8px; background: rgba(57,255,20,0.05); border-radius: 4px; }
@media (max-width: 900px) {
.wrap { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
.editor { width: 92%; right: 4%; top: auto; bottom: 16px; }
}
</style>
</head>
<body>
<div class="wrap">
<div class="panel">
<div class="head">
<h1>ANYTHING2</h1>
<div class="small">Point Cloud | Editor</div>
</div>
<div class="left">
<div class="tab-container">
<div class="tab active" data-tab="point-cloud">Point Cloud</div>
<div class="tab" data-tab="edit">Point Editor</div>
<div class="tab" data-tab="view">View Controls</div>
</div>
<!-- Point Cloud Tab -->
<div class="tab-content active" id="point-cloud-tab">
<div class="note">Upload a JPEG image or MP4 video to generate a 3D point cloud. Drag & drop supported.</div>
<div class="controls">
<button id="uploadImageBtn" class="btn">📁 Upload JPEG Image</button>
<button id="uploadVideoBtn" class="btn">🎞 Upload MP4 Video</button>
<button id="recomputeBtn" class="btn">🔄 Recompute Depth</button>
<button id="resetBtn" class="btn">🔁 Reset Scene</button>
</div>
<div style="display:flex;gap:8px;align-items:center;margin-top:8px">
<div class="small">Export scene:</div>
<button id="exportBtn" class="btn" style="flex:1">Export JSON</button>
</div>
<div class="terminal" id="terminal" aria-live="polite"></div>
</div>
<!-- Point Editor Tab -->
<div class="tab-content" id="edit-tab">
<div class="note">Click on individual points to select and edit them.</div>
<div class="controls">
<div class="small">Selected Point:</div>
<div id="selectedPointInfo" class="point-info">No point selected</div>
<div class="small">Point Color:</div>
<div class="color-picker">
<div class="color-option active" data-color="#39ff14" style="background:#39ff14"></div>
<div class="color-option" data-color="#ff3333" style="background:#ff3333"></div>
<div class="color-option" data-color="#3366ff" style="background:#3366ff"></div>
<div class="color-option" data-color="#ffff33" style="background:#ffff33"></div>
<div class="color-option" data-color="#ff33ff" style="background:#ff33ff"></div>
<div class="color-option" data-color="#33ffff" style="background:#33ffff"></div>
</div>
<button id="applyColorBtn" class="btn">Apply Color to Selected</button>
<button id="applyColorAllBtn" class="btn">Apply Color to All</button>
<button id="deletePointBtn" class="btn">Delete Selected Point</button>
</div>
<div class="terminal" id="editTerminal"></div>
</div>
<!-- View Controls Tab -->
<div class="tab-content" id="view-tab">
<div class="note">Adjust the view and visualization settings.</div>
<div class="controls">
<div style="margin-bottom:8px">
<label class="small">Point size</label><br/>
<input id="pointSize" type="range" min="0.1" max="2" step="0.1" value="0.5" style="width:100%"/>
</div>
<div style="margin-bottom:8px">
<label class="small">Depth scale</label><br/>
<input id="depthScale" type="range" min="1" max="40" step="1" value="12" style="width:100%"/>
</div>
<div style="margin-bottom:8px">
<label class="small">Grid size</label><br/>
<input id="gridSize" type="range" min="5" max="50" step="5" value="20" style="width:100%"/>
</div>
<div style="margin-bottom:8px">
<label class="small">Grid divisions</label><br/>
<input id="gridDivisions" type="range" min="5" max="50" step="5" value="20" style="width:100%"/>
</div>
<div style="margin-bottom:8px">
<label class="small">Auto-rotate</label><input id="autoRotate" type="checkbox" style="margin-left:8px"/>
</div>
</div>
<div class="terminal" id="viewTerminal"></div>
</div>
<div class="status-bar">
<div class="small" id="statusPoints">Points: 0</div>
<div class="small" id="statusFPS">FPS: 0</div>
</div>
</div>
</div>
<div class="panel right">
<div id="threeContainer"></div>
<div class="editor" id="editor">
<div style="font-weight:600;margin-bottom:8px">DA3 Point Cloud Controls</div>
<div style="margin-bottom:8px">
<label class="small">Camera Zoom: <span id="zoomValue">1.0</span></label><br/>
<input id="cameraZoom" type="range" min="0.1" max="5" step="0.1" value="1.0" style="width:100%"/>
</div>
<div style="margin-bottom:8px">
<label class="small">Camera X: <span id="cameraXValue">0</span></label><br/>
<input id="cameraX" type="range" min="-20" max="20" step="1" value="0" style="width:100%"/>
</div>
<div style="margin-bottom:8px">
<label class="small">Camera Y: <span id="cameraYValue">0</span></label><br/>
<input id="cameraY" type="range" min="-20" max="20" step="1" value="0" style="width:100%"/>
</div>
<div style="margin-bottom:8px">
<label class="small">Camera Z: <span id="cameraZValue">15</span></label><br/>
<input id="cameraZ" type="range" min="5" max="50" step="1" value="15" style="width:100%"/>
</div>
<div style="margin-top:6px" class="small">Drag & drop JPEG/MP4 onto the canvas.</div>
<div style="margin-top:10px;"><strong class="small">Scene Objects</strong></div>
<div id="objectList" style="margin-top:6px"></div>
</div>
<div class="drop" id="dropZone"><div class="small">Drop JPEG or MP4 here</div></div>
</div>
</div>
<!-- Three.js Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.min.js"></script>
<script>
(function(){
// Programmatic file inputs
const imageInput = document.createElement('input');
imageInput.type='file';
imageInput.accept='image/jpeg,image/jpg';
imageInput.style.display='none';
document.body.appendChild(imageInput);
const videoInput = document.createElement('input');
videoInput.type='file';
videoInput.accept='video/mp4';
videoInput.style.display='none';
document.body.appendChild(videoInput);
// UI refs
const uploadImageBtn = document.getElementById('uploadImageBtn');
const uploadVideoBtn = document.getElementById('uploadVideoBtn');
const recomputeBtn = document.getElementById('recomputeBtn');
const resetBtn = document.getElementById('resetBtn');
const exportBtn = document.getElementById('exportBtn');
const applyColorBtn = document.getElementById('applyColorBtn');
const applyColorAllBtn = document.getElementById('applyColorAllBtn');
const deletePointBtn = document.getElementById('deletePointBtn');
const terminal = document.getElementById('terminal');
const editTerminal = document.getElementById('editTerminal');
const viewTerminal = document.getElementById('viewTerminal');
const dropZone = document.getElementById('dropZone');
const pointSizeEl = document.getElementById('pointSize');
const depthScaleEl = document.getElementById('depthScale');
const gridSizeEl = document.getElementById('gridSize');
const gridDivisionsEl = document.getElementById('gridDivisions');
const autoRotateEl = document.getElementById('autoRotate');
const objectListEl = document.getElementById('objectList');
const statusPoints = document.getElementById('statusPoints');
const statusFPS = document.getElementById('statusFPS');
const selectedPointInfo = document.getElementById('selectedPointInfo');
const colorOptions = document.querySelectorAll('.color-option');
const cameraZoom = document.getElementById('cameraZoom');
const cameraX = document.getElementById('cameraX');
const cameraY = document.getElementById('cameraY');
const cameraZ = document.getElementById('cameraZ');
const zoomValue = document.getElementById('zoomValue');
const cameraXValue = document.getElementById('cameraXValue');
const cameraYValue = document.getElementById('cameraYValue');
const cameraZValue = document.getElementById('cameraZValue');
// Tab switching
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
tab.classList.add('active');
document.getElementById(`${tab.dataset.tab}-tab`).classList.add('active');
});
});
// Color picker
let selectedColor = '#39ff14';
colorOptions.forEach(option => {
option.addEventListener('click', () => {
colorOptions.forEach(opt => opt.classList.remove('active'));
option.classList.add('active');
selectedColor = option.dataset.color;
log(`Selected color: ${selectedColor}`, 'info', 'editTerminal');
});
});
// Log function with different terminals
function log(msg, level = 'info', terminalId = 'terminal') {
const targetTerminal = document.getElementById(terminalId);
const row = document.createElement('div');
row.className='line';
const p = document.createElement('span');
p.className='prompt';
p.textContent='webxos:~$';
const t = document.createElement('span');
t.textContent=' ' + msg;
if (level === 'error') t.style.color = 'var(--warning)';
if (level === 'success') t.style.color = 'var(--success)';
if (level === 'warning') t.style.color = '#ffa500';
row.appendChild(p);
row.appendChild(t);
targetTerminal.appendChild(row);
targetTerminal.scrollTop = targetTerminal.scrollHeight;
}
// Three.js Scene Setup
let scene, camera, renderer, controls, pointCloud, gridHelper, axesHelper;
let raycaster, mouse;
let selectedPointIndex = -1;
let pointGeometry, pointMaterial;
let frameCount = 0, lastTime = performance.now(), fps = 0;
function initThreeJS() {
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x050505);
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 15);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.getElementById('threeContainer').appendChild(renderer.domElement);
// Controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// Lighting
const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
// Grid Helper
gridHelper = new THREE.GridHelper(20, 20, 0x39ff14, 0x39ff14);
gridHelper.material.opacity = 0.2;
gridHelper.material.transparent = true;
scene.add(gridHelper);
// Axes Helper
axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// Raycaster for point selection
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
// Event listeners
window.addEventListener('resize', onWindowResize);
renderer.domElement.addEventListener('click', onCanvasClick);
// Start animation loop
animate();
log('Three.js scene initialized with grid and controls', 'success');
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onCanvasClick(event) {
// Calculate mouse position in normalized device coordinates
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
// Update the raycaster
raycaster.setFromCamera(mouse, camera);
// Check for intersections with points
if (pointCloud) {
const intersects = raycaster.intersectObject(pointCloud);
if (intersects.length > 0) {
// Get the index of the clicked point
const index = intersects[0].index;
selectedPointIndex = index;
// Get point position and color
const positions = pointGeometry.attributes.position.array;
const colors = pointGeometry.attributes.color.array;
const x = positions[index * 3];
const y = positions[index * 3 + 1];
const z = positions[index * 3 + 2];
const r = colors[index * 3];
const g = colors[index * 3 + 1];
const b = colors[index * 3 + 2];
// Update UI
selectedPointInfo.innerHTML = `
Position: (${x.toFixed(2)}, ${y.toFixed(2)}, ${z.toFixed(2)})<br>
Color: (${Math.round(r * 255)}, ${Math.round(g * 255)}, ${Math.round(b * 255)})
`;
log(`Selected point ${index} at (${x.toFixed(2)}, ${y.toFixed(2)}, ${z.toFixed(2)})`, 'info', 'editTerminal');
} else {
selectedPointIndex = -1;
selectedPointInfo.textContent = 'No point selected';
}
}
}
function animate() {
requestAnimationFrame(animate);
// Update FPS counter
frameCount++;
const currentTime = performance.now();
if (currentTime - lastTime >= 1000) {
fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
statusFPS.textContent = `FPS: ${fps}`;
frameCount = 0;
lastTime = currentTime;
}
// Auto-rotate if enabled
if (autoRotateEl.checked) {
pointCloud.rotation.y += 0.005;
}
// Update controls
controls.update();
// Render
renderer.render(scene, camera);
}
// Depth estimator
function estimateDepthAndPoints(image) {
return new Promise((resolve) => {
const maxDim = 700;
let w = image.naturalWidth || image.width, h = image.naturalHeight || image.height;
const scale = Math.min(1, maxDim / Math.max(w,h));
w = Math.max(1, Math.floor(w * scale)); h = Math.max(1, Math.floor(h * scale));
const c = document.createElement('canvas'); c.width = w; c.height = h;
const gctx = c.getContext('2d'); gctx.drawImage(image, 0, 0, w, h);
const data = gctx.getImageData(0,0,w,h).data;
const depth = new Float32Array(w*h);
for (let y=0;y<h;y++){
for (let x=0;x<w;x++){
const i = (y*w + x)*4;
const r = data[i]/255, g = data[i+1]/255, b = data[i+2]/255;
const bright = 0.2126*r + 0.7152*g + 0.0722*b;
const cx = (x/w - 0.5)*2, cy = (y/h - 0.5)*2;
const radial = Math.exp(-(cx*cx + cy*cy) * 0.9);
depth[y*w + x] = bright * 0.9 + radial * 0.5;
}
}
// normalize
let min = Infinity, max = -Infinity;
for (let i=0;i<depth.length;i++){ if (depth[i]<min) min=depth[i]; if (depth[i]>max) max=depth[i]; }
const range = (max - min) || 1;
for (let i=0;i<depth.length;i++) depth[i] = (depth[i] - min) / range;
// build positions and colors, sample with step
const maxPoints = 8000;
const step = Math.max(1, Math.floor(Math.sqrt((w*h)/maxPoints)));
const positions = [];
const colors = [];
for (let y=0;y<h;y+=step){
for (let x=0;x<w;x+=step){
const idx = y*w + x;
const px = idx*4;
const r = data[px]/255, g = data[px+1]/255, b = data[px+2]/255;
const d = depth[idx];
// map to 3D space: X right, Y up, Z forward - centered at (0,0,0)
const X = (x / w - 0.5) * 16;
const Y = (0.5 - y / h) * 9;
const Z = (d - 0.5) * (parseFloat(depthScaleEl.value) || 12);
positions.push(X, Y, Z);
colors.push(r, g, b);
}
}
resolve({ positions: positions, colors: colors, count: positions.length / 3 });
});
}
// Create point cloud from image
function createPointCloudFromImage(image){
log('Image uploaded: running DA3 brightness depth', 'info');
estimateDepthAndPoints(image).then(p => {
// Remove existing point cloud
if (pointCloud) {
scene.remove(pointCloud);
pointGeometry.dispose();
pointMaterial.dispose();
}
// Create geometry
pointGeometry = new THREE.BufferGeometry();
// Set positions
const positions = new Float32Array(p.positions);
pointGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
// Set colors
const colors = new Float32Array(p.colors);
pointGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
// Create material
pointMaterial = new THREE.PointsMaterial({
size: parseFloat(pointSizeEl.value),
vertexColors: true,
sizeAttenuation: true
});
// Create points
pointCloud = new THREE.Points(pointGeometry, pointMaterial);
scene.add(pointCloud);
// Update UI
statusPoints.textContent = `Points: ${p.count}`;
refreshObjectList();
log(`DA3 point cloud created with ${p.count} points at origin (0,0,0)`, 'success');
});
}
// Apply color to selected point
function applyColorToSelected() {
if (selectedPointIndex === -1) {
log('No point selected', 'warning', 'editTerminal');
return;
}
const colors = pointGeometry.attributes.color.array;
const hexColor = new THREE.Color(selectedColor);
colors[selectedPointIndex * 3] = hexColor.r;
colors[selectedPointIndex * 3 + 1] = hexColor.g;
colors[selectedPointIndex * 3 + 2] = hexColor.b;
pointGeometry.attributes.color.needsUpdate = true;
log(`Applied color ${selectedColor} to point ${selectedPointIndex}`, 'success', 'editTerminal');
}
// Apply color to all points
function applyColorToAll() {
if (!pointCloud) {
log('No point cloud to color', 'warning', 'editTerminal');
return;
}
const colors = pointGeometry.attributes.color.array;
const hexColor = new THREE.Color(selectedColor);
for (let i = 0; i < colors.length; i += 3) {
colors[i] = hexColor.r;
colors[i + 1] = hexColor.g;
colors[i + 2] = hexColor.b;
}
pointGeometry.attributes.color.needsUpdate = true;
log(`Applied color ${selectedColor} to all points`, 'success', 'editTerminal');
}
// Delete selected point
function deleteSelectedPoint() {
if (selectedPointIndex === -1) {
log('No point selected', 'warning', 'editTerminal');
return;
}
const positions = pointGeometry.attributes.position.array;
const colors = pointGeometry.attributes.color.array;
// Create new arrays without the selected point
const newPositions = [];
const newColors = [];
for (let i = 0; i < positions.length / 3; i++) {
if (i !== selectedPointIndex) {
newPositions.push(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
newColors.push(colors[i * 3], colors[i * 3 + 1], colors[i * 3 + 2]);
}
}
// Update geometry
pointGeometry.setAttribute('position', new THREE.Float32BufferAttribute(newPositions, 3));
pointGeometry.setAttribute('color', new THREE.Float32BufferAttribute(newColors, 3));
// Update point count
const newCount = newPositions.length / 3;
statusPoints.textContent = `Points: ${newCount}`;
// Reset selection
selectedPointIndex = -1;
selectedPointInfo.textContent = 'No point selected';
log(`Deleted point ${selectedPointIndex}. ${newCount} points remaining`, 'success', 'editTerminal');
}
// Recompute depth with current settings
function recomputeDepth(){
if (!sceneState.sourceImage) {
log('No source image available to recompute depth', 'error');
return;
}
log('Recomputing depth with current scale...', 'info');
createPointCloudFromImage(sceneState.sourceImage);
}
function clearScene(){
if (pointCloud) {
scene.remove(pointCloud);
pointGeometry.dispose();
pointMaterial.dispose();
pointCloud = null;
}
statusPoints.textContent = 'Points: 0';
refreshObjectList();
selectedPointIndex = -1;
selectedPointInfo.textContent = 'No point selected';
log('Scene cleared', 'info');
}
function refreshObjectList(){
objectListEl.innerHTML = '';
const list = [];
if (pointCloud) list.push('Point Cloud');
if (list.length === 0) {
const el = document.createElement('div');
el.textContent = 'No objects';
el.style.padding='6px';
el.style.border='1px solid rgba(57,255,20,0.04)';
objectListEl.appendChild(el);
} else {
list.forEach(n=>{
const el = document.createElement('div');
el.textContent = n;
el.style.padding='6px';
el.style.border='1px solid rgba(57,255,20,0.04)';
objectListEl.appendChild(el);
});
}
}
// Extract first frame from MP4 file
function extractFirstFrameFromVideo(file){
return new Promise((resolve,reject)=>{
const url = URL.createObjectURL(file);
const v = document.createElement('video');
v.muted = true; v.crossOrigin = 'anonymous'; v.preload = 'auto'; v.src = url;
let done = false;
const timeout = setTimeout(()=> {
if (!done) { URL.revokeObjectURL(url); reject(new Error('Video load timeout')); }
}, 10000);
v.addEventListener('loadeddata', ()=>{
try { v.currentTime = 0.02; } catch(e){ /* ignore */ }
});
v.addEventListener('seeked', ()=>{
if (done) return;
const c = document.createElement('canvas'); c.width = v.videoWidth; c.height = v.videoHeight;
const g = c.getContext('2d'); g.drawImage(v,0,0,c.width,c.height);
const img = new Image();
img.onload = ()=> { done = true; clearTimeout(timeout); URL.revokeObjectURL(url); resolve(img); };
img.onerror = ()=> { done = true; clearTimeout(timeout); URL.revokeObjectURL(url); reject(new Error('Frame capture failed')); };
img.src = c.toDataURL('image/jpeg');
});
v.addEventListener('error', ()=> { clearTimeout(timeout); URL.revokeObjectURL(url); reject(new Error('Video load error')); });
});
}
// File handling
function handleImageFile(file){
if (!file) return log('No file', 'error');
const t = (file.type || '').toLowerCase();
if (!t.includes('jpeg') && !t.includes('jpg')) return log('Only JPEG supported', 'error');
const reader = new FileReader();
reader.onerror = ()=> log('File read error', 'error');
reader.onload = (ev)=>{
const img = new Image();
img.onload = ()=> {
sceneState.sourceImage = img;
createPointCloudFromImage(img);
};
img.onerror = ()=> log('Invalid image', 'error');
img.src = ev.target.result;
};
reader.readAsDataURL(file);
}
function handleVideoFile(file){
if (!file) return log('No file', 'error');
const t = (file.type || '').toLowerCase();
if (!t.includes('mp4')) return log('Only MP4 supported', 'error');
extractFirstFrameFromVideo(file).then(img=>{
sceneState.sourceImage = img;
createPointCloudFromImage(img);
}).catch(err=> log('Video frame error: ' + err.message, 'error'));
}
// Drag & drop
function preventDefaults(e){ e.preventDefault(); e.stopPropagation(); }
['dragenter','dragover','dragleave','drop'].forEach(ev =>
document.getElementById('threeContainer').addEventListener(ev, preventDefaults)
);
document.getElementById('threeContainer').addEventListener('dragover', ()=> dropZone.classList.add('active'));
document.getElementById('threeContainer').addEventListener('dragleave', ()=> dropZone.classList.remove('active'));
document.getElementById('threeContainer').addEventListener('drop', (e)=>{
dropZone.classList.remove('active');
const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
if (!f) return log('No file dropped', 'error');
const t = (f.type || '').toLowerCase();
if (t.includes('jpeg') || t.includes('jpg')) handleImageFile(f);
else if (t.includes('mp4')) handleVideoFile(f);
else log('Unsupported file type. Use JPEG or MP4', 'error');
});
// Scene state
const sceneState = {
sourceImage: null
};
// UI wiring
uploadImageBtn.addEventListener('click', ()=> imageInput.click());
uploadVideoBtn.addEventListener('click', ()=> videoInput.click());
recomputeBtn.addEventListener('click', ()=> recomputeDepth());
resetBtn.addEventListener('click', ()=> clearScene());
exportBtn.addEventListener('click', ()=>{
if (!pointCloud) {
log('No point cloud to export', 'error');
return;
}
const positions = pointGeometry.attributes.position.array;
const colors = pointGeometry.attributes.color.array;
const count = positions.length / 3;
const pointData = [];
for (let i = 0; i < count; i++) {
pointData.push({
x: positions[i * 3],
y: positions[i * 3 + 1],
z: positions[i * 3 + 2],
r: colors[i * 3],
g: colors[i * 3 + 1],
b: colors[i * 3 + 2]
});
}
const payload = {
points: pointData,
count: count,
pointSize: pointSizeEl.value,
depthScale: depthScaleEl.value
};
const blob = new Blob([JSON.stringify(payload, null, 2)], { type:'application/json' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'point_cloud.json';
document.body.appendChild(a);
a.click();
a.remove();
log('Point cloud exported to JSON', 'success');
});
applyColorBtn.addEventListener('click', applyColorToSelected);
applyColorAllBtn.addEventListener('click', applyColorToAll);
deletePointBtn.addEventListener('click', deleteSelectedPoint);
imageInput.addEventListener('change', (e)=> {
const f = e.target.files && e.target.files[0];
if (!f) return;
handleImageFile(f);
imageInput.value='';
});
videoInput.addEventListener('change', (e)=> {
const f = e.target.files && e.target.files[0];
if (!f) return;
handleVideoFile(f);
videoInput.value='';
});
// Control listeners
pointSizeEl.addEventListener('input', ()=> {
if (pointMaterial) {
pointMaterial.size = parseFloat(pointSizeEl.value);
}
});
depthScaleEl.addEventListener('input', ()=> {
log('Depth scale changed - use "Recompute Depth" to regenerate point cloud', 'info');
});
gridSizeEl.addEventListener('input', ()=> {
scene.remove(gridHelper);
gridHelper = new THREE.GridHelper(
parseFloat(gridSizeEl.value),
parseFloat(gridDivisionsEl.value),
0x39ff14, 0x39ff14
);
gridHelper.material.opacity = 0.2;
gridHelper.material.transparent = true;
scene.add(gridHelper);
});
gridDivisionsEl.addEventListener('input', ()=> {
scene.remove(gridHelper);
gridHelper = new THREE.GridHelper(
parseFloat(gridSizeEl.value),
parseFloat(gridDivisionsEl.value),
0x39ff14, 0x39ff14
);
gridHelper.material.opacity = 0.2;
gridHelper.material.transparent = true;
scene.add(gridHelper);
});
cameraZoom.addEventListener('input', ()=> {
camera.zoom = parseFloat(cameraZoom.value);
zoomValue.textContent = cameraZoom.value;
camera.updateProjectionMatrix();
});
cameraX.addEventListener('input', ()=> {
camera.position.x = parseFloat(cameraX.value);
cameraXValue.textContent = cameraX.value;
});
cameraY.addEventListener('input', ()=> {
camera.position.y = parseFloat(cameraY.value);
cameraYValue.textContent = cameraY.value;
});
cameraZ.addEventListener('input', ()=> {
camera.position.z = parseFloat(cameraZ.value);
cameraZValue.textContent = cameraZ.value;
});
// Initialize the application
function start(){
initThreeJS();
log('DA3 Point Cloud Editor ready. Upload JPEG or MP4 to generate 3D point cloud.', 'success');
log('Click on points to select and edit them.', 'info');
}
start();
})();
</script>
</body>
</html>