-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathearth-view.js
More file actions
1709 lines (1489 loc) · 48.5 KB
/
earth-view.js
File metadata and controls
1709 lines (1489 loc) · 48.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
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
import "./earth-view.css";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import earthTexture from "./src/img/earth.jpg";
import starsTexture from "./src/img/stars.jpg";
// Scene Setup
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000011, 1);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// Enhanced Orbit Controls
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.minDistance = 15;
controls.maxDistance = 50;
controls.autoRotate = false;
controls.autoRotateSpeed = 0.5;
// Camera positioning
camera.position.set(25, 15, 25);
controls.update();
// Sunlight Simulation System
class SunlightSimulator {
constructor() {
this.currentTime = new Date();
this.timeSpeed = 1; // 1 = real time, higher = faster
this.isRealTime = true;
this.manualTime = 12; // Manual time in hours (0-24)
this.isPaused = false; // New pause state
this.useLocalTime = true; // Use client's local timezone
this.clientTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
this.setupSun();
this.setupLighting();
this.setupAtmosphere();
this.updateTimezoneDisplay();
}
setupSun() {
// Create visible sun - STATIONARY at fixed position
const sunGeometry = new THREE.SphereGeometry(2, 32, 32);
const sunMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
});
this.sun = new THREE.Mesh(sunGeometry, sunMaterial);
// Fixed position - Sun stays here and never moves
this.sun.position.set(100, 0, 0);
scene.add(this.sun);
// Sun glow effect
const glowGeometry = new THREE.SphereGeometry(3, 32, 32);
const glowMaterial = new THREE.MeshBasicMaterial({
color: 0xffffaa,
transparent: true,
opacity: 0.3,
side: THREE.BackSide,
});
this.sunGlow = new THREE.Mesh(glowGeometry, glowMaterial);
this.sun.add(this.sunGlow);
}
setupLighting() {
// Main sunlight (directional light) - STATIONARY
this.sunLight = new THREE.DirectionalLight(0xffffff, 1.5);
this.sunLight.position.set(100, 0, 0); // Fixed position matching the sun
this.sunLight.target.position.set(0, 0, 0); // Always points to Earth center
this.sunLight.castShadow = true;
this.sunLight.shadow.mapSize.width = 4096;
this.sunLight.shadow.mapSize.height = 4096;
this.sunLight.shadow.camera.near = 0.1;
this.sunLight.shadow.camera.far = 200;
this.sunLight.shadow.camera.left = -50;
this.sunLight.shadow.camera.right = 50;
this.sunLight.shadow.camera.top = 50;
this.sunLight.shadow.camera.bottom = -50;
scene.add(this.sunLight);
scene.add(this.sunLight.target);
// Ambient light for space illumination
this.spaceAmbient = new THREE.AmbientLight(0xffffff, 0.1);
scene.add(this.spaceAmbient);
// Earth's atmospheric scattering simulation - moved farther away and reduced intensity
this.atmosphereLight = new THREE.DirectionalLight(0xffffff, 0.1); // Changed to white light
this.atmosphereLight.position.set(-150, 0, 0); // Moved much farther away (from -30 to -150)
this.atmosphereLight.target.position.set(0, 0, 0); // Always points to Earth center
this.atmosphereLight.castShadow = false; // Disable shadows for atmosphere light
scene.add(this.atmosphereLight);
scene.add(this.atmosphereLight.target);
}
setupAtmosphere() {
// Create atmosphere glow around Earth
const atmosphereGeometry = new THREE.SphereGeometry(10.5, 64, 64);
const atmosphereMaterial = new THREE.ShaderMaterial({
uniforms: {
c: { value: 0.8 },
p: { value: 6.0 },
glowColor: { value: new THREE.Color(0xffffff) }, // Changed to white glow
viewVector: { value: camera.position },
},
vertexShader: `
uniform vec3 viewVector;
uniform float c;
uniform float p;
varying float intensity;
void main() {
vec3 vNormal = normalize(normalMatrix * normal);
vec3 vNormel = normalize(normalMatrix * viewVector);
intensity = pow(c - dot(vNormal, vNormel), p);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 glowColor;
varying float intensity;
void main() {
vec3 glow = glowColor * intensity;
gl_FragColor = vec4(glow, intensity);
}
`,
side: THREE.BackSide,
blending: THREE.AdditiveBlending,
transparent: true,
});
this.atmosphere = new THREE.Mesh(
atmosphereGeometry,
atmosphereMaterial
);
earthGroup.add(this.atmosphere);
}
// Calculate Earth's rotation based on time (Sun remains stationary)
calculateEarthRotation(timeInHours) {
// Earth rotates 360° in 24 hours = 15°/hour
// We want local solar noon (12:00) to face the Sun (sun positioned on +X).
// Therefore rotation should be 0 at 12:00, and 180° at 00:00 (midnight).
// Compute degrees as (12 - hours) * 15 and convert to radians.
const hours = ((timeInHours % 24) + 24) % 24; // normalize to [0,24)
const degrees = (12 - hours) * 15; // 15° per hour, 0° at noon
const earthRotationAngle = degrees * (Math.PI / 180);
return earthRotationAngle;
}
getCurrentTime() {
if (this.isPaused) {
return this.manualTime; // Return current time when paused
}
if (this.isRealTime) {
const now = new Date();
if (this.useLocalTime) {
// Use client's local time
return (
now.getHours() +
now.getMinutes() / 60 +
now.getSeconds() / 3600
);
} else {
// Use UTC time
return (
now.getUTCHours() +
now.getUTCMinutes() / 60 +
now.getUTCSeconds() / 3600
);
}
} else {
return this.manualTime;
}
}
getCurrentDate() {
const now = new Date();
return {
date: now,
localTime: {
hours: now.getHours(),
minutes: now.getMinutes(),
seconds: now.getSeconds(),
timezone: this.clientTimezone,
offset: now.getTimezoneOffset(),
},
utcTime: {
hours: now.getUTCHours(),
minutes: now.getUTCMinutes(),
seconds: now.getUTCSeconds(),
},
};
}
updateTimezoneDisplay() {
const timezoneDisplay = document.getElementById("timezone-info");
if (timezoneDisplay) {
const offset = new Date().getTimezoneOffset();
const offsetHours = Math.floor(Math.abs(offset) / 60);
const offsetMinutes = Math.abs(offset) % 60;
const offsetSign = offset <= 0 ? "+" : "-";
timezoneDisplay.textContent = `${
this.clientTimezone
} (UTC${offsetSign}${offsetHours
.toString()
.padStart(2, "0")}:${offsetMinutes
.toString()
.padStart(2, "0")})`;
}
}
updateEarthRotation() {
const currentHour = this.getCurrentTime();
const rotationAngle = this.calculateEarthRotation(currentHour);
// Rotate Earth around its Y-axis (day/night cycle)
// Note: We're rotating the entire earthGroup which includes markers
earthGroup.rotation.y = rotationAngle;
return currentHour;
}
updateLightingIntensity(timeInHours) {
// Keep sunlight and atmosphere constant; only Earth's rotation determines day/night
this.sunLight.intensity = 1.5;
this.sunLight.color.setRGB(1, 1, 0.8); // Slightly warm white
this.atmosphere.material.uniforms.c.value = 0.8;
this.sunGlow.material.opacity = 0.35;
}
setTimeSpeed(speed) {
this.timeSpeed = speed;
}
setManualTime(hours) {
this.manualTime = hours;
this.isRealTime = false;
}
enableRealTime() {
this.isRealTime = true;
// Always sync to system time when enabling real-time
const now = new Date();
if (this.useLocalTime) {
this.manualTime =
now.getHours() +
now.getMinutes() / 60 +
now.getSeconds() / 3600;
} else {
this.manualTime =
now.getUTCHours() +
now.getUTCMinutes() / 60 +
now.getUTCSeconds() / 3600;
}
}
pauseTime() {
this.isPaused = true;
}
resumeTime() {
this.isPaused = false;
}
togglePause() {
this.isPaused = !this.isPaused;
return this.isPaused;
}
setTimeMode(useLocal) {
this.useLocalTime = useLocal;
this.updateTimezoneDisplay();
}
getFormattedTime() {
const dateInfo = this.getCurrentDate();
const currentTime = this.getCurrentTime();
const hours = Math.floor(currentTime);
const minutes = Math.floor((currentTime - hours) * 60);
const seconds = Math.floor(((currentTime - hours) * 60 - minutes) * 60);
return {
time: `${hours.toString().padStart(2, "0")}:${minutes
.toString()
.padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`,
timeOnly: `${hours.toString().padStart(2, "0")}:${minutes
.toString()
.padStart(2, "0")}`,
timezone: this.useLocalTime ? dateInfo.localTime.timezone : "UTC",
date: dateInfo.date.toLocaleDateString(),
isLocal: this.useLocalTime,
};
}
animate() {
if (!this.isPaused && !this.isRealTime) {
// Advance manual time only when not paused
this.manualTime += this.timeSpeed * 0.001; // Adjust speed
if (this.manualTime >= 24) this.manualTime = 0;
}
const currentTime = this.updateEarthRotation();
this.updateLightingIntensity(currentTime);
// Update atmosphere shader uniforms
this.atmosphere.material.uniforms.viewVector.value = camera.position;
return currentTime;
}
}
// User Timezone Marker System
class UserTimezoneMarker {
constructor() {
this.userMarker = null;
this.userLabel = null;
this.isVisible = true;
this.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
this.createUserMarker();
this.setupEventListeners();
}
// Get approximate coordinates for timezone (simplified mapping)
getTimezoneCoordinates(timezone) {
// Major timezone to coordinates mapping (approximate)
const timezoneMap = {
// Americas
"America/New_York": { lat: 40.7128, lon: -74.006 },
"America/Los_Angeles": { lat: 34.0522, lon: -118.2437 },
"America/Chicago": { lat: 41.8781, lon: -87.6298 },
"America/Denver": { lat: 39.7392, lon: -104.9903 },
"America/Toronto": { lat: 43.6532, lon: -79.3832 },
"America/Mexico_City": { lat: 19.4326, lon: -99.1332 },
"America/Sao_Paulo": { lat: -23.5505, lon: -46.6333 },
"America/Buenos_Aires": { lat: -34.6118, lon: -58.396 },
// Europe
"Europe/London": { lat: 51.5074, lon: -0.1278 },
"Europe/Paris": { lat: 48.8566, lon: 2.3522 },
"Europe/Berlin": { lat: 52.52, lon: 13.405 },
"Europe/Rome": { lat: 41.9028, lon: 12.4964 },
"Europe/Madrid": { lat: 40.4168, lon: -3.7038 },
"Europe/Amsterdam": { lat: 52.3676, lon: 4.9041 },
"Europe/Stockholm": { lat: 59.3293, lon: 18.0686 },
"Europe/Moscow": { lat: 55.7558, lon: 37.6176 },
// Asia
"Asia/Tokyo": { lat: 35.6762, lon: 139.6503 },
"Asia/Shanghai": { lat: 31.2304, lon: 121.4737 },
"Asia/Hong_Kong": { lat: 22.3193, lon: 114.1694 },
"Asia/Singapore": { lat: 1.3521, lon: 103.8198 },
"Asia/Mumbai": { lat: 19.076, lon: 72.8777 },
"Asia/Dubai": { lat: 25.2048, lon: 55.2708 },
"Asia/Seoul": { lat: 37.5665, lon: 126.978 },
"Asia/Bangkok": { lat: 13.7563, lon: 100.5018 },
// Oceania
"Australia/Sydney": { lat: -33.8688, lon: 151.2093 },
"Australia/Melbourne": { lat: -37.8136, lon: 144.9631 },
"Pacific/Auckland": { lat: -36.8485, lon: 174.7633 },
// Africa
"Africa/Cairo": { lat: 30.0444, lon: 31.2357 },
"Africa/Johannesburg": { lat: -26.2041, lon: 28.0473 },
"Africa/Lagos": { lat: 6.5244, lon: 3.3792 },
};
// Return coordinates if found, otherwise estimate from timezone offset
if (timezoneMap[timezone]) {
return timezoneMap[timezone];
}
// Fallback: estimate longitude from timezone offset
const offset = new Date().getTimezoneOffset() / 60; // Hours from UTC
const estimatedLon = -offset * 15; // 15 degrees per hour
return { lat: 0, lon: estimatedLon }; // Place on equator
}
// Convert latitude/longitude to 3D coordinates on sphere
latLonToVector3(lat, lon, radius) {
const phi = (90 - lat) * (Math.PI / 180);
const theta = (lon + 180) * (Math.PI / 180);
const x = -(radius * Math.sin(phi) * Math.cos(theta));
const z = radius * Math.sin(phi) * Math.sin(theta);
const y = radius * Math.cos(phi);
return new THREE.Vector3(x, y, z);
}
createUserMarker() {
const coords = this.getTimezoneCoordinates(this.timezone);
const earthRadius = 10;
// Create distinctive user marker (smaller)
const markerGroup = new THREE.Group();
// Main marker - smaller and unobtrusive
const markerGeometry = new THREE.SphereGeometry(0.35, 12, 12);
const markerMaterial = new THREE.MeshPhongMaterial({
color: 0x00ff00, // Bright green for user location
transparent: true,
opacity: 0.9,
});
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
// Pulsing ring effect (smaller)
const ringGeometry = new THREE.RingGeometry(0.6, 1.0, 32);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0x00ff00,
transparent: true,
opacity: 0.35,
side: THREE.DoubleSide,
});
const ring = new THREE.Mesh(ringGeometry, ringMaterial);
ring.lookAt(camera.position); // Face the camera
// Vertical beam effect (shorter)
const beamGeometry = new THREE.CylinderGeometry(0.06, 0.06, 7.5, 8);
const beamMaterial = new THREE.MeshBasicMaterial({
color: 0x00ff00,
transparent: true,
opacity: 0.28,
});
const beam = new THREE.Mesh(beamGeometry, beamMaterial);
beam.position.y = 3.75; // Extend upward from surface
markerGroup.add(marker);
markerGroup.add(ring);
markerGroup.add(beam);
// Position on Earth surface (slightly closer)
const position = this.latLonToVector3(
coords.lat,
coords.lon,
earthRadius + 0.45
);
markerGroup.position.copy(position);
// Store references for animation
markerGroup.userData = {
ring: ring,
beam: beam,
marker: marker,
coords: coords,
phase: 0,
};
earthGroup.add(markerGroup);
this.userMarker = markerGroup;
// Create label
this.createUserLabel(coords);
console.log(
`User timezone marker created for ${this.timezone} at ${coords.lat}, ${coords.lon}`
);
}
createUserLabel(coords) {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = 220;
canvas.height = 56;
// Background (smaller)
context.fillStyle = "rgba(0, 100, 0, 0.85)";
context.fillRect(0, 0, canvas.width, canvas.height);
// Border
context.strokeStyle = "#00ff00";
context.lineWidth = 2;
context.strokeRect(0, 0, canvas.width, canvas.height);
// Text (smaller font)
context.fillStyle = "#ffffff";
context.font = "bold 14px Arial";
context.textAlign = "center";
context.fillText("📍 Your Location", canvas.width / 2, 22);
context.font = "11px Arial";
context.fillText(this.timezone, canvas.width / 2, 38);
context.fillText(
`${coords.lat.toFixed(1)}°, ${coords.lon.toFixed(1)}°`,
canvas.width / 2,
50
);
const texture = new THREE.CanvasTexture(canvas);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
});
const sprite = new THREE.Sprite(material);
const position = this.latLonToVector3(coords.lat, coords.lon, 10);
sprite.position.copy(position);
sprite.position.multiplyScalar(1.3);
sprite.scale.set(3.2, 1.2, 1);
earthGroup.add(sprite);
this.userLabel = sprite;
}
setupEventListeners() {
// Add toggle button listener when DOM is ready
document.addEventListener("DOMContentLoaded", () => {
const toggleBtn = document.getElementById("toggle-user-marker");
if (toggleBtn) {
toggleBtn.addEventListener("click", () => {
this.toggleVisibility();
});
}
});
}
toggleVisibility() {
this.isVisible = !this.isVisible;
if (this.userMarker) {
this.userMarker.visible = this.isVisible;
}
if (this.userLabel) {
this.userLabel.visible = this.isVisible;
}
const toggleBtn = document.getElementById("toggle-user-marker");
if (toggleBtn) {
toggleBtn.textContent = this.isVisible
? "👤 Hide My Location"
: "👤 Show My Location";
toggleBtn.classList.toggle("active", this.isVisible);
}
}
animate() {
if (!this.userMarker || !this.isVisible) return;
const time = Date.now() * 0.001;
const userData = this.userMarker.userData;
// Pulsing ring animation
const pulseScale = 1 + 0.3 * Math.sin(time * 2);
userData.ring.scale.setScalar(pulseScale);
userData.ring.material.opacity = 0.2 + 0.3 * Math.sin(time * 2);
// Beam opacity animation
userData.beam.material.opacity = 0.1 + 0.2 * Math.sin(time * 1.5);
// Keep ring facing camera
userData.ring.lookAt(camera.position);
}
}
// Earth Creation
const textureLoader = new THREE.TextureLoader();
const earthGeometry = new THREE.SphereGeometry(10, 64, 64);
const earthMaterial = new THREE.MeshPhongMaterial({
map: textureLoader.load(earthTexture),
shininess: 100,
transparent: false,
opacity: 1.0,
});
const earth = new THREE.Mesh(earthGeometry, earthMaterial);
earth.castShadow = true;
earth.receiveShadow = true;
// Create Earth group to hold both the planet and markers
const earthGroup = new THREE.Group();
earthGroup.add(earth);
scene.add(earthGroup);
// Initialize sunlight simulator after earthGroup is created
const sunlightSim = new SunlightSimulator();
// Star Field Background with image texture
function createStarField() {
// Use the imported stars texture
const starsTextureMap = textureLoader.load(starsTexture);
// Create a large sphere with inside faces
const starsGeometry = new THREE.SphereGeometry(900, 64, 64);
const starsMaterial = new THREE.MeshBasicMaterial({
map: starsTextureMap,
side: THREE.BackSide, // Show inside of sphere
});
// Create mesh and add to scene
const stars = new THREE.Mesh(starsGeometry, starsMaterial);
scene.add(stars);
// Also add some particle stars for additional depth
const starsPointsGeometry = new THREE.BufferGeometry();
const starsPointsMaterial = new THREE.PointsMaterial({
color: 0xffffff,
size: 1.5,
sizeAttenuation: false,
});
const starsVertices = [];
for (let i = 0; i < 3000; i++) {
const x = (Math.random() - 0.5) * 2000;
const y = (Math.random() - 0.5) * 2000;
const z = (Math.random() - 0.5) * 2000;
starsVertices.push(x, y, z);
}
starsPointsGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(starsVertices, 3)
);
const starsPoints = new THREE.Points(
starsPointsGeometry,
starsPointsMaterial
);
scene.add(starsPoints);
}
// Initialize user timezone marker
const userLocationMarker = new UserTimezoneMarker();
// Create the star field after everything else is initialized
createStarField();
// EONET Categories Data
const eonetCategories = {
title: "EONET Event Categories",
description:
"List of all the available event categories in the EONET system",
categories: [
{
id: 6,
title: "Drought",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/6",
description:
"Long lasting absence of precipitation affecting agriculture and livestock, and the overall availability of food and water.",
color: 0x8b4513,
size: 0.5,
emoji: "🏜️",
},
{
id: 7,
title: "Dust and Haze",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/7",
description:
"Related to dust storms, air pollution and other non-volcanic aerosols. Volcano-related plumes shall be included with the originating eruption event.",
color: 0xffd700,
size: 0.6,
emoji: "🌫️",
},
{
id: 16,
title: "Earthquakes",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/16",
description:
"Related to all manner of shaking and displacement. Certain aftermath of earthquakes may also be found under landslides and floods.",
color: 0x8b4513,
size: 0.6,
emoji: "🌋",
},
{
id: 9,
title: "Floods",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/9",
description:
"Related to aspects of actual flooding--e.g., inundation, water extending beyond river and lake extents.",
color: 0x0080ff,
size: 0.7,
emoji: "🌊",
},
{
id: 14,
title: "Landslides",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/14",
description:
"Related to landslides and variations thereof: mudslides, avalanche.",
color: 0x654321,
size: 0.6,
emoji: "⛰️",
},
{
id: 19,
title: "Manmade",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/19",
description:
"Events that have been human-induced and are extreme in their extent.",
color: 0xff69b4,
size: 0.5,
emoji: "🏭",
},
{
id: 15,
title: "Sea and Lake Ice",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/15",
description:
"Related to all ice that resides on oceans and lakes, including sea and lake ice (permanent and seasonal) and icebergs.",
color: 0x87ceeb,
size: 0.4,
emoji: "❄️",
},
{
id: 10,
title: "Severe Storms",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/10",
description:
"Related to the atmospheric aspect of storms (hurricanes, cyclones, tornadoes, etc.). Results of storms may be included under floods, landslides, etc.",
color: 0xffff00,
size: 0.8,
emoji: "🌪️",
},
{
id: 17,
title: "Snow",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/17",
description:
"Related to snow events, particularly extreme/anomalous snowfall in either timing or extent/depth.",
color: 0xffffff,
size: 0.4,
emoji: "❄️",
},
{
id: 18,
title: "Temperature Extremes",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/18",
description:
"Related to anomalous land temperatures, either heat or cold.",
color: 0xff6347,
size: 0.5,
emoji: "🔥",
},
{
id: 12,
title: "Volcanoes",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/12",
description:
"Related to both the physical effects of an eruption (rock, ash, lava) and the atmospheric (ash and gas plumes).",
color: 0xff0000,
size: 1.0,
emoji: "🌋",
},
{
id: 13,
title: "Water Color",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/13",
description:
"Related to events that alter the appearance of water: phytoplankton, red tide, algae, sediment, whiting, etc.",
color: 0x00ffff,
size: 0.5,
emoji: "🌊",
},
{
id: 8,
title: "Wildfires",
link: "https://eonet.gsfc.nasa.gov/api/v2.1/categories/8",
description:
"Wildland fires includes all nature of fire, in forest and plains, as well as those that spread to become urban and industrial fire events. Fires may be naturally caused or manmade.",
color: 0xff4500,
size: 0.8,
emoji: "🔥",
},
],
};
// Helper function to get category by ID
function getCategoryById(categoryId) {
return eonetCategories.categories.find(
(category) => category.id === categoryId
);
}
// Helper function to get category key from title
function getCategoryKey(title) {
// Convert category title to a key (e.g. "Wildfires" -> "wildfires")
const map = {
Wildfires: "wildfires",
Volcanoes: "volcanoes",
Earthquakes: "earthquakes",
Floods: "floods",
"Severe Storms": "storms",
Drought: "droughts",
"Dust and Haze": "dustHaze",
"Sea and Lake Ice": "seaLakeIce",
Snow: "snow",
Landslides: "landslides",
Manmade: "manmade",
"Temperature Extremes": "tempExtremes",
"Water Color": "waterColor",
};
return map[title] || title.toLowerCase().replace(/\s+/g, "");
}
// Create category color map
const categoryMap = {};
eonetCategories.categories.forEach((category) => {
const key = getCategoryKey(category.title);
categoryMap[key] = {
id: category.id,
title: category.title,
color: category.color,
size: category.size,
description: category.description,
link: category.link,
emoji: category.emoji || "📍",
};
});
// Enhanced EONET Data Overlay for Earth View
class EarthViewEONET {
constructor() {
this.events = [];
this.markers = [];
this.labels = [];
this.categories = eonetCategories.categories;
this.eventTypes = this.initEventTypesFromCategories();
this.animationSpeed = 1;
this.markerSize = 0.5;
this.showLabels = true;
this.selectedMarker = null;
this.eventLimit = 200; // Default limit of events to display
this.setupEventListeners();
this.setupFilterButtons();
this.createLegend();
this.fetchData();
}
initEventTypesFromCategories() {
const eventTypes = {};
this.categories.forEach((category) => {
const key = getCategoryKey(category.title);
eventTypes[key] = {
id: category.id,
title: category.title,
color: category.color || 0xcccccc,
size: category.size || 0.5,
description: category.description,
link: category.link,
emoji: category.emoji || "📍",
glow: this.calculateGlowColor(category.color || 0xcccccc),
};
});
return eventTypes;
}
calculateGlowColor(baseColor) {
// Calculate a slightly brighter version of the base color for the glow
const color = new THREE.Color(baseColor);
color.r = Math.min(1, color.r * 1.3);
color.g = Math.min(1, color.g * 1.3);
color.b = Math.min(1, color.b * 1.3);
return color.getHex();
}
setupFilterButtons() {
const filterContainer = document.querySelector(".filter-buttons");
if (!filterContainer) return;
// Clear existing buttons
filterContainer.innerHTML = "";
// Add "All Events" button
const allButton = document.createElement("button");
allButton.id = "filter-all";
allButton.className = "filter-btn active";
allButton.textContent = "All Events";
filterContainer.appendChild(allButton);
// Add a button for each category
this.categories.forEach((category) => {
const button = document.createElement("button");
const key = getCategoryKey(category.title);
button.id = `filter-${key}`;
button.className = "filter-btn";
button.textContent = category.title;
// Set button background color to match category
const color = new THREE.Color(category.color || 0xcccccc);
const r = Math.floor(color.r * 255);
const g = Math.floor(color.g * 255);
const b = Math.floor(color.b * 255);
button.style.backgroundColor = `rgba(${r}, ${g}, ${b}, 0.7)`;
// Set text color (white or black) based on background brightness
const brightness = (r * 299 + g * 587 + b * 114) / 1000;
button.style.color = brightness > 128 ? "#000" : "#fff";
filterContainer.appendChild(button);
});
}
createLegend() {
const legendContainer = document.querySelector(".legend");
if (!legendContainer) return;
// Clear existing legend
legendContainer.innerHTML = "<h4>🏷️ Event Types</h4>";
// Add a legend item for each category
this.categories.forEach((category) => {
const item = document.createElement("div");
item.className = "legend-item";
const color = new THREE.Color(category.color || 0xcccccc);
const r = Math.floor(color.r * 255);
const g = Math.floor(color.g * 255);
const b = Math.floor(color.b * 255);
item.innerHTML = `
<span class="legend-color" style="background-color: rgb(${r}, ${g}, ${b})"></span>
<span class="legend-text">${category.title}</span>
`;
legendContainer.appendChild(item);
});
}
setupEventListeners() {
// Marker size control
document
.getElementById("marker-size")
.addEventListener("input", (e) => {
this.markerSize = parseFloat(e.target.value);
this.updateMarkerSizes();
});
// Animation speed control
document
.getElementById("animation-speed")
.addEventListener("input", (e) => {
this.animationSpeed = parseFloat(e.target.value);
});
// Show labels toggle
document
.getElementById("show-labels")
.addEventListener("change", (e) => {
this.showLabels = e.target.checked;
this.toggleLabels();
});
// Event limit control
document
.getElementById("event-limit")
.addEventListener("input", (e) => {
this.eventLimit = parseInt(e.target.value);
document.getElementById("event-limit-value").textContent =
this.eventLimit;
});
// Refresh data button
document
.getElementById("refresh-data")
.addEventListener("click", () => {
this.fetchData();
});
// Auto rotate toggle
document
.getElementById("auto-rotate-btn")
.addEventListener("click", () => {
controls.autoRotate = !controls.autoRotate;
const btn = document.getElementById("auto-rotate-btn");
btn.textContent = controls.autoRotate
? "⏸️ Stop Rotate"
: "🔄 Auto Rotate";
});
// Mouse interaction for marker selection
this.setupMouseInteraction();
}
setupMouseInteraction() {
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
renderer.domElement.addEventListener("click", (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);