-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2432 lines (2091 loc) · 104 KB
/
app.js
File metadata and controls
2432 lines (2091 loc) · 104 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
// app.js
// Import components
import { addAnimatedModel } from './components/addAnimatedModel.js';
import { addConnectorPolyline } from './components/addConnectorPolyline.js';
// Grant CesiumJS access to your ion assets
Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxODFlMzg1MS0yNjNiLTQ2NjQtYjdlNC1jN2RiZjhjMGZiOWQiLCJpZCI6MjkzOTkzLCJpYXQiOjE3NDQ2Mzc2MTF9.hO0qmOtSNBv-buxwOBkgZ6XKPyNk_TQdhhYnohE_Y-A";
// --- Global variables ---
let viewer;
let mediaRecorder;
let recordedChunks = [];
let recordingActive = false;
let legendTitleElement; // Variable to hold the legend title DOM element
let appTitleElement;
// -----------------------------------
// Selectable options
// -----------------------------------
let addSuitabilityLayers = true;
let addGasPipelines = true;
let addTransmissionLines = true;
let addPowerPlantLayers = true;
let addBuffer = true;
// true = smooth camera fly; false = instant jump with fade
let useCameraFly = true;
// Time delay after a suitability layer is added
let suitabilityDelayMs = 2000; // 2000
let pipelineWaitMs = 2500; // 2500
let transmissionlineWaitMs = 2500; // 2500
// --- UI Elements (Grabbed once) ---
const legendDiv = document.getElementById('legendDiv');
const primaryLegendItemsContainer = document.getElementById('primaryLegendItemsContainer');
const pitchSlider = document.getElementById("pitchSlider");
const headingSlider = document.getElementById("headingSlider");
const pitchValue = document.getElementById("pitchValue");
const headingValue = document.getElementById("headingValue");
const sequenceButton = document.getElementById("sequenceButton");
// Intro popup shown until Run Sequence clicked
const introPopup = document.createElement('div');
introPopup.id = 'introPopup';
introPopup.innerHTML = `
<h1 style="margin:0; font-weight:bold; font-size:24px; color:white;">
Projected locations of new natural gas combined cycle power plants (with recirculating cooling) in Wyoming, USA (2020-2050)
</h1>
</br>
<p style="margin:8px 0 0; font-weight:400; font-size:18px; color:rgba(255,255,255,0.8);">
This visualization uses results from CERF: Capacity Expansion Regional Feasibility model, https://immm-sfa.github.io/cerf/
</p>
`;
introPopup.style.cssText = `
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(40, 40, 40, 0.8);
border: 2px solid #333;
border-radius: 12px;
padding: 40px 60px;
width: 350px;
text-align: center;
z-index: 1000;
`;
// Append popup inside the Cesium container so it centers over the map
const cesiumContainer = document.getElementById('cesiumContainer');
cesiumContainer.style.position = cesiumContainer.style.position || 'relative';
cesiumContainer.appendChild(introPopup);
// --- Legend Management ---
const legendItems = {}; // Keep track of legend items by id
// Options for suitability polygons
const polygonOptions = {
stroke: Cesium.Color.BLACK,
fill: Cesium.Color.BLACK.withAlpha(1.0),
strokeWidth: 3,
clampToGround: true,
height: 0,
};
// Prepare a full‑screen black DIV for fades
const fadeDiv = document.createElement('div');
fadeDiv.style.cssText = `
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: black;
pointer-events: none;
opacity: 0;
transition: opacity 0.6s ease-in-out;
z-index: 999;
`;
document.body.appendChild(fadeDiv);
/**
* Fade out, jump camera, then fade back in.
* @returns {Promise}
*/
function fadeTransitionTo(viewerInstance, lon, lat, height, heading, pitch, durationMs = 1000) {
return new Promise(resolve => {
// 1. Prepare blur overlay fade‑in
// ensure no black background
fadeDiv.style.background = 'transparent';
// animate both opacity and blur amount
fadeDiv.style.transition = `opacity ${durationMs}ms ease-in-out, backdrop-filter ${durationMs}ms ease-in-out, -webkit-backdrop-filter ${durationMs}ms ease-in-out`;
// set the blur radius you want (e.g., 8px)
fadeDiv.style.backdropFilter = 'blur(8px)';
fadeDiv.style.webkitBackdropFilter = 'blur(8px)';
// fade overlay in (so it applies the blur)
fadeDiv.style.opacity = 1;
// wait for the blur‑in to finish
setTimeout(() => {
// 2. Jump camera instantly
viewerInstance.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, height),
orientation: {
heading: Cesium.Math.toRadians(heading),
pitch: Cesium.Math.toRadians(pitch),
roll: 0.0
}
});
// 3. Fade overlay out (remove blur)
fadeDiv.style.backdropFilter = 'blur(0px)';
fadeDiv.style.webkitBackdropFilter = 'blur(0px)';
fadeDiv.style.opacity = 0;
// 4. Resolve after blur‑out transition is done
setTimeout(resolve, durationMs);
}, durationMs);
});
}
/**
* Adds an item to the legend.
* @param {string} id - Unique ID for the legend item.
* @param {string} title - Text label for the item.
* @param {string} symbolHtml - HTML string for the symbol (e.g., colored div, img tag).
* @param {boolean} [clearPreviousItems=false] - If true, clear existing items before adding this one (subject to exclusions).
* @param {string[]} [excludeFromClearIds=[]] - An array of item IDs to *keep* if clearPreviousItems is true.
*/
function addLegendItem(id, title, symbolHtml, clearPreviousItems = false, excludeFromClearIds = []) { // Added exclude parameter
// --- Clearing Logic ---
if (clearPreviousItems) {
const allCurrentIds = Object.keys(legendItems); // Get IDs currently in the legend
allCurrentIds.forEach(existingId => {
// Check if the current existing item's ID is in the exclusion list
if (!excludeFromClearIds.includes(existingId)) {
// If it's NOT excluded, remove it
removeLegendItem(existingId);
}
// If it IS in the exclusion list, do nothing (keep it)
});
}
// Only add if it doesn't already exist (or handle update logic if needed)
if (!legendItems[id]) {
const item = document.createElement('div');
// Sanitize ID for DOM: replace non-alphanumeric chars with '-'
const domId = `legend-item-${id.replace(/[^a-zA-Z0-9\-_]/g, '-')}`;
item.id = domId;
// Ensure symbolHtml is treated as HTML, and title is treated as text
item.innerHTML = `${symbolHtml} <span></span>`;
item.querySelector('span').textContent = title; // Safer way to set text
primaryLegendItemsContainer.appendChild(item);
legendItems[id] = item; // Track the added item
} else {
// Optional: What to do if item with same ID already exists?
// console.log(`Legend item ${id} already exists.`);
// You could potentially update its title/symbol here if necessary.
}
}
function removeLegendItem(id) {
const domId = `legend-item-${id.replace(/[^a-zA-Z0-9\-_]/g, '-')}`;
const itemElement = document.getElementById(domId);
if (itemElement) {
itemElement.parentNode.removeChild(itemElement);
delete legendItems[id];
}
}
// Helper function to clear specific legend items
function clearSpecificLegendItems(idsToRemove) {
console.log("Clearing specific legend items:", idsToRemove);
idsToRemove.forEach(id => {
removeLegendItem(id);
});
}
// Optional: Function to clear ALL sequence graphics AND legend items
function clearSequenceGraphics(viewerInstance) {
if (!viewerInstance) return;
console.log("Clearing sequence graphics and ALL legend items...");
// Clear all legend items currently tracked
const allLegendIds = Object.keys(legendItems);
// Remove DataSources (update with ALL relevant IDs used in your sequence)
const layerIds = [
// Suitability Layers
'id_suitability0',
'id_suitability1',
'id_suitability2',
'id_suitability3',
'id_suitability4',
'id_suitability5',
'id_suitability6',
'id_suitability7',
'id_suitability8',
'id_suitability9',
'id_suitability10',
'id_suitability11',
'id_suitability12',
'id_suitability13',
'id_suitability14',
// Power Plant Layers (Add all years used)
'2030_gas_plants_clipped',
'2035_gas_plants_clipped',
'2040_gas_plants_clipped',
'2045_gas_plants_clipped',
'2050_gas_plants_clipped'
// Add any other layer IDs that might be loaded in the sequence
];
layerIds.forEach(id => {
const dsCollection = viewerInstance.dataSources.getByName(id);
if (dsCollection.length > 0) {
dsCollection.forEach(ds => viewerInstance.dataSources.remove(ds, true)); // Remove all with that name
console.log(`Removed DataSource(s) with name: ${id}`);
} else {
// console.log(`No DataSource found with name: ${id}`); // Optional log
}
});
}
// Materials functions
const pulsatingGlowMaterial = new Cesium.PolylineGlowMaterialProperty({
glowPower: new Cesium.CallbackProperty(function(time, result) {
// Use performance.now() for continuous time base, independent of Cesium clock state
const seconds = performance.now() / 1000.0;
const minGlow = 0.2;
const maxGlow = 1.0; // Max glow from your example
// Adjust frequency (e.g., * Math.PI * 2 makes it cycle every 1 second)
const oscillation = (Math.sin(seconds * Math.PI * 2) + 1) / 2; // Map sin (-1 to 1) -> (0 to 1)
return minGlow + oscillation * (maxGlow - minGlow);
}, false), // isConstant = false -> evaluate every frame
taperPower: 1.0, // Consistent glow power along the line
color: Cesium.Color.RED.withAlpha(0.7) // Color from your example
});
// Pulsating aqua glow for pipeline connector
const pulsatingGlowMaterialAqua = new Cesium.PolylineGlowMaterialProperty({
glowPower: new Cesium.CallbackProperty(function(time, result) {
const seconds = performance.now() / 2500.0;
const minGlow = 0.4;
const maxGlow = 0.8;
const oscillation = (Math.sin(seconds * Math.PI * 2) + 1) / 2;
return minGlow + oscillation * (maxGlow - minGlow);
}, false),
taperPower: 1.0,
color: Cesium.Color.AQUA.withAlpha(0.7)
});
const pulsatingGlowMaterialPurple = new Cesium.PolylineGlowMaterialProperty({
glowPower: new Cesium.CallbackProperty(function(time, result) {
// Use performance.now() for continuous time base, independent of Cesium clock state
const seconds = performance.now() / 2000.0;
const minGlow = 0.4;
const maxGlow = 1.0; // Max glow from your example
// Adjust frequency (e.g., * Math.PI * 2 makes it cycle every 1 second)
const oscillation = (Math.sin(seconds * Math.PI * 2) + 1) / 2; // Map sin (-1 to 1) -> (0 to 1)
return minGlow + oscillation * (maxGlow - minGlow);
}, false), // isConstant = false -> evaluate every frame
taperPower: 1.0, // Consistent glow power along the line
color: Cesium.Color.fromCssColorString('#5D3A9B').withAlpha(0.7) // Custom purple color
});
const pulsatingGlowMaterialSlow = new Cesium.PolylineGlowMaterialProperty({
glowPower: new Cesium.CallbackProperty(function(time, result) {
// Use performance.now() for continuous time base, independent of Cesium clock state
const seconds = performance.now() / 2500.0;
const minGlow = 0.2;
const maxGlow = 0.6; // Max glow from your example
// Adjust frequency (e.g., * Math.PI * 2 makes it cycle every 1 second)
const oscillation = (Math.sin(seconds * Math.PI * 2) + 1) / 2; // Map sin (-1 to 1) -> (0 to 1)
return minGlow + oscillation * (maxGlow - minGlow);
}, false), // isConstant = false -> evaluate every frame
taperPower: 1.0, // Consistent glow power along the line
color: Cesium.Color.RED.withAlpha(0.7) // Color from your example
});
// --- Core CesiumJS Initialization (Async Function) ---
async function startCesium() {
try {
// console.log("Initializing Cesium Viewer...");
viewer = new Cesium.Viewer('cesiumContainer', {
// Use Cesium World Terrain via Ion Asset ID (Asset 1) - ENABLED
terrainProvider: await Cesium.CesiumTerrainProvider.fromIonAssetId(1),
// Use high-res satellite imagery from Esri by default
imageryProvider: new Cesium.ArcGisMapServerImageryProvider({
url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
}),
animation: false,
fullscreenButton: false, // Keep false or true based on preference
geocoder: false, // Keep false or true based on preference
homeButton: false, // Keep false or true based on preference
infoBox: true, // Usually useful, keep true unless specifically not needed
sceneModePicker: false, // Usually false for focused apps
selectionIndicator: true, // Usually useful, keep true
timeline: false, // Keep false unless time-dynamic data is used
navigationHelpButton: false, // Keep false or true based on preference
});
// Hide the default Cesium credit/attribution bar
viewer.cesiumWidget.creditContainer.style.display = 'none';
// ---------------------------------------------
// SET INITIAL VIEW
// ---------------------------------------------
// Initial view on load
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(-99.0, 40.0, 4_000_000),
orientation: {
heading : Cesium.Math.toRadians( 0.0),
pitch : Cesium.Math.toRadians(-90.0),
roll : 0.15
}
});
// ---------------------------------------------
// 3D POWER PLANT MODEL
// ---------------------------------------------
// Define the configuration for the animated model sequence.
const constructPowerPlant = {
model: {
lon: -110.55166, // Model longitude
lat: 41.31584, // Model latitude
uris: [ // Array of model URIs (stages of construction)
'./data/models/gas_plant_v3.glb'
],
entityBaseId: 'powerPlantModel-main', // Base ID for all model entities
name: 'Gas Power Plant Model', // Base display name
scale: 2, // Model scale
minimumPixelSize: 64, // Minimum pixel size
maximumScale: 20000, // Maximum scale
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // Ensure the model is clamped to the terrain
visible: false, // Return the model completely transparent if false
},
camera: {
flyTo: false, // Enable camera flight to the model's location
},
animation: {
delayForBuild: 0, // controls the time lag for the model to be build before adding color - prevents flashing
delayBetweenStages: 0 // Delay (ms) before starting the next model addition
},
legend: {
update: false, // Flag to update the legend title during this phase
},
cleanup: {
removePrevious: false // Remove previously added entities matching the entityBaseId before adding new ones
}
};
// Call the modular function to add and animate the model(s)
addAnimatedModel(viewer, constructPowerPlant);
// ---------------------------------------------
// 3D TRANSMISSION TOWERS
// ---------------------------------------------
// Define the configuration for the animated model sequence.
const buildTransmissionTower = {
model: {
lon: -110.553592, // Model longitude
lat: 41.305885, // Model latitude
uris: [ // Array of model URIs (stages of construction)
'./data/models/transmission_tower.glb'
],
entityBaseId: 'transmissionTower', // Base ID for all model entities
name: 'Transmission Tower', // Base display name
scale: 2, // Model scale
minimumPixelSize: 64, // Minimum pixel size
maximumScale: 20000, // Maximum scale
rotation: 45, // Rotation of the model
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // Ensure the model is clamped to the terrain
visible: false, // Return the model completely transparent if false
},
camera: {
flyTo: false, // Enable camera flight to the model's location
},
animation: {
delayForBuild: 0, // controls the time lag for the model to be build before adding color - prevents flashing
delayBetweenStages: 0 // Delay (ms) before starting the next model addition
},
legend: {
update: false, // Flag to update the legend title during this phase
},
cleanup: {
removePrevious: false // Remove previously added entities matching the entityBaseId before adding new ones
}
};
addAnimatedModel(viewer, buildTransmissionTower);
// Define the configuration for the animated model sequence.
const buildTransmissionTowerTwo = {
model: {
lon: -110.545374, // Model longitude
lat: 41.309198, // Model latitude
uris: [ // Array of model URIs (stages of construction)
'./data/models/transmission_tower.glb'
],
entityBaseId: 'transmissionTowerTwo', // Base ID for all model entities
name: 'Transmission Tower', // Base display name
scale: 2, // Model scale
minimumPixelSize: 64, // Minimum pixel size
maximumScale: 20000, // Maximum scale
rotation: 45, // Rotation of the model
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // Ensure the model is clamped to the terrain
visible: false, // Return the model completely transparent if false
},
camera: {
flyTo: false, // Enable camera flight to the model's location
},
animation: {
delayForBuild: 0, // controls the time lag for the model to be build before adding color - prevents flashing
delayBetweenStages: 0 // Delay (ms) before starting the next model addition
},
legend: {
update: false, // Flag to update the legend title during this phase
},
cleanup: {
removePrevious: false // Remove previously added entities matching the entityBaseId before adding new ones
}
};
addAnimatedModel(viewer, buildTransmissionTowerTwo);
// Define the configuration for the animated model sequence.
const buildTransmissionTowerThree = {
model: {
lon: -110.525461, // Model longitude
lat: 41.309241, // Model latitude
uris: [ // Array of model URIs (stages of construction)
'./data/models/transmission_tower.glb'
],
entityBaseId: 'transmissionTowerThree', // Base ID for all model entities
name: 'Transmission Tower', // Base display name
scale: 2.1, // Model scale
minimumPixelSize: 64, // Minimum pixel size
maximumScale: 20000, // Maximum scale
rotation: 45, // Rotation of the model
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // Ensure the model is clamped to the terrain
visible: false, // Return the model completely transparent if false
},
camera: {
flyTo: false, // Enable camera flight to the model's location
},
animation: {
delayForBuild: 0, // controls the time lag for the model to be build before adding color - prevents flashing
delayBetweenStages: 0 // Delay (ms) before starting the next model addition
},
legend: {
update: false, // Flag to update the legend title during this phase
},
cleanup: {
removePrevious: false // Remove previously added entities matching the entityBaseId before adding new ones
}
};
addAnimatedModel(viewer, buildTransmissionTowerThree);
// ---------------------------------------------
// SETUP LISTENER
// ---------------------------------------------
// console.log("Cesium Viewer initialized successfully.");
// Add this code after your Cesium initialization, e.g., at the end of your app.js file.
viewer.scene.preRender.addEventListener(() => {
if (!viewer || !viewer.camera || !viewer.camera.positionCartographic) return;
const camera = viewer.camera;
const position = camera.positionCartographic;
// Update Pitch and Heading from their current values
const currentPitch = Cesium.Math.toDegrees(camera.pitch);
const currentHeading = Cesium.Math.toDegrees(camera.heading);
const normalizedHeading = (currentHeading % 360 + 360) % 360;
// Update the UI elements directly
document.getElementById("pitchValue").textContent = Math.round(currentPitch);
document.getElementById("headingValue").textContent = Math.round(normalizedHeading);
// Update the Height display (meters)
const currentHeight = Math.round(position.height);
document.getElementById("heightValue").textContent = currentHeight;
// Update the center coordinates of the view
const canvas = viewer.canvas;
const centerScreen = new Cesium.Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2);
const centerCartesian = viewer.scene.camera.pickEllipsoid(centerScreen, Cesium.Ellipsoid.WGS84);
if (centerCartesian) {
const centerCarto = Cesium.Cartographic.fromCartesian(centerCartesian);
const centerLatDegrees = Cesium.Math.toDegrees(centerCarto.latitude).toFixed(6);
const centerLonDegrees = Cesium.Math.toDegrees(centerCarto.longitude).toFixed(6);
document.getElementById("centerLat").textContent = centerLatDegrees;
document.getElementById("centerLon").textContent = centerLonDegrees;
}
});
// --- Get Legend Title Element Reference ---
legendTitleElement = document.getElementById('legendTitle');
appTitleElement = document.getElementById('legendHeaderTitle');
// --- Attach Event Listeners and UI Logic that depends on 'viewer' ---
// Legend Listeners
viewer.dataSources.dataSourceAdded.addEventListener((collection, dataSource) => {
console.log(`DataSource added: ${dataSource.name}`);
// Ensure legendInfo exists before trying to add
if (dataSource.legendInfo && legendTitleElement) { // Check legendTitleElement too
addLegendItem(dataSource.name, dataSource.legendInfo.title, dataSource.legendInfo.symbolHtml);
} else if (dataSource.name && !dataSource.legendInfo) {
console.warn(`DataSource ${dataSource.name} added without legendInfo.`);
}
});
viewer.dataSources.dataSourceRemoved.addEventListener((collection, dataSource) => {
console.log(`DataSource removed: ${dataSource.name}`);
// Use name property if it exists to remove legend item
if (dataSource.name) {
removeLegendItem(dataSource.name);
}
});
// Camera Control Logic
function updateCameraFromSliders() {
if (!viewer || !viewer.camera.positionCartographic) {
console.warn("Viewer or camera position not ready for slider update.");
return;
}
const heading = Cesium.Math.toRadians(parseFloat(headingSlider.value));
const pitch = Cesium.Math.toRadians(parseFloat(pitchSlider.value));
// Instead of reading from a removed height slider, obtain the current height from the camera.
const currentHeight = viewer.camera.positionCartographic.height;
const center = viewer.camera.positionCartographic;
viewer.camera.setView({
destination: Cesium.Cartesian3.fromRadians(center.longitude, center.latitude, currentHeight),
orientation: { heading: heading, pitch: pitch, roll: 0.0 }
});
}
pitchSlider.addEventListener("input", () => { pitchValue.textContent = pitchSlider.value; updateCameraFromSliders(); });
headingSlider.addEventListener("input", () => { headingValue.textContent = headingSlider.value; updateCameraFromSliders(); });
// Update sliders on manual navigation
viewer.camera.changed.addEventListener(() => {
if (!viewer || !viewer.camera.positionCartographic) return; // Extra safety check
const camera = viewer.camera;
const position = camera.positionCartographic;
const currentPitch = Cesium.Math.toDegrees(camera.pitch);
const currentHeading = Cesium.Math.toDegrees(camera.heading);
const normalizedHeading = (currentHeading % 360 + 360) % 360;
if (Math.abs(parseFloat(pitchSlider.value) - Math.round(currentPitch)) > 0.5) {
pitchSlider.value = Math.round(currentPitch);
pitchValue.textContent = Math.round(currentPitch);
}
if (Math.abs(parseFloat(headingSlider.value) - Math.round(normalizedHeading)) > 0.5) {
headingSlider.value = Math.round(normalizedHeading);
headingValue.textContent = Math.round(normalizedHeading);
}
// Update the Height display in meters (no slider)
const currentHeight = Math.round(position.height); // height is in meters
document.getElementById("heightValue").textContent = currentHeight;
// --- Update the Center Coordinates ---
const canvas = viewer.canvas;
const centerScreen = new Cesium.Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2);
const centerCartesian = viewer.scene.camera.pickEllipsoid(centerScreen, Cesium.Ellipsoid.WGS84);
if (centerCartesian) {
const centerCarto = Cesium.Cartographic.fromCartesian(centerCartesian);
const centerLatDegrees = Cesium.Math.toDegrees(centerCarto.latitude).toFixed(4);
const centerLonDegrees = Cesium.Math.toDegrees(centerCarto.longitude).toFixed(4);
// Update the HTML elements with the new coordinates
document.getElementById("centerLat").textContent = centerLatDegrees;
document.getElementById("centerLon").textContent = centerLonDegrees;
}
});
// ROI coordinates
const roiLon = -110.7; // -110.2;
const roiLat = 41.469939;
const roiHeight = 150055; // 132000; // in meters
// Grab the record map checkbox
const recordMapCheckbox = document.getElementById('recordMapCheckbox');
// Sequence Button Listener
sequenceButton.addEventListener("click", async () => {
// Remove intro popup before starting sequence
const intro = document.getElementById('introPopup');
if (intro) {
intro.parentNode.removeChild(intro);
}
console.log("Run Sequence button clicked.");
try {
// Start recording if checkbox checked and not already recording
if (recordMapCheckbox && recordMapCheckbox.checked && !recordingActive) {
startRecording();
}
// Clear sequence graphics if needed
clearSequenceGraphics(viewer);
// Run the sequence: show Wyoming first, then fly to ROI
await runSequence(viewer, roiLon, roiLat, roiHeight);
// Stop recording if it was started
if (recordingActive) {
stopRecording();
}
} catch (error) {
console.error("Error during runSequence:", error);
}
});
} catch (error) {
console.error("Failed to initialize Cesium Viewer:", error);
const container = document.getElementById('cesiumContainer');
if (container) {
container.innerHTML = `<div style="padding: 20px; color: red; text-align: center;">Error initializing map: ${error.message} <br/> Please check the console (F12) and ensure your Cesium Ion Token is correct.</div>`;
}
}
}
/**
* Animate a white rectangle randomly moving around your NLC grid
* until it settles over the cell containing the current year’s plant.
*
* @param {Cesium.Viewer} viewerInstance
* @param {Cesium.GeoJsonDataSource} nlcDs – the loaded NLC layer for that year
* @param {Cesium.DataSource} pptDs – the loaded power‑plant GeoJSON for that year
* @param {number} durationSeconds – how long to random‑move before settling
* @returns {Promise<void>} – resolves once the highlight is in place
*/
// Updated async implementation of animateRandomHighlight
async function animateRandomHighlight(viewerInstance, nlcDs, pptDs, durationSeconds, maskRect, showRect) {
// Ensure NLC layer is visible and plant layer hidden during highlight
nlcDs.show = true;
pptDs.show = false;
// Remove old label if it exists
const oldLabel = viewerInstance.entities.getById('showRectLabel');
if (oldLabel) {
viewerInstance.entities.remove(oldLabel);
}
const boxFont = '26px sans-serif';
const boxAlpha = 0.8;
// Add a text label above the top border of the mask rectangle
viewerInstance.entities.add({
id: 'showRectLabel',
position: Cesium.Cartesian3.fromRadians(
(showRect.west + showRect.east) / 2,
showRect.north,
0
),
label: {
text: 'Explore Focal Region',
font: boxFont,
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: Cesium.Color.BLACK.withAlpha(boxAlpha),
backgroundPadding: new Cesium.Cartesian2(4, 4),
style: Cesium.LabelStyle.FILL,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
pixelOffset: new Cesium.Cartesian2(0, -5)
}
});
// Add NLC colorbar overlay when NLC label appears
const colorbarDiv = document.createElement('div');
colorbarDiv.id = 'nlcColorbar';
// Compute midpoint of the rectangle’s bottom edge
const midLon = (showRect.west + showRect.east) / 2;
const midLat = showRect.south;
const groundPos = Cesium.Cartesian3.fromRadians(midLon, midLat, 0);
const screenPos = viewerInstance.scene.cartesianToCanvasCoordinates(groundPos);
// Style & position the bar
Object.assign(colorbarDiv.style, {
position: 'absolute',
pointerEvents: 'none',
width: '200px',
height: '20px',
background: 'linear-gradient(to right, #1AFF1A, #4B0092)',
border: '1px solid #ffffff',
left: (screenPos.x - 100) + 'px', // center under rect
top: (screenPos.y + 5) + 'px', // just below the outline
zIndex: '999'
});
cesiumContainer.appendChild(colorbarDiv);
// Add labels for the colorbar
const lowerLabel = document.createElement('div');
lowerLabel.id = 'nlcColorbarLower';
lowerLabel.textContent = 'Lower\nCosts';
Object.assign(lowerLabel.style, {
position: 'absolute',
pointerEvents: 'none',
color: '#ffffff',
fontSize: '16px',
left: `${screenPos.x - 195}px`, // 10px to the left of the bar start
top: `${screenPos.y + 5}px` // same vertical position as the bar
});
cesiumContainer.appendChild(lowerLabel);
const higherLabel = document.createElement('div');
higherLabel.id = 'nlcColorbarHigher';
higherLabel.textContent = 'Higher\nCosts';
Object.assign(higherLabel.style, {
position: 'absolute',
pointerEvents: 'none',
color: '#ffffff',
fontSize: '16px',
left: `${screenPos.x + 100 + 10}px`, // 10px to the right of the bar end (bar width = 200)
top: `${screenPos.y + 5}px`
});
cesiumContainer.appendChild(higherLabel);
// 1. Filter to NLC polygons inside the mask rectangle (suitable areas)
let entitiesToUse = nlcDs.entities.values;
if (maskRect) {
entitiesToUse = entitiesToUse.filter(ent => {
const coords = ent.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
const cellRect = Cesium.Rectangle.fromCartesianArray(coords);
// Only include polygons that intersect the maskRect (inside the mask)
return Cesium.Rectangle.intersection(cellRect, maskRect) !== undefined;
});
}
// Only display the filtered NLC polygons
nlcDs.entities.values.forEach(ent => {
ent.show = false;
});
entitiesToUse.forEach(ent => {
ent.show = true;
});
// Step 1: Hide NLC polygons overlapping suitability layers; show only those fully in suitable areas
// Gather all suitability data sources (named id_suitability0…id_suitability14)
const suitabilitySources = [];
for (let i = 0; i <= 14; i++) {
const ds = viewerInstance.dataSources.getByName(`id_suitability${i}`)[0];
if (ds) suitabilitySources.push(ds);
}
entitiesToUse.forEach(ent => {
const coords = ent.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
const cellRect = Cesium.Rectangle.fromCartesianArray(coords);
// Check intersection with any suitability polygon
let overlapsSuitability = false;
suitabilitySources.forEach(suitDs => {
suitDs.entities.values.forEach(suitEnt => {
const suitCoords = suitEnt.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
const suitRect = Cesium.Rectangle.fromCartesianArray(suitCoords);
if (Cesium.Rectangle.intersection(cellRect, suitRect) !== undefined) {
overlapsSuitability = true;
}
});
});
if (overlapsSuitability) {
// Make overlapping polygons fully transparent
ent.polygon.material = Cesium.Color.TRANSPARENT;
ent.polygon.outline = false;
} else {
// Highlight only the suitable ones
ent.polygon.material = Cesium.Color.fromCssColorString('#4B0092').withAlpha(1.0);
ent.polygon.outline = true;
ent.polygon.outlineColor = Cesium.Color.WHITE;
ent.polygon.outlineWidth = 2;
}
});
await new Promise(r => setTimeout(r, 5000));
// Step 2: Color remaining polygons from red to green based on their NLC value
// Remove any previous 'showRectLabel' to avoid duplicates
const oldLabel2 = viewerInstance.entities.getById('showRectLabel');
if (oldLabel2) {
viewerInstance.entities.remove(oldLabel2);
}
// Add updated label for Economic Costs
viewerInstance.entities.add({
id: 'showRectLabel',
position: Cesium.Cartesian3.fromRadians(
(showRect.west + showRect.east) / 2,
showRect.north,
0
),
label: {
text: 'Net Locational Costs (NLC)',
font: boxFont,
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: Cesium.Color.BLACK.withAlpha(boxAlpha),
backgroundPadding: new Cesium.Cartesian2(4, 4),
style: Cesium.LabelStyle.FILL,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
pixelOffset: new Cesium.Cartesian2(0, -5)
}
});
const values = entitiesToUse.map(ent => ent.properties.NLC.getValue(Cesium.JulianDate.now()));
const minVal = Math.min(...values);
const maxVal = Math.max(...values);
entitiesToUse.forEach(ent => {
const val = ent.properties.NLC.getValue(Cesium.JulianDate.now());
const t = (val - minVal) / (maxVal - minVal);
const color = new Cesium.Color();
Cesium.Color.lerp(
// color blind friendlly
Cesium.Color.fromCssColorString('#1AFF1A'), // bright green
Cesium.Color.fromCssColorString('#4B0092'), // dark purple
t,
color
);
ent.polygon.material = color.withAlpha(0.8);
ent.polygon.outline = true;
ent.polygon.outlineWidth = 4;
});
await new Promise(r => setTimeout(r, 5000));
// Step 3: Identify top 20% most negative (lowest) NLC values
const sorted = entitiesToUse.slice().sort((a, b) => {
return a.properties.NLC.getValue(Cesium.JulianDate.now()) - b.properties.NLC.getValue(Cesium.JulianDate.now());
});
const cutoffIndex = Math.floor(sorted.length * 0.20);
const cutoffVal = sorted[cutoffIndex]?.properties.NLC.getValue(Cesium.JulianDate.now()) ?? minVal;
// Remove any previous 'showRectLabel' to avoid duplicates
const oldLabel5 = viewerInstance.entities.getById('showRectLabel');
if (oldLabel5) {
viewerInstance.entities.remove(oldLabel5);
}
// Add updated label for Economic Costs
viewerInstance.entities.add({
id: 'showRectLabel',
position: Cesium.Cartesian3.fromRadians(
(showRect.west + showRect.east) / 2,
showRect.north,
0
),
label: {
text: 'Lowest NLC',
font: boxFont,
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: Cesium.Color.BLACK.withAlpha(boxAlpha),
backgroundPadding: new Cesium.Cartesian2(4, 4),
style: Cesium.LabelStyle.FILL,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
pixelOffset: new Cesium.Cartesian2(0, -5)
}
});
// Step 4: Color top 5% green, others red with white borders
entitiesToUse.forEach(ent => {
const val = ent.properties.NLC.getValue(Cesium.JulianDate.now());
if (val <= cutoffVal) {
ent.polygon.material = Cesium.Color.fromCssColorString('#1AFF1A').withAlpha(0.6);
} else {
ent.polygon.material = Cesium.Color.fromCssColorString('#4B0092').withAlpha(0.6);
}
ent.polygon.outline = true;
ent.polygon.outlineColor = Cesium.Color.WHITE;
ent.polygon.outlineWidth = 4;
});
await new Promise(r => setTimeout(r, 5000));
// Step 5: Run the random highlight animation over just the top 20% for 5000 ms,
// but only on polygons that do not intersect any suitability layers
const oldLabel3 = viewerInstance.entities.getById('showRectLabel');
if (oldLabel3) {
viewerInstance.entities.remove(oldLabel3);
}
viewerInstance.entities.add({
id: 'showRectLabel',
position: Cesium.Cartesian3.fromRadians(
(showRect.west + showRect.east) / 2,
showRect.north,
0
),
label: {
text: 'Finding Optimal Location',
font: boxFont,
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: Cesium.Color.BLACK.withAlpha(boxAlpha),
backgroundPadding: new Cesium.Cartesian2(4, 4),
style: Cesium.LabelStyle.FILL,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
pixelOffset: new Cesium.Cartesian2(0, -5)
}
});
const topCount = Math.ceil(entitiesToUse.length * 0.20);
const candidateEntities = sorted.slice(0, topCount);
let topEntities = candidateEntities.filter(ent => {
const coords = ent.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
const cellRect = Cesium.Rectangle.fromCartesianArray(coords);
// Exclude any entity overlapping a suitability polygon
return !suitabilitySources.some(suitDs =>
suitDs.entities.values.some(suitEnt => {
const suitCoords = suitEnt.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
const suitRect = Cesium.Rectangle.fromCartesianArray(suitCoords);
return Cesium.Rectangle.intersection(cellRect, suitRect) !== undefined;
})
);
});
// If no polygons pass the suitability filter, fall back to the top 20% candidates
if (topEntities.length === 0) {
topEntities = candidateEntities;
}
if (topEntities.length > 0) {
// Sample rect and target rect logic
const sample = topEntities[0];
const sampleCartesians = sample.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
const sampleRect = Cesium.Rectangle.fromCartesianArray(sampleCartesians);
const plantPos = pptDs.entities.values[0].position.getValue(Cesium.JulianDate.now());
const plantCarto = Cesium.Ellipsoid.WGS84.cartesianToCartographic(plantPos);
let targetRect = sampleRect;
topEntities.forEach(ent => {
const coords = ent.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
const r = Cesium.Rectangle.fromCartesianArray(coords);
if (Cesium.Rectangle.contains(r, plantCarto)) {
targetRect = r;
}
});
// Create highlight rectangle
const highlight = viewerInstance.entities.add({
id: 'randomRectHighlight',
rectangle: {
coordinates: sampleRect,
material: Cesium.Color.WHITE.withAlpha(0.4), // visible semi-transparent fill
outline: true,
outlineColor: Cesium.Color.WHITE.withAlpha(1.0),
outlineWidth: 7, // slightly thicker for visibility
heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
height: 100
}