-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
993 lines (899 loc) · 37.1 KB
/
script.js
File metadata and controls
993 lines (899 loc) · 37.1 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
// Satisfactory Node Heatmap - Interactive map with heatmap, shapes, and waypoints
// Uses Leaflet with CRS.Simple to keep a single, non-distorted coordinate space
(function () {
const imagePath = "resources/map.jpg";
// URL state helpers
const QS = {
parseBool(v, d) {
if (v == null) return d;
const s = String(v).toLowerCase();
if (["1", "true", "yes", "on"].includes(s)) return true;
if (["0", "false", "no", "off"].includes(s)) return false;
return d;
},
parseNumber(v, d) {
if (v == null) return d;
const n = Number(v);
return Number.isFinite(n) ? n : d;
},
getParams() {
return new URLSearchParams(window.location.search || "");
},
};
// Capture initial state from URL so we can apply after UI builds
const initialState = readInitialStateFromUrl();
// Elements
const elHeat = document.getElementById("toggle-heatmap");
const elBorder = document.getElementById("toggle-border");
const elWaypoints = document.getElementById("toggle-waypoints");
// Reset control now lives in map UI under zoom; no sidebar button
const coordX = document.getElementById("coord-x");
const coordY = document.getElementById("coord-y");
// Heatmap controls
const hmResources = document.getElementById("hm-resources");
const hmInfluence = document.getElementById("hm-influence");
const hmGrid = document.getElementById("hm-grid");
const hmRadius = document.getElementById("hm-radius");
const hmBlur = document.getElementById("hm-blur");
const hmCombine = document.getElementById("hm-combine");
const hmMax = document.getElementById("hm-max");
const hmKernel = document.getElementById("hm-kernel");
const hmThreshold = document.getElementById("hm-threshold");
const hmOpacity = document.getElementById("hm-opacity");
const nodesListSolid = document.getElementById("nodes-list-solid");
const nodesListLiquid = document.getElementById("nodes-list-liquid");
const nodesListGas = document.getElementById("nodes-list-gas");
const nodesAllOn = document.getElementById("nodes-all-on");
const nodesAllOff = document.getElementById("nodes-all-off");
const nodesToggleImpure = document.getElementById("nodes-toggle-impure");
const nodesToggleNormal = document.getElementById("nodes-toggle-normal");
const nodesTogglePure = document.getElementById("nodes-toggle-pure");
// Map/image sizes
let width = 0,
height = 0;
const GAME = {
X_MIN: -324700,
X_MAX: 425300,
Y_MIN: -375000,
Y_MAX: 375000,
SIZE: 750000,
};
// Node layers registry: Map resourceName -> { form, Impure, Normal, Pure, active }
const nodeLayers = new Map();
// Node index for heatmap: Map resourceName -> { sumWeight, nodes: [{xImg,yImg, weight}] }
const nodeIndex = new Map();
// Normalized name -> canonical resourceName
const nameLookup = new Map();
// Snapshot of default values as defined in code/HTML at load
let defaultState = null;
// Keep references to layers that need resetting
let borderLayerRef = null;
let waypointsLayerRef = null;
let mapRef = null;
let heatLayer = null;
let lastHeatPoints = [];
// Load the image to get its intrinsic dimensions
const img = new Image();
img.src = imagePath + "?v=" + Date.now(); // cache-bust for local dev
img.decode
? img
.decode()
.then(init)
.catch(() => (img.onload = () => init()))
: (img.onload = () => init());
function init() {
width = img.naturalWidth || img.width;
height = img.naturalHeight || img.height;
if (!width || !height) {
console.error("Failed to load map image dimensions.");
return;
}
// Coordinate system: [y, x] -> [lat, lng] with CRS.Simple
const bounds = [
[0, 0],
[height, width],
];
// Init map
const map = L.map("map", {
crs: L.CRS.Simple,
minZoom: -4,
maxZoom: 4,
zoomControl: true,
attributionControl: false,
maxBounds: bounds,
maxBoundsViscosity: 1.0,
});
const image = L.imageOverlay(imagePath, bounds, { interactive: false }).addTo(map);
map.fitBounds(bounds);
mapRef = map;
// Overlays
// 1) Heatmap (data-driven; initially empty until selections)
heatLayer = L.heatLayer([], heatLayerOptions()).addTo(map);
// 2) World Border (closed polygon, solid red line, no fill)
const borderWorld = [
[-341000, -313000],
[-232000, -370000],
[450000, -370000],
[450000, -33000],
[192000, 335000],
[-237000, 335000],
[-341000, 95000],
];
const borderImg = borderWorld.map(([X, Y]) => [height - ((Y - GAME.Y_MIN) / GAME.SIZE) * height, ((X - GAME.X_MIN) / GAME.SIZE) * width]);
let borderLayer = L.polygon(borderImg, { color: "#ff0000", weight: 3, fill: false });
if (elBorder && elBorder.checked) borderLayer.addTo(map);
borderLayerRef = borderLayer;
// 3) Waypoints (markers with popup on click)
const waypointData = [
// Example path for reference
// { name: "Iron Node", y: height * 0.52, x: width * 0.42, desc: "High purity iron." },
// { name: "Coal Node", y: height * 0.3, x: width * 0.75, desc: "Coal deposit near cliff." },
// { name: "Water Pump", y: height * 0.78, x: width * 0.22, desc: "Water access point." },
];
const icon = L.divIcon({
className: "waypoint-icon",
html: '<div style="width:18px;height:18px;border-radius:50%;background:#4cc9f0;border:2px solid #0b0d12;box-shadow:0 0 0 2px #4cc9f0aa"></div>',
iconSize: [18, 18],
iconAnchor: [9, 9],
});
const waypointMarkers = waypointData.map((wp) => L.marker([wp.y, wp.x], { icon }).bindPopup(`<strong>${wp.name}</strong><br/>${wp.desc}`));
const waypointsLayer = L.layerGroup(waypointMarkers).addTo(map);
waypointsLayerRef = waypointsLayer;
// Single movable waypoint via X/Y Go control
let gotoMarker = null;
const gotoIcon = L.divIcon({
className: "goto-waypoint",
html: '<div class="pin"></div>',
iconSize: [18, 18],
iconAnchor: [9, 9],
});
// Add X/Y inputs + Go button next to zoom controls
const gotoControl = L.control({ position: "topleft" });
gotoControl.onAdd = function () {
const container = L.DomUtil.create("div", "coords-go");
const xInput = document.createElement("input");
xInput.type = "text";
xInput.placeholder = "X";
xInput.inputMode = "numeric";
xInput.setAttribute("aria-label", "X coordinate");
const yInput = document.createElement("input");
yInput.type = "text";
yInput.placeholder = "Y";
yInput.inputMode = "numeric";
yInput.setAttribute("aria-label", "Y coordinate");
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = "Go";
function go() {
elWaypoints.checked = true;
const X = Number(xInput.value.replace(/[,\s]/g, ""));
const Y = Number(yInput.value.replace(/[,\s]/g, ""));
const valid = Number.isFinite(X) && Number.isFinite(Y);
xInput.classList.toggle("invalid", !Number.isFinite(X));
yInput.classList.toggle("invalid", !Number.isFinite(Y));
if (!valid) return;
// Convert game coords (X,Y) -> image coords (xImg,yImg) -> Leaflet latlng [y,x]
const xImg = ((X - GAME.X_MIN) / GAME.SIZE) * width;
const yImg = height - ((Y - GAME.Y_MIN) / GAME.SIZE) * height;
const latlng = [yImg, xImg];
if (gotoMarker) {
gotoMarker.setLatLng(latlng);
} else {
gotoMarker = L.marker(latlng, { icon: gotoIcon });
waypointsLayer.addLayer(gotoMarker);
}
// Ensure layer visible if user has Waypoints toggled on
if (elWaypoints.checked && !map.hasLayer(waypointsLayer)) {
waypointsLayer.addTo(map);
}
// Briefly highlight the waypoint
if (gotoMarker._icon) {
gotoMarker._icon.classList.remove("pulse");
// Force reflow to restart animation
// eslint-disable-next-line no-unused-expressions
gotoMarker._icon.offsetHeight;
gotoMarker._icon.classList.add("pulse");
}
// Optionally center map around point a bit
map.panTo(latlng, { animate: true });
}
btn.addEventListener("click", go);
xInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") go();
});
yInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") go();
});
container.append(xInput, yInput, btn);
L.DomEvent.disableClickPropagation(container);
L.DomEvent.disableScrollPropagation(container);
return container;
};
gotoControl.addTo(map);
// Add "Reset view" button under the zoom-out control
// This inserts a third button in the default Leaflet zoom bar
const zoomContainer = map.zoomControl && map.zoomControl.getContainer();
if (zoomContainer) {
const home = L.DomUtil.create("a", "leaflet-control-zoom-home", zoomContainer);
home.href = "#";
home.title = "Reset view";
home.setAttribute("aria-label", "Reset view");
home.innerHTML = `
<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false">
<path fill="currentColor" d="M12 3.172 3.586 11.586a2 2 0 0 0 2.828 2.828L7 13.828V20a1 1 0 0 0 1 1h3v-5h2v5h3a1 1 0 0 0 1-1v-6.172l.586.586a2 2 0 1 0 2.828-2.828L12 3.172z"/>
</svg>`;
L.DomEvent.on(home, "click", (e) => {
L.DomEvent.preventDefault(e);
L.DomEvent.stopPropagation(e);
map.fitBounds(bounds);
});
}
// Controls wiring for base overlays
elHeat.addEventListener("change", () => {
toggleLayer(map, heatLayer, elHeat.checked);
saveStateToUrl();
});
elBorder.addEventListener("change", () => {
toggleLayer(map, borderLayer, elBorder.checked);
saveStateToUrl();
});
elWaypoints.addEventListener("change", () => {
toggleLayer(map, waypointsLayer, elWaypoints.checked);
saveStateToUrl();
});
// Sidebar reset button removed; reset handled via map control above
// Wire reset-to-defaults button
const resetBtn = document.getElementById("reset-defaults");
if (resetBtn) resetBtn.addEventListener("click", resetToDefaults);
// Collapsible UI behavior
document.querySelectorAll("[data-collapsible]").forEach((section) => {
const btn = section.querySelector(".collapse-toggle");
const body = section.querySelector(".collapse-body");
btn.addEventListener("click", () => {
const expanded = btn.getAttribute("aria-expanded") === "true";
btn.setAttribute("aria-expanded", String(!expanded));
body.style.display = expanded ? "none" : "";
});
});
// Mouse coordinate readout in footer (convert image coords -> game coords)
map.on("mousemove", (e) => {
const xImg = e.latlng.lng; // [lng] is x in image space
const yImg = e.latlng.lat; // [lat] is y in image space
const X = GAME.X_MIN + (xImg / width) * GAME.SIZE;
// Flip Y so top is Y_MIN and bottom is Y_MAX
const Y = GAME.Y_MIN + ((height - yImg) / height) * GAME.SIZE;
coordX.textContent = Math.round(X).toLocaleString();
coordY.textContent = Math.round(Y).toLocaleString();
});
map.on("mouseout", () => {
coordX.textContent = "—";
coordY.textContent = "—";
});
// Capture defaults before applying any URL overrides
captureDefaultState();
// Apply initial layer visibility from URL before loading nodes
if (initialState.layers) {
if (typeof initialState.layers.heat === "boolean") {
elHeat.checked = initialState.layers.heat;
toggleLayer(map, heatLayer, elHeat.checked);
}
if (typeof initialState.layers.border === "boolean") {
elBorder.checked = initialState.layers.border;
toggleLayer(map, borderLayer, elBorder.checked);
}
if (typeof initialState.layers.waypoints === "boolean") {
elWaypoints.checked = initialState.layers.waypoints;
toggleLayer(map, waypointsLayer, elWaypoints.checked);
}
}
// Load nodes and build layers + UI
loadNodes(map).then(() => {
populateHeatmapResourceList();
// Apply initial heatmap resources/settings from URL
applyInitialHeatmapStateFromUrl();
hookHeatmapControls();
rebuildHeatmap();
// After nodes/UI exist, apply initial node toggles
applyInitialNodeTogglesFromUrl(map);
// Sync URL to reflect any differences from defaults (will be empty on fresh load)
saveStateToUrl();
});
// Keep heat visualization balanced across zoom levels by adapting radius
map.on("zoomend", () => {
renderHeatWith(lastHeatPoints);
});
// Keep layers aligned and prevent aspect distortion (CRS.Simple handles scaling proportionally)
const ro = new ResizeObserver(() => {
map.invalidateSize();
});
ro.observe(document.getElementById("map"));
}
function toggleLayer(map, layer, on) {
if (on) {
if (!map.hasLayer(layer)) layer.addTo(map);
} else {
if (map.hasLayer(layer)) map.removeLayer(layer);
}
}
// Nodes
async function loadNodes(map) {
try {
const res = await fetch("resources/nodes_vanilla.json");
if (!res.ok) throw new Error("Failed to load nodes_vanilla.json");
const nodes = await res.json();
// Build layer groups per resource + purity
const purityKeys = ["Impure", "Normal", "Pure"];
const iconCache = new Map();
// Group nodes
for (const n of nodes) {
const resName = n.name || n.class_name || "Unknown";
const purity = normalizePurity(n.purity || "Normal");
const form = n.resource_form || "Solid";
if (!nodeLayers.has(resName)) {
nodeLayers.set(resName, {
form,
Impure: L.layerGroup(),
Normal: L.layerGroup(),
Pure: L.layerGroup(),
active: { Impure: true, Normal: true, Pure: true },
});
}
const groups = nodeLayers.get(resName);
const { x: X, y: Y } = n.location || { x: 0, y: 0 };
const xImg = ((X - GAME.X_MIN) / GAME.SIZE) * width;
// Flip Y so that in-game Y_MIN maps to image top (0)
const yImg = height - ((Y - GAME.Y_MIN) / GAME.SIZE) * height;
const m = L.marker([yImg, xImg], { icon: nodeIconFor(resName, purity, iconCache) }).bindPopup(`<strong>${escapeHtml(resName)}</strong><br/>Purity: ${purity}<br/>X: ${Math.round(X)} Y: ${Math.round(Y)}`);
groups[purity].addLayer(m);
// Index for heatmap
const w = purityWeight(purity);
if (!nodeIndex.has(resName)) nodeIndex.set(resName, { sumWeight: 0, nodes: [] });
nodeIndex.get(resName).nodes.push({ x: xImg, y: yImg, weight: w });
nodeIndex.get(resName).sumWeight += w;
}
// Add all groups to map and build UI rows, grouped by resource_form
// No default selections; all off until user or URL state enables
const defaultSelected = new Set();
nodeLayers.forEach((groups, resName) => {
const resKey = String(resName).trim().toLowerCase();
nameLookup.set(resKey, resName);
const defaultOn = defaultSelected.has(resKey);
groups.active.Impure = defaultOn;
groups.active.Normal = defaultOn;
groups.active.Pure = defaultOn;
if (defaultOn) {
groups.Impure.addTo(map);
groups.Normal.addTo(map);
groups.Pure.addTo(map);
}
const row = document.createElement("div");
row.className = "row";
const label = document.createElement("div");
label.className = "label";
label.textContent = resName;
const btns = document.createElement("div");
btns.className = "btns";
const btnImpure = purityButton("Impure", resName);
const btnNormal = purityButton("Normal", resName);
const btnPure = purityButton("Pure", resName);
// Set initial active state (none by default)
btnImpure.classList.toggle("active", defaultOn);
btnNormal.classList.toggle("active", defaultOn);
btnPure.classList.toggle("active", defaultOn);
btnImpure.addEventListener("click", () => togglePurity(map, groups, "Impure", btnImpure));
btnNormal.addEventListener("click", () => togglePurity(map, groups, "Normal", btnNormal));
btnPure.addEventListener("click", () => togglePurity(map, groups, "Pure", btnPure));
btns.append(btnImpure, btnNormal, btnPure);
row.append(label, btns);
const container = groups.form === "Liquid" ? nodesListLiquid : groups.form === "Gas" ? nodesListGas : nodesListSolid;
container.appendChild(row);
});
// Mass actions
nodesAllOn.addEventListener("click", () => {
nodeLayers.forEach((groups) => {
setPurity(map, groups, "Impure", true);
setPurity(map, groups, "Normal", true);
setPurity(map, groups, "Pure", true);
});
updateButtonsActive(true);
saveStateToUrl();
});
nodesAllOff.addEventListener("click", () => {
nodeLayers.forEach((groups) => {
setPurity(map, groups, "Impure", false);
setPurity(map, groups, "Normal", false);
setPurity(map, groups, "Pure", false);
});
updateButtonsActive(false);
saveStateToUrl();
});
// Per-purity toggle-all actions
nodesToggleImpure.addEventListener("click", () => {
toggleAllOfPurity(map, "Impure");
saveStateToUrl();
});
nodesToggleNormal.addEventListener("click", () => {
toggleAllOfPurity(map, "Normal");
saveStateToUrl();
});
nodesTogglePure.addEventListener("click", () => {
toggleAllOfPurity(map, "Pure");
saveStateToUrl();
});
} catch (err) {
console.error(err);
}
}
function updateButtonsActive(on) {
document.querySelectorAll("#nodes-list-solid .btn.icon, #nodes-list-liquid .btn.icon, #nodes-list-gas .btn.icon").forEach((btn) => btn.classList.toggle("active", on));
}
function toggleAllOfPurity(map, purity) {
nodeLayers.forEach((groups) => {
const next = !groups.active[purity];
setPurity(map, groups, purity, next);
});
// Sync UI buttons per resource
document.querySelectorAll(`#nodes-section .btn.icon[data-purity="${purity}"]`).forEach((btn) => {
const res = btn.dataset.resource;
const groups = nodeLayers.get(res);
if (groups) btn.classList.toggle("active", groups.active[purity]);
});
}
function setPurity(map, groups, purity, on) {
groups.active[purity] = on;
toggleLayer(map, groups[purity], on);
}
function togglePurity(map, groups, purity, btn) {
const on = !groups.active[purity];
setPurity(map, groups, purity, on);
btn.classList.toggle("active", on);
saveStateToUrl();
}
function purityButton(kind, resourceName) {
const btn = document.createElement("button");
btn.type = "button";
const purityClass = kind.toLowerCase();
btn.className = "btn icon " + purityClass;
btn.dataset.purity = kind;
btn.dataset.resource = resourceName;
const img = createMiniIconImg(resourceName);
btn.appendChild(img);
return btn;
}
function normalizePurity(p) {
if (!p) return "Normal";
const s = String(p).toLowerCase();
if (s.startsWith("imp")) return "Impure";
if (s.startsWith("pur")) return "Pure";
return "Normal";
}
function purityWeight(purity) {
switch (purity) {
case "Impure":
return 1;
case "Pure":
return 4;
default:
return 2; // Normal
}
}
function circle(color) {
return `<div style="width:14px;height:14px;border-radius:50%;background:${color};border:2px solid #0b0d12;box-shadow:0 0 0 2px ${color}33"></div>`;
}
function escapeHtml(str) {
return String(str).replace(/[&<>"]+/g, (s) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[s]));
}
function iconPathForResource(resourceName) {
const baseName = String(resourceName).trim().replace(/\s+/g, "_");
return `resources/img/${baseName}.png`;
}
function createMiniIconImg(resourceName) {
const img = document.createElement("img");
img.className = "mini-icon";
img.alt = resourceName;
img.src = iconPathForResource(resourceName);
img.onerror = function () {
this.onerror = null;
this.src = "resources/img/unknown.png";
};
return img;
}
// Build or reuse a divIcon that shows the resource image; fallback to unknown.png if missing
function nodeIconFor(resourceName, purity, cache) {
const purityKey = purity.toLowerCase();
const baseName = String(resourceName).trim().replace(/\s+/g, "_");
const key = `${baseName}:${purityKey}`;
if (cache.has(key)) return cache.get(key);
const src = `resources/img/${baseName}.png`;
const html = `
<div class="node-marker ${purityKey}">
<img src="${src}" alt="${escapeHtml(resourceName)}" onerror="this.onerror=null;this.src='resources/img/unknown.png'"/>
</div>`;
const icon = L.divIcon({
className: "",
html,
iconSize: [22, 22],
iconAnchor: [11, 11],
});
cache.set(key, icon);
return icon;
}
// Heatmap UI and computation
function populateHeatmapResourceList() {
if (!hmResources) return;
const names = Array.from(nodeIndex.keys()).sort((a, b) => a.localeCompare(b));
hmResources.innerHTML = "";
for (const name of names) {
const opt = document.createElement("option");
opt.value = name;
opt.textContent = name;
hmResources.appendChild(opt);
}
}
function hookHeatmapControls() {
const trigger = debounce(() => {
// Any change to heatmap settings enables the heatmap
if (elHeat && mapRef) {
elHeat.checked = true;
toggleLayer(mapRef, heatLayer, true);
}
rebuildHeatmap();
saveStateToUrl();
}, 150);
[hmResources, hmInfluence, hmGrid, hmRadius, hmBlur, hmCombine, hmMax, hmKernel, hmThreshold, hmOpacity].forEach((el) => {
if (!el) return;
const ev = el.tagName === "SELECT" ? "change" : "input";
el.addEventListener(ev, trigger);
});
}
function rebuildHeatmap() {
if (!mapRef || !heatLayer) return;
const selected = Array.from(hmResources?.selectedOptions || []).map((o) => o.value);
const points = computeHeatPoints(selected);
lastHeatPoints = points;
renderHeatWith(points);
}
function computeHeatPoints(selectedResources) {
const pts = [];
if (!selectedResources || selectedResources.length === 0) return pts;
const cells = Number(hmGrid?.value || 64);
const step = Math.max(6, Math.min(width, height) / cells);
const R = Number(hmInfluence?.value || 320);
const kernel = hmKernel?.value || "compact";
const combine = hmCombine?.value || "product";
const entries = selectedResources.map((name) => nodeIndex.get(name)).filter(Boolean);
if (entries.length === 0) return pts;
const normalizers = entries.map((e) => Math.max(1e-6, e.sumWeight));
const rawVals = [];
for (let y = step / 2; y < height; y += step) {
for (let x = step / 2; x < width; x += step) {
const vals = [];
for (let i = 0; i < entries.length; i++) {
const e = entries[i];
const denom = normalizers[i];
let sum = 0;
for (const n of e.nodes) {
const dx = x - n.x;
const dy = y - n.y;
const d2 = dx * dx + dy * dy;
if (kernel === "compact") {
const r2 = R * R;
if (d2 <= r2) {
const u = d2 / r2; // 0..1
const k = (1 - u) * (1 - u);
sum += n.weight * k;
}
} else {
const sigma = R / 2;
const twoSigma2 = 2 * sigma * sigma;
sum += n.weight * Math.exp(-d2 / twoSigma2);
}
}
vals.push(sum / denom);
}
let intensity = 0;
if (combine === "min") {
intensity = Math.max(0, Math.min(...vals));
} else if (combine === "sum") {
intensity = vals.reduce((a, b) => a + b, 0) / vals.length;
} else {
const eps = 1e-9;
const logSum = vals.reduce((acc, v) => acc + Math.log(Math.max(eps, v)), 0);
intensity = Math.exp(logSum / vals.length);
}
if (intensity > 0) {
rawVals.push(intensity, x, y);
}
}
}
if (rawVals.length === 0) return pts;
// Percentile threshold to keep only hotspots
const pct = Number(hmThreshold?.value || 80) / 100;
const values = [];
for (let i = 0; i < rawVals.length; i += 3) values.push(rawVals[i]);
values.sort((a, b) => a - b);
const idx = Math.floor(values.length * pct);
const thr = values[Math.min(values.length - 1, Math.max(0, idx))];
let maxVal = values[values.length - 1] || thr || 1;
if (maxVal <= thr) maxVal = thr + 1e-6;
const gain = Number(hmMax?.value || 1);
for (let i = 0; i < rawVals.length; i += 3) {
const v = rawVals[i];
if (v <= thr) continue;
const x = rawVals[i + 1];
const y = rawVals[i + 2];
const t = Math.min(1, ((v - thr) / (maxVal - thr)) * gain);
pts.push([y, x, t]);
}
return pts;
}
function heatLayerOptions() {
// Adapt radius to current zoom to make heat readable at all scales
const zScale = mapRef ? mapRef.getZoomScale(mapRef.getZoom(), 0) : 1;
const radiusPx = Math.max(1, Number(hmRadius?.value || 25) * Math.max(1, zScale));
const blurPx = Number(hmBlur?.value || 20);
const alpha = Math.min(1, Math.max(0, Number(hmOpacity?.value ?? 60) / 100));
return {
radius: radiusPx,
blur: blurPx,
maxZoom: 4,
max: 1.0,
minOpacity: alpha, // raise/lower global alpha for all drawn points
gradient: {
0.0: `rgba(0,0,0,0)`,
0.2: `rgba(255,0,0,${(0.25 * alpha).toFixed(3)})`,
0.4: `rgba(255,0,0,${(0.55 * alpha).toFixed(3)})`,
0.7: `rgba(255,0,0,${(0.85 * alpha).toFixed(3)})`,
1.0: `rgba(255,0,0,${(1 * alpha).toFixed(3)})`,
},
};
}
function renderHeatWith(points) {
const wasOn = mapRef.hasLayer(heatLayer);
if (wasOn) mapRef.removeLayer(heatLayer);
heatLayer = L.heatLayer(points, heatLayerOptions());
if (wasOn && elHeat.checked) heatLayer.addTo(mapRef);
}
function debounce(fn, ms) {
let t = null;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn.apply(null, args), ms);
};
}
// ----- URL <-> UI state sync -----
function captureDefaultState() {
// Read current DOM defaults (from HTML attributes); no URL applied yet
defaultState = {
layers: {
heat: !!elHeat?.checked,
border: !!elBorder?.checked,
waypoints: !!elWaypoints?.checked,
},
hm: {
resources: [], // no default selections
opacity: hmOpacity ? String(hmOpacity.value) : undefined,
influence: hmInfluence ? String(hmInfluence.value) : undefined,
grid: hmGrid ? String(hmGrid.value) : undefined,
radius: hmRadius ? String(hmRadius.value) : undefined,
blur: hmBlur ? String(hmBlur.value) : undefined,
combine: hmCombine ? String(hmCombine.value) : undefined,
max: hmMax ? String(hmMax.value) : undefined,
kernel: hmKernel ? String(hmKernel.value) : undefined,
threshold: hmThreshold ? String(hmThreshold.value) : undefined,
},
nodes: [],
};
}
function readInitialStateFromUrl() {
const p = QS.getParams();
const layers = {
heat: QS.parseBool(p.get("heat"), undefined),
border: QS.parseBool(p.get("border"), undefined),
waypoints: QS.parseBool(p.get("waypoints"), undefined),
};
const hm = {
resources: (p.get("hmResources") || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean)
.map((s) => decodeURIComponent(s)),
influence: QS.parseNumber(p.get("hmInfluence"), undefined),
grid: QS.parseNumber(p.get("hmGrid"), undefined),
radius: QS.parseNumber(p.get("hmRadius"), undefined),
blur: QS.parseNumber(p.get("hmBlur"), undefined),
combine: p.get("hmCombine") || undefined,
max: QS.parseNumber(p.get("hmMax"), undefined),
kernel: p.get("hmKernel") || undefined,
threshold: QS.parseNumber(p.get("hmThreshold"), undefined),
opacity: QS.parseNumber(p.get("hmOpacity"), undefined),
};
// Nodes: comma-separated list of name[.purity]
const nodesParam = p.get("nodes");
const nodes = [];
if (nodesParam) {
for (const part of nodesParam.split(",")) {
const s = part.trim();
if (!s) continue;
const [rawName, rawPurity] = s.split(".");
const name = decodeURIComponent(rawName || "").trim();
if (!name) continue;
const purity = normalizePurity(rawPurity || "");
nodes.push({ name, purity });
}
}
return { layers, hm, nodes };
}
function applyInitialHeatmapStateFromUrl() {
const hm = initialState.hm || {};
if (hm.opacity != null && hmOpacity) hmOpacity.value = String(hm.opacity);
if (hm.influence != null && hmInfluence) hmInfluence.value = String(hm.influence);
if (hm.grid != null && hmGrid) hmGrid.value = String(hm.grid);
if (hm.radius != null && hmRadius) hmRadius.value = String(hm.radius);
if (hm.blur != null && hmBlur) hmBlur.value = String(hm.blur);
if (hm.combine && hmCombine) hmCombine.value = hm.combine;
if (hm.max != null && hmMax) hmMax.value = String(hm.max);
if (hm.kernel && hmKernel) hmKernel.value = hm.kernel;
if (hm.threshold != null && hmThreshold) hmThreshold.value = String(hm.threshold);
if (Array.isArray(hm.resources) && hm.resources.length && hmResources) {
const wanted = new Set(hm.resources.map((r) => r.trim().toLowerCase()));
for (const opt of Array.from(hmResources.options)) {
const key = String(opt.value).trim().toLowerCase();
opt.selected = wanted.has(key);
}
}
}
function applyInitialNodeTogglesFromUrl(map) {
if (!Array.isArray(initialState.nodes) || initialState.nodes.length === 0) return;
for (const { name, purity } of initialState.nodes) {
const key = nameLookup.get(String(name).trim().toLowerCase());
if (!key) continue;
const groups = nodeLayers.get(key);
if (!groups) continue;
if (!purity || purity === "Normal") {
// If purity unspecified, enable all three
setPurity(map, groups, "Impure", true);
setPurity(map, groups, "Normal", true);
setPurity(map, groups, "Pure", true);
// Update UI buttons
updateResourceButtonsUI(key, { Impure: true, Normal: true, Pure: true });
} else {
setPurity(map, groups, purity, true);
const active = Object.assign({}, groups.active);
active[purity] = true;
updateResourceButtonsUI(key, active);
}
}
}
function updateResourceButtonsUI(resourceName, active) {
const rows = document.querySelectorAll(`#nodes-section .row`);
for (const row of rows) {
const label = row.querySelector(".label");
if (!label || label.textContent !== resourceName) continue;
row.querySelectorAll(".btn.icon").forEach((btn) => {
const p = btn.dataset.purity;
btn.classList.toggle("active", !!active[p]);
});
break;
}
}
function serializeStateToParams() {
const params = new URLSearchParams();
// Layers
if (defaultState) {
if (!!elHeat?.checked !== !!defaultState.layers.heat) params.set("heat", elHeat.checked ? "1" : "0");
if (!!elBorder?.checked !== !!defaultState.layers.border) params.set("border", elBorder.checked ? "1" : "0");
if (!!elWaypoints?.checked !== !!defaultState.layers.waypoints) params.set("waypoints", elWaypoints.checked ? "1" : "0");
}
// Heatmap settings
if (hmResources) {
const selectedValues = Array.from(hmResources.selectedOptions || []).map((o) => o.value);
const def = (defaultState?.hm.resources || []).map((v) => String(v));
const selSet = new Set(selectedValues.map((v) => String(v)));
const defSet = new Set(def);
const sameSize = selSet.size === defSet.size;
let same = sameSize;
if (same) {
for (const v of selSet) if (!defSet.has(v)) { same = false; break; }
}
if (!same && selSet.size > 0) {
const encoded = selectedValues.map((v) => encodeURIComponent(v));
params.set("hmResources", encoded.join(","));
}
}
if (hmOpacity && String(hmOpacity.value) !== defaultState?.hm.opacity) params.set("hmOpacity", String(hmOpacity.value));
if (hmInfluence && String(hmInfluence.value) !== defaultState?.hm.influence) params.set("hmInfluence", String(hmInfluence.value));
if (hmGrid && String(hmGrid.value) !== defaultState?.hm.grid) params.set("hmGrid", String(hmGrid.value));
if (hmRadius && String(hmRadius.value) !== defaultState?.hm.radius) params.set("hmRadius", String(hmRadius.value));
if (hmBlur && String(hmBlur.value) !== defaultState?.hm.blur) params.set("hmBlur", String(hmBlur.value));
if (hmCombine && String(hmCombine.value) !== defaultState?.hm.combine) params.set("hmCombine", String(hmCombine.value));
if (hmMax && String(hmMax.value) !== defaultState?.hm.max) params.set("hmMax", String(hmMax.value));
if (hmKernel && String(hmKernel.value) !== defaultState?.hm.kernel) params.set("hmKernel", String(hmKernel.value));
if (hmThreshold && String(hmThreshold.value) !== defaultState?.hm.threshold) params.set("hmThreshold", String(hmThreshold.value));
// Nodes: collect resource.purity for each active
const pairs = [];
nodeLayers.forEach((groups, resName) => {
["Impure", "Normal", "Pure"].forEach((p) => {
if (groups.active[p]) pairs.push(`${encodeURIComponent(resName)}.${p.toLowerCase()}`);
});
});
if (pairs.length) params.set("nodes", pairs.join(","));
return params;
}
const saveStateToUrl = debounce(() => {
try {
const params = serializeStateToParams();
const q = params.toString();
const newUrl = q ? `?${q}` : window.location.pathname;
window.history.replaceState(null, "", newUrl);
} catch (_) {}
}, 150);
function resetToDefaults() {
if (!defaultState) return;
try {
// Layers
if (typeof defaultState.layers.heat === "boolean") {
elHeat.checked = defaultState.layers.heat;
if (mapRef) toggleLayer(mapRef, heatLayer, elHeat.checked);
}
if (typeof defaultState.layers.border === "boolean" && borderLayerRef && mapRef) {
elBorder.checked = defaultState.layers.border;
toggleLayer(mapRef, borderLayerRef, elBorder.checked);
}
if (typeof defaultState.layers.waypoints === "boolean" && waypointsLayerRef && mapRef) {
elWaypoints.checked = defaultState.layers.waypoints;
toggleLayer(mapRef, waypointsLayerRef, elWaypoints.checked);
}
// Heatmap controls
if (hmOpacity && defaultState.hm.opacity != null) hmOpacity.value = String(defaultState.hm.opacity);
if (hmInfluence && defaultState.hm.influence != null) hmInfluence.value = String(defaultState.hm.influence);
if (hmGrid && defaultState.hm.grid != null) hmGrid.value = String(defaultState.hm.grid);
if (hmRadius && defaultState.hm.radius != null) hmRadius.value = String(defaultState.hm.radius);
if (hmBlur && defaultState.hm.blur != null) hmBlur.value = String(defaultState.hm.blur);
if (hmCombine && defaultState.hm.combine != null) hmCombine.value = String(defaultState.hm.combine);
if (hmMax && defaultState.hm.max != null) hmMax.value = String(defaultState.hm.max);
if (hmKernel && defaultState.hm.kernel != null) hmKernel.value = String(defaultState.hm.kernel);
if (hmThreshold && defaultState.hm.threshold != null) hmThreshold.value = String(defaultState.hm.threshold);
if (hmResources) {
const wanted = new Set((defaultState.hm.resources || []).map((r) => String(r).trim().toLowerCase()));
for (const opt of Array.from(hmResources.options)) {
const key = String(opt.value).trim().toLowerCase();
opt.selected = wanted.has(key);
}
}
// Nodes (all off by default in current design)
nodeLayers.forEach((groups) => {
setPurity(mapRef, groups, "Impure", false);
setPurity(mapRef, groups, "Normal", false);
setPurity(mapRef, groups, "Pure", false);
});
updateButtonsActive(false);
rebuildHeatmap();
saveStateToUrl();
} catch (e) {
console.error(e);
}
}
// Generate a few sample heat points (scattered, reproducible)
function demoHeatPoints(w, h) {
const pts = [];
const seeds = [
{ x: 0.25, y: 0.35, intensity: 0.6 },
{ x: 0.55, y: 0.5, intensity: 0.8 },
{ x: 0.7, y: 0.25, intensity: 0.7 },
{ x: 0.18, y: 0.75, intensity: 0.5 },
];
// For each seed, add a small cluster
seeds.forEach((seed) => {
for (let i = 0; i < 30; i++) {
const dx = (Math.random() - 0.5) * 0.08;
const dy = (Math.random() - 0.5) * 0.08;
const x = Math.min(0.98, Math.max(0.02, seed.x + dx));
const y = Math.min(0.98, Math.max(0.02, seed.y + dy));
const intensity = Math.max(0.25, Math.min(1, seed.intensity + (Math.random() - 0.5) * 0.25));
pts.push([h * y, w * x, intensity]);
}
});
return pts;
}
})();