-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
2159 lines (1884 loc) · 102 KB
/
index.html
File metadata and controls
2159 lines (1884 loc) · 102 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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bay Area DEM 3D Viewer</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
overflow: hidden;
background: linear-gradient(180deg, #000030, #000000);
}
#container {
width: 100vw;
height: 100vh;
position: relative;
}
#info {
position: absolute;
top: 10px;
right: 10px;
color: white;
background: rgba(0, 0, 0, 0.7);
padding: 15px;
border-radius: 8px;
font-size: 14px;
width: 300px;
backdrop-filter: blur(10px);
}
#controls {
position: absolute;
top: 10px;
left: 10px;
background: rgba(0, 0, 0, 0.7);
padding: 15px;
border-radius: 8px;
color: white;
width: 300px;
backdrop-filter: blur(10px);
}
#controls h3 {
margin-bottom: 10px;
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
padding-bottom: 5px;
}
.control-group {
margin: 10px 0;
}
.control-group label {
display: block;
margin-bottom: 5px;
font-size: 12px;
color: #aaa;
}
input[type="range"] {
width: 100%;
margin: 5px 0;
}
input[type="file"] {
width: 100%;
padding: 5px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
color: white;
cursor: pointer;
}
button {
background: #4CAF50;
border: none;
color: white;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
width: 100%;
margin-top: 5px;
transition: background 0.3s;
}
button:hover {
background: #45a049;
}
#loading {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 24px;
text-align: center;
}
.spinner {
border: 4px solid rgba(255, 255, 255, 0.3);
border-top: 4px solid white;
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
#stats {
position: absolute;
bottom: 10px;
left: 10px;
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 10px;
border-radius: 8px;
font-size: 12px;
font-family: monospace;
backdrop-filter: blur(10px);
}
</style>
</head>
<body>
<div id="container">
<div id="info">
<h2>Bay Area 3D Terrain</h2>
<p>Interactive 3D visualization of the San Francisco Bay Area</p>
<p style="font-size: 11px; margin-top: 5px; color: #aaa;">
Original data by <a href="https://earthworks.stanford.edu/catalog/stanford-nh236hj3673"
target="_blank"
style="color: #87CEEB; text-decoration: none; border-bottom: 1px dotted #87CEEB;">
Stanford Earthworks
</a>
</p>
<p style="font-size: 11px; margin-top: 3px; color: #aaa;">
Developed by <a href="https://manoellemos.com"
target="_blank"
style="color: #87CEEB; text-decoration: none; border-bottom: 1px dotted #87CEEB;">
Manoel Lemos
</a>
</p>
<p style="font-size: 11px; margin-top: 3px; color: #aaa;">
Source on <a href="https://github.com/mlemos/3dbay"
target="_blank"
style="color: #87CEEB; text-decoration: none; border-bottom: 1px dotted #87CEEB;">
GitHub
</a>
</p>
<p style="font-size: 11px; margin-top: 3px; color: #aaa;">
Tools: <a href="crop.html"
target="_blank"
style="color: #87CEEB; text-decoration: none; border-bottom: 1px dotted #87CEEB;">
Crop Tool
</a>
</p>
</div>
<div id="controls">
<h3>Controls</h3>
<div class="control-group">
<label for="fileInput">Load GeoTIFF:</label>
<input type="file" id="fileInput" accept=".tif,.tiff" />
<button id="loadSample">Reload Bay Area Data</button>
</div>
<div class="control-group">
<label for="exaggeration">Vertical Exaggeration: <span id="exagValue">0.2</span>x</label>
<input type="range" id="exaggeration" min="0.1" max="2" step="0.1" value="0.2" />
</div>
<div class="control-group">
<label for="quality">Mesh Quality: <span id="qualityValue">Ultra</span></label>
<input type="range" id="quality" min="1" max="5" step="1" value="4" />
</div>
<div class="control-group">
<label for="colorScheme">Color Scheme:</label>
<select id="colorScheme" style="width: 100%; padding: 5px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px; color: white;">
<option value="heyho" selected>HeyHo</option>
<option value="elevation">Elevation</option>
<option value="terrain">Terrain</option>
<option value="grayscale">Grayscale</option>
<option value="heatmap">Heatmap</option>
</select>
<div id="colorPalette" style="margin-top: 8px; height: 20px; border-radius: 4px; border: 1px solid rgba(255, 255, 255, 0.3); background: linear-gradient(to right, rgb(0, 77, 0) 0%, rgb(128, 255, 0) 25%, rgb(255, 255, 0) 50%, rgb(255, 128, 0) 75%, rgb(255, 0, 0) 100%); background-clip: padding-box; overflow: hidden;"></div>
<div style="margin-top: 4px; font-size: 10px; color: #888;">Elevation Range: <span id="elevationRange">Loading...</span></div>
</div>
<div class="control-group">
<label for="renderMode">Render Mode:</label>
<select id="renderMode" style="width: 100%; padding: 5px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px; color: white;">
<option value="voxel" selected>Voxels</option>
<option value="mesh">Mesh</option>
<option value="wireframe">Wireframe</option>
</select>
</div>
<div class="control-group" id="voxelGapControl">
<label style="display: flex; align-items: center;">
<input type="checkbox" id="voxelGapless" checked style="margin-right: 5px;" />
Gapless Voxels (Remove gaps between voxels)
</label>
</div>
<div class="control-group">
<label for="seaLevelMode">Sea Level Display:</label>
<select id="seaLevelMode" style="width: 100%; padding: 5px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px; color: white;">
<option value="scheme">Scheme</option>
<option value="solid">Solid Color</option>
<option value="hidden" selected>Hidden</option>
</select>
</div>
<div class="control-group">
<label for="seaLevelColor">Sea Level Color:</label>
<input type="color" id="seaLevelColor" value="#000814" style="width: 100%; height: 30px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px;" />
</div>
<div class="control-group">
<label for="seaLevelTransparency">Sea Level Opacity: <span id="seaLevelTransparencyValue">100%</span></label>
<input type="range" id="seaLevelTransparency" min="0" max="100" value="100" style="width: 100%;" />
</div>
<div class="control-group">
<label for="backgroundMode">Background:</label>
<select id="backgroundMode" style="width: 100%; padding: 5px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px; color: white;">
<option value="gradient" selected>Gradient</option>
<option value="flat">Flat Color</option>
<option value="sky">No Background (Sky view)</option>
</select>
</div>
<div class="control-group">
<label for="backgroundColor">Background Color:</label>
<input type="color" id="backgroundColor" value="#000030" style="width: 100%; height: 30px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px;" />
</div>
<div class="control-group" style="display: flex; justify-content: space-between;">
<label style="display: flex; align-items: center;">
<input type="checkbox" id="showBounds" checked style="margin-right: 5px;" />
Show Bounds
</label>
<label style="display: flex; align-items: center;">
<input type="checkbox" id="showGrid" style="margin-right: 5px;" />
Show Grid
</label>
<label style="display: flex; align-items: center;">
<input type="checkbox" id="showAxis" style="margin-right: 5px;" />
Show Axis
</label>
</div>
<div class="control-group">
<label style="font-size: 12px; color: #aaa; margin-bottom: 5px;">Actions:</label>
<button id="resetEverything" style="width: 100%; margin-bottom: 8px; background: #d9534f; padding: 8px; font-size: 14px;">Back to Default</button>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">
<button id="resetCamera" style="padding: 8px; font-size: 13px;">Initial View</button>
<button id="topView" style="padding: 8px; font-size: 13px;">Top View</button>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">
<button id="copyConfig" style="padding: 8px; font-size: 13px; background: #17a2b8;">Copy Config</button>
<button id="pasteConfig" style="padding: 8px; font-size: 13px; background: #17a2b8;">Paste Config</button>
</div>
<label style="font-size: 12px; color: #aaa; margin-bottom: 5px; margin-top: 10px; display: block;">Image Export:</label>
<div style="margin-bottom: 8px;">
<label style="display: flex; align-items: center; font-size: 12px; margin-bottom: 5px;">
<input type="checkbox" id="transparentBackground" style="margin-right: 5px;" />
Transparent Background
</label>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">
<button id="saveImage" style="padding: 8px; font-size: 13px; background: #6f42c1;">Save PNG</button>
<button id="copyImage" style="padding: 8px; font-size: 13px; background: #6f42c1;">Copy Image</button>
</div>
<button id="toggleUI" style="width: 100%; padding: 8px; font-size: 14px;">Hide UI (U)</button>
</div>
<div class="control-group" style="font-size: 11px; color: #aaa; margin-top: 15px; padding-top: 10px; border-top: 1px solid rgba(255,255,255,0.2);">
<div style="margin-bottom: 8px;"><strong>Navigation:</strong></div>
<div style="margin-bottom: 5px;"><strong>Mouse:</strong></div>
<div style="margin-left: 10px;">• Left drag: Rotate view</div>
<div style="margin-left: 10px;">• Right drag: Pan camera</div>
<div style="margin-left: 10px;">• Scroll: Zoom in/out</div>
<div style="margin-bottom: 5px; margin-top: 8px;"><strong>Keyboard:</strong></div>
<div style="margin-left: 10px;">• Arrow keys: Pan map</div>
<div style="margin-left: 10px;">• Shift + Arrows: Rotate view</div>
<div style="margin-left: 10px;">• Page Up/Down: Zoom in/out</div>
<div style="margin-left: 10px;">• U: Toggle UI on/off</div>
</div>
</div>
<div id="lightingControls" style="position: absolute; top: 10px; left: 320px; background: rgba(0, 0, 0, 0.7); padding: 15px; border-radius: 8px; color: white; width: 280px; backdrop-filter: blur(10px);">
<h3 style="margin: 0 0 10px 0; border-bottom: 1px solid rgba(255, 255, 255, 0.3); padding-bottom: 5px;">Lighting Controls</h3>
<div class="control-group">
<label for="ambientIntensity">Ambient Light: <span id="ambientIntensityValue">60%</span></label>
<input type="range" id="ambientIntensity" min="0" max="100" value="60" style="width: 100%;" />
</div>
<div class="control-group">
<label for="ambientColor">Ambient Color:</label>
<input type="color" id="ambientColor" value="#ffffff" style="width: 100%; height: 30px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px;" />
</div>
<div class="control-group">
<label for="directionalIntensity">Directional Light: <span id="directionalIntensityValue">80%</span></label>
<input type="range" id="directionalIntensity" min="0" max="200" value="80" style="width: 100%;" />
</div>
<div class="control-group">
<label for="directionalColor">Directional Color:</label>
<input type="color" id="directionalColor" value="#ffffff" style="width: 100%; height: 30px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px;" />
</div>
<div class="control-group">
<label for="sunAngle">Sun Angle: <span id="sunAngleValue">45°</span></label>
<input type="range" id="sunAngle" min="0" max="90" value="45" style="width: 100%;" />
</div>
<div class="control-group">
<label for="sunRotation">Sun Rotation: <span id="sunRotationValue">45°</span></label>
<input type="range" id="sunRotation" min="0" max="360" value="45" style="width: 100%;" />
</div>
<div class="control-group">
<label for="hemisphereIntensity">Hemisphere Light: <span id="hemisphereIntensityValue">30%</span></label>
<input type="range" id="hemisphereIntensity" min="0" max="100" value="30" style="width: 100%;" />
</div>
<div class="control-group">
<label for="skyColor">Sky Color:</label>
<input type="color" id="skyColor" value="#87CEEB" style="width: 100%; height: 30px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px;" />
</div>
<div class="control-group">
<label for="groundColor">Ground Color:</label>
<input type="color" id="groundColor" value="#333333" style="width: 100%; height: 30px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px;" />
</div>
<div class="control-group">
<label style="display: flex; align-items: center;">
<input type="checkbox" id="shadowsEnabled" checked style="margin-right: 5px;" />
Enable Shadows
</label>
</div>
<div class="control-group">
<label style="font-size: 12px; color: #aaa; margin-bottom: 5px;">Lighting Presets:</label>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
<button id="presetNoon" style="padding: 8px; font-size: 13px;">Noon</button>
<button id="presetSunset" style="padding: 8px; font-size: 13px;">Sunset</button>
<button id="presetNight" style="padding: 8px; font-size: 13px;">Night</button>
<button id="presetDefault" style="padding: 8px; font-size: 13px;">Default</button>
</div>
</div>
</div>
<div id="loading" style="display: none;">
<div class="spinner"></div>
<p>Loading elevation data...</p>
</div>
<div id="rebuilding" style="display: none; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: white; font-size: 14px; background: rgba(0,0,0,0.5); padding: 10px; border-radius: 5px;">
Updating mesh...
</div>
<div id="cameraStatus" style="position: absolute; bottom: 10px; right: 10px; background: rgba(0, 0, 0, 0.7); color: white; padding: 10px; border-radius: 8px; font-size: 12px; font-family: monospace; backdrop-filter: blur(10px); min-width: 280px;">
<div style="border-bottom: 1px solid rgba(255, 255, 255, 0.3); padding-bottom: 5px; margin-bottom: 5px;">
<strong>Data Information</strong><br>
<span id="dataStats">No data loaded</span>
</div>
<div>
<strong>Camera Status</strong><br>
Position: X: <span id="camPosX">0.0</span>, Y: <span id="camPosY">0.0</span>, Z: <span id="camPosZ">0.0</span><br>
Target: X: <span id="camTargetX">0.0</span>, Y: <span id="camTargetY">0.0</span>, Z: <span id="camTargetZ">0.0</span><br>
Distance: <span id="camDistance">0.0</span>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/geotiff@2.1.0/dist-browser/geotiff.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.159.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.159.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
let scene, camera, renderer, controls;
let terrain = null;
let verticalExaggeration = 0.2;
let ambientLight, directionalLight, hemisphereLight;
// Store elevation data for rebuilding mesh
let storedElevationData = null;
let storedWidth = null;
let storedHeight = null;
let storedBBox = null;
let storedPixelScale = null;
let globalMinElev = null;
let globalMaxElev = null;
let gridHelper = null; // Store grid reference for repositioning
let axesHelper = null; // Store axes reference for toggling
let boundingBoxHelper = null; // Store bounding box reference
// Debounce timer for controls
let rebuildTimeout = null;
let isRebuilding = false;
// Create gradient background
function createGradientBackground() {
const canvas = document.createElement('canvas');
canvas.width = 2;
canvas.height = 512;
const context = canvas.getContext('2d');
const gradient = context.createLinearGradient(0, 0, 0, 512);
const baseColor = document.getElementById('backgroundColor').value;
gradient.addColorStop(0, baseColor);
gradient.addColorStop(0.4, baseColor);
gradient.addColorStop(1, '#000000');
context.fillStyle = gradient;
context.fillRect(0, 0, 2, 512);
const texture = new THREE.CanvasTexture(canvas);
texture.needsUpdate = true;
return texture;
}
// Initialize Three.js scene
function initScene() {
scene = new THREE.Scene();
// Set initial background - gradient by default
scene.background = createGradientBackground();
scene.fog = new THREE.Fog(0x000000, 100, 10000);
// Camera
camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
0.1,
20000
);
camera.position.set(-541.2, 385.2, 62.4);
// Renderer
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
premultipliedAlpha: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setClearColor(0x000000, 0); // Transparent background
document.getElementById('container').appendChild(renderer.domElement);
// Controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.minDistance = 10;
controls.maxDistance = 5000;
controls.target.set(-76.0, -73.9, -85.3); // Set initial target at center
// Lights
ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(100, 200, 100);
directionalLight.castShadow = true;
directionalLight.shadow.camera.near = 0.1;
directionalLight.shadow.camera.far = 5000;
directionalLight.shadow.camera.left = -1000;
directionalLight.shadow.camera.right = 1000;
directionalLight.shadow.camera.top = 1000;
directionalLight.shadow.camera.bottom = -1000;
scene.add(directionalLight);
// Hemisphere light for sky/ground ambient
hemisphereLight = new THREE.HemisphereLight(0x87CEEB, 0x333333, 0.3);
scene.add(hemisphereLight);
// Grid helper - matches terrain size and positioned below
gridHelper = new THREE.GridHelper(1000, 50, 0x444444, 0x222222);
gridHelper.position.y = -50; // Position below the terrain (will be adjusted based on data)
gridHelper.visible = false; // Start hidden by default
scene.add(gridHelper);
// Axes helper
axesHelper = new THREE.AxesHelper(500);
axesHelper.visible = false; // Start hidden by default
scene.add(axesHelper);
// Bounding box helper - just a square outline at ground level, slightly outside the data
const offset = 10; // Offset to place the square outside the data
const points = [
new THREE.Vector3(-500 - offset, 0, -500 - offset),
new THREE.Vector3(500 + offset, 0, -500 - offset),
new THREE.Vector3(500 + offset, 0, 500 + offset),
new THREE.Vector3(-500 - offset, 0, 500 + offset),
new THREE.Vector3(-500 - offset, 0, -500 - offset) // Close the square
];
const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
boundingBoxHelper = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({
color: 0x00ffff,
opacity: 0.7,
transparent: true
}));
boundingBoxHelper.visible = true; // Start visible by default
scene.add(boundingBoxHelper);
animate();
}
// Update camera status display
function updateCameraStatus() {
if (camera && controls) {
const pos = camera.position;
const target = controls.target;
const distance = pos.distanceTo(target);
// Update individual span elements for smoother updates
const updateElement = (id, value) => {
const element = document.getElementById(id);
if (element) element.textContent = value;
};
updateElement('camPosX', pos.x.toFixed(1));
updateElement('camPosY', pos.y.toFixed(1));
updateElement('camPosZ', pos.z.toFixed(1));
updateElement('camTargetX', target.x.toFixed(1));
updateElement('camTargetY', target.y.toFixed(1));
updateElement('camTargetZ', target.z.toFixed(1));
updateElement('camDistance', distance.toFixed(1));
}
}
// Animation loop
function animate() {
requestAnimationFrame(animate);
handleKeyboardNavigation();
controls.update();
updateCameraStatus();
renderer.render(scene, camera);
updateStats();
}
// Load GeoTIFF file
async function loadGeoTIFF(file) {
document.getElementById('loading').style.display = 'block';
try {
console.log('Converting file to ArrayBuffer...');
const arrayBuffer = await file.arrayBuffer();
console.log('ArrayBuffer size:', arrayBuffer.byteLength, 'bytes');
console.log('Parsing GeoTIFF...');
const tiff = await GeoTIFF.fromArrayBuffer(arrayBuffer);
const image = await tiff.getImage();
const width = image.getWidth();
const height = image.getHeight();
console.log('Image dimensions:', width, 'x', height);
console.log('Reading raster data...');
const rasters = await image.readRasters();
const data = rasters[0];
console.log('Raster data length:', data.length);
// Get bounds and resolution
const bbox = image.getBoundingBox();
const pixelScale = image.getFileDirectory().ModelPixelScale;
console.log('Bounding box:', bbox);
console.log('Pixel scale:', pixelScale);
// Store data for rebuilding
storedElevationData = data;
storedWidth = width;
storedHeight = height;
storedBBox = bbox;
storedPixelScale = pixelScale;
// Create terrain mesh (with camera reset on initial load)
createTerrainMesh(data, width, height, bbox, pixelScale, true);
document.getElementById('loading').style.display = 'none';
console.log('Terrain mesh created successfully!');
} catch (error) {
console.error('Error loading GeoTIFF:', error);
console.error('Error stack:', error.stack);
alert('Error loading file: ' + error.message);
document.getElementById('loading').style.display = 'none';
}
}
// Create 3D terrain mesh from elevation data
function createTerrainMesh(elevationData, width, height, bbox, pixelScale, resetCamera = false) {
// Remove existing terrain
if (terrain) {
scene.remove(terrain);
if (terrain.geometry) terrain.geometry.dispose();
if (terrain.material) {
if (Array.isArray(terrain.material)) {
terrain.material.forEach(m => m.dispose());
} else {
terrain.material.dispose();
}
}
terrain = null;
}
// Get quality factor and render mode
const qualityValue = parseInt(document.getElementById('quality').value);
const renderMode = document.getElementById('renderMode').value;
// Calculate optimal step sizes based on data dimensions
// Three.js PlaneGeometry can handle up to ~65k vertices per dimension (2^16)
// Increased limits for better quality visualization
const maxTotalVertices = 4000000; // 4 million vertices for higher quality
const maxDimension = 2048; // Maximum per dimension
// Define quality steps based on data size
let step;
if (qualityValue === 1) { // Low
step = Math.max(16, Math.floor(Math.min(width, height) / 64));
} else if (qualityValue === 2) { // Medium
step = Math.max(8, Math.floor(Math.min(width, height) / 128));
} else if (qualityValue === 3) { // High
step = Math.max(4, Math.floor(Math.min(width, height) / 256));
} else if (qualityValue === 4) { // Ultra
step = Math.max(2, Math.floor(Math.min(width, height) / 512));
} else { // Maximum (5)
step = 1; // Use every pixel
}
// Calculate mesh dimensions
let meshWidth = Math.floor(width / step);
let meshHeight = Math.floor(height / step);
// Ensure we don't exceed limits
while ((meshWidth * meshHeight) > maxTotalVertices && step < Math.min(width, height)) {
step += 1;
meshWidth = Math.floor(width / step);
meshHeight = Math.floor(height / step);
}
// Final dimension limits
meshWidth = Math.min(meshWidth, maxDimension);
meshHeight = Math.min(meshHeight, maxDimension);
console.log(`Data dimensions: ${width}x${height}`);
console.log(`Creating mesh: ${meshWidth}x${meshHeight} (step: ${step}, quality: ${qualityValue})`);
console.log(`Total vertices: ${meshWidth * meshHeight}`);
// Show warning if resolution was limited
if (qualityValue === 4 && step > 2) {
console.log(`Note: Ultra quality adjusted to step ${step} to handle large dataset (${width}x${height})`);
}
// Create geometry
const geometry = new THREE.PlaneGeometry(
1000, // world width
1000, // world height
meshWidth - 1,
meshHeight - 1
);
// Get min/max elevation
let minElev = Infinity;
let maxElev = -Infinity;
for (let i = 0; i < elevationData.length; i += step) {
const value = elevationData[i];
if (!isNaN(value) && value !== -9999) {
minElev = Math.min(minElev, value);
maxElev = Math.max(maxElev, value);
}
}
console.log('Elevation range:', minElev, 'to', maxElev, 'meters');
// Store global min/max for color palette
globalMinElev = minElev;
globalMaxElev = maxElev;
// Update elevation range display
const rangeSpan = document.getElementById('elevationRange');
if (rangeSpan) {
rangeSpan.textContent = `${minElev.toFixed(0)}m to ${maxElev.toFixed(0)}m`;
}
// Calculate actual step for data sampling based on limited mesh size
const actualStepX = width / meshWidth;
const actualStepY = height / meshHeight;
// Position grid below the lowest point in the terrain
if (gridHelper) {
// Calculate the lowest point in world units
const lowestPoint = (minElev - minElev) / (maxElev - minElev) * 200 * verticalExaggeration;
gridHelper.position.y = lowestPoint - 30; // Position 30 units below the lowest terrain point
}
// Keep bounding box at sea level (y = 0)
if (boundingBoxHelper) {
// Just ensure visibility is correct
boundingBoxHelper.visible = document.getElementById('showBounds') ?
document.getElementById('showBounds').checked : true;
}
// Check render mode
if (renderMode === 'voxel') {
// Create voxel representation
createVoxelTerrain(elevationData, width, height, meshWidth, meshHeight, minElev, maxElev, actualStepX, actualStepY);
// Update stats
const actualResolution = (step * 30).toFixed(1);
const dataStatsElement = document.getElementById('dataStats');
if (dataStatsElement) {
dataStatsElement.innerHTML = `
Data: ${width}x${height} pixels<br>
Voxels: ${meshWidth}x${meshHeight}<br>
Resolution: ~${actualResolution}m (1:${step} sampling)<br>
Elevation: ${minElev.toFixed(1)}m - ${maxElev.toFixed(1)}m<br>
Total Voxels: ${(meshWidth * meshHeight).toLocaleString()}
`;
}
if (resetCamera && controls) {
controls.target.set(-76.0, -73.9, -85.3);
camera.position.set(-541.2, 385.2, 62.4);
controls.update();
}
return; // Exit early for voxel mode
}
// Update vertices with elevation and check sea level settings
const vertices = geometry.attributes.position.array;
const seaLevelMode = document.getElementById('seaLevelMode').value;
for (let j = 0; j < meshHeight; j++) {
for (let i = 0; i < meshWidth; i++) {
const index = (j * meshWidth + i) * 3;
const dataX = Math.floor(i * actualStepX);
const dataY = Math.floor(j * actualStepY);
const dataIndex = Math.min(dataY * width + dataX, elevationData.length - 1);
let elevation = elevationData[dataIndex];
if (isNaN(elevation) || elevation === -9999) {
elevation = minElev;
}
// Always set normal elevation - we'll handle hiding via opacity
const normalizedElev = (elevation - minElev) / (maxElev - minElev);
vertices[index + 2] = normalizedElev * 200 * verticalExaggeration;
}
}
geometry.computeVertexNormals();
geometry.attributes.position.needsUpdate = true;
// Create material with color based on elevation
// Always use RGBA for proper transparency support
const colors = new Float32Array(meshWidth * meshHeight * 4);
for (let j = 0; j < meshHeight; j++) {
for (let i = 0; i < meshWidth; i++) {
const index = (j * meshWidth + i) * 4;
const dataX = Math.floor(i * actualStepX);
const dataY = Math.floor(j * actualStepY);
const dataIndex = Math.min(dataY * width + dataX, elevationData.length - 1);
let elevation = elevationData[dataIndex];
if (isNaN(elevation) || elevation === -9999) {
elevation = minElev;
}
const normalized = (elevation - minElev) / (maxElev - minElev);
const color = getColorForElevation(normalized, elevation);
// Handle different sea level modes
if (color.r === -1) {
// Hidden mode - make completely transparent (0% opacity)
colors[index] = 0;
colors[index + 1] = 0;
colors[index + 2] = 0;
colors[index + 3] = 0; // 0% opacity - fully transparent
} else if (color.a !== undefined) {
// Has explicit alpha value (0 to 1)
// Premultiply alpha to avoid darkening
colors[index] = color.r;
colors[index + 1] = color.g;
colors[index + 2] = color.b;
colors[index + 3] = color.a; // Use specified alpha
} else {
// No alpha specified, default to opaque
colors[index] = color.r;
colors[index + 1] = color.g;
colors[index + 2] = color.b;
colors[index + 3] = 1.0; // 100% opacity - fully opaque
}
}
}
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 4));
// Create material based on render mode
// Always enable transparency to support vertex alpha
const seaMode = document.getElementById('seaLevelMode').value;
const material = new THREE.MeshPhongMaterial({
vertexColors: true,
wireframe: renderMode === 'wireframe',
side: THREE.DoubleSide,
flatShading: false,
transparent: true, // Always enable for vertex alpha support
alphaTest: 0.01, // Don't render pixels with alpha < 0.01
depthWrite: true,
depthTest: true
});
// Create mesh
terrain = new THREE.Mesh(geometry, material);
terrain.rotation.x = -Math.PI / 2;
terrain.castShadow = true;
terrain.receiveShadow = true;
scene.add(terrain);
// Update stats
const actualResolution = (step * 30).toFixed(1); // Assuming 30m per pixel original resolution
const dataStatsElement = document.getElementById('dataStats');
if (dataStatsElement) {
dataStatsElement.innerHTML = `
Data: ${width}x${height} pixels<br>
Mesh: ${meshWidth}x${meshHeight} vertices<br>
Resolution: ~${actualResolution}m (1:${step} sampling)<br>
Elevation: ${minElev.toFixed(1)}m - ${maxElev.toFixed(1)}m<br>
Triangles: ${((meshWidth - 1) * (meshHeight - 1) * 2).toLocaleString()}
`;
}
// Only reset camera if explicitly requested (e.g., initial load or reset button)
if (resetCamera && controls) {
controls.target.set(-76.0, -73.9, -85.3);
camera.position.set(-541.2, 385.2, 62.4);
controls.update();
}
}
// Create voxel terrain using instanced meshes
function createVoxelTerrain(elevationData, width, height, meshWidth, meshHeight, minElev, maxElev, actualStepX, actualStepY) {
// Create a single box geometry for all voxels
const gapless = document.getElementById('voxelGapless').checked;
const voxelScale = gapless ? 1.0 : 0.9;
// Calculate voxel size based on the terrain dimensions
// For gapless mode, voxels need to be sized to exactly fill the grid
const baseVoxelSizeX = 1000 / (meshWidth - 1);
const baseVoxelSizeY = 1000 / (meshHeight - 1);
const voxelSizeX = baseVoxelSizeX * voxelScale;
const voxelSizeY = baseVoxelSizeY * voxelScale;
const boxGeometry = new THREE.BoxGeometry(voxelSizeX, voxelSizeY, 1);
// Create instanced mesh for performance
const instanceCount = meshWidth * meshHeight;
const seaLevelMode = document.getElementById('seaLevelMode').value;
const material = new THREE.MeshPhysicalMaterial({
vertexColors: false,
roughness: 0.1,
metalness: 0.3,
clearcoat: 1.0,
clearcoatRoughness: 0.0,
reflectivity: 0.9,
transparent: true,
opacity: 0.9,
envMapIntensity: 1.0
});
const instancedMesh = new THREE.InstancedMesh(boxGeometry, material, instanceCount);
instancedMesh.castShadow = true;
instancedMesh.receiveShadow = true;
// Create matrix and color for each instance
const matrix = new THREE.Matrix4();
const color = new THREE.Color();
let instanceIndex = 0;
for (let j = 0; j < meshHeight; j++) {
for (let i = 0; i < meshWidth; i++) {
const dataX = Math.floor(i * actualStepX);
const dataY = Math.floor(j * actualStepY);
const dataIndex = Math.min(dataY * width + dataX, elevationData.length - 1);
let elevation = elevationData[dataIndex];
if (isNaN(elevation) || elevation === -9999) {
elevation = minElev;
}
// Calculate position (match plane geometry coordinates)
// i corresponds to X axis (width), j corresponds to Y axis (height)
// Y needs to be negated to match the PlaneGeometry orientation after rotation
// For gapless mode, position voxels based on their actual size
const x = gapless ?
(i - (meshWidth - 1) / 2) * baseVoxelSizeX :
(i / (meshWidth - 1) - 0.5) * 1000;
const y = gapless ?
-((j - (meshHeight - 1) / 2) * baseVoxelSizeY) :
-(j / (meshHeight - 1) - 0.5) * 1000;
// Normalize elevation
const normalized = (elevation - minElev) / (maxElev - minElev);
const minVoxelSize = Math.min(voxelSizeX, voxelSizeY);
const voxelHeight = Math.max(normalized * 200 * verticalExaggeration, minVoxelSize * 0.1);
const z = voxelHeight / 2; // Height is on Z axis before rotation
// Get color for this elevation
const voxelColor = getColorForElevation(normalized, elevation);
// Skip hidden sea level voxels
if (voxelColor.r === -1) {
// Set a zero-scale matrix to hide this voxel
matrix.makeScale(0, 0, 0);
matrix.setPosition(x, y, z);
instancedMesh.setMatrixAt(instanceIndex, matrix);
color.setRGB(0, 0, 0); // Set a default color
} else {
// Set normal color without modifying for transparency
color.setRGB(voxelColor.r, voxelColor.g, voxelColor.b);
// Handle transparency by scaling the voxel
let scaleModifier = 1;
if (voxelColor.a !== undefined && voxelColor.a < 1) {
// Scale down the voxel based on opacity to simulate transparency
// At 0% opacity (alpha=0), voxel is nearly invisible (scale=0.1)
// At 100% opacity (alpha=1), voxel is full size (scale=1)
scaleModifier = Math.max(0.1, voxelColor.a);
}
// Set transform matrix for this instance
matrix.makeScale(scaleModifier, scaleModifier, voxelHeight * scaleModifier);
matrix.setPosition(x, y, z);
instancedMesh.setMatrixAt(instanceIndex, matrix);
}
instancedMesh.setColorAt(instanceIndex, color);
instanceIndex++;
}
}
// Update the instance matrices
instancedMesh.instanceMatrix.needsUpdate = true;
instancedMesh.instanceColor.needsUpdate = true;
// Rotate to match terrain orientation
instancedMesh.rotation.x = -Math.PI / 2;
// Add to scene
terrain = instancedMesh;
scene.add(terrain);
}
// Get color based on elevation (0-1 normalized and actual elevation in meters)
function getColorForElevation(normalized, actualElevation = null) {