Repository navigation
Expand file tree
/
Copy pathuserscript.user.js
More file actions
1388 lines (1183 loc) · 47.1 KB
/
Copy pathuserscript.user.js
File metadata and controls
1388 lines (1183 loc) · 47.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
994
995
996
997
998
999
1000
// ==UserScript==
// @name EarthMC Dynmap+
// @version 26.2
// @description Enrich the EarthMC map exploration's experience
// @author 3meraldK
// @match https://map.earthmc.net/*
// @match https://aurora.earthmc.net/*
// @iconURL https://raw.githubusercontent.com/3meraldK/earthmc-dynmap/main/icon.png
// ==/UserScript==
// Both files
const htmlCode = {
// main.js
playerLookup: '<div class="leaflet-control-layers leaflet-control left-container" id="player-lookup"></div>',
partOfLabel: '<span id="part-of-label">Part of <b>{allianceList}</b></span>',
residentClickable: '<span class="resident-clickable" onclick="lookupPlayerFunc(\'{player}\')">{player}</span>', // Different function than in main.js
residentList: '<span class="resident-list">\t{list}</span>',
scrollableResidentList: '<div class="resident-list" id="scrollable-list">\t{list}</div>',
playerLookupLoading: '<div class="leaflet-control-layers leaflet-control left-container" id="player-lookup-loading">Loading...</button>',
promptBox: '<div id="prompt-box"><p id="message">{message}</p></div>',
// content.js
buttons: {
locate: '<button class="sidebar-button" id="locate-button">Locate</button>',
searchArchive: '<button class="sidebar-button" id="archive-button">Search archive</button>',
options: '<button class="sidebar-button" id="options-button">Options</button>',
switchMapMode: '<button class="sidebar-input" id="switch-map-mode">Switch map mode</button>',
togglePlayerList: '<button class="sidebar-input" id="toggle-player-list">Toggle player list</button>'
},
options: {
menu: '<div id="options-menu"></div>',
option: '<div class="option"></div>',
label: '<label for="{option}">{optionName}</label>',
checkbox: '<input id="{option}" type="checkbox" name="{option}">',
archiveWorldMode: '<select id="archive-mode-world"><option value="" selected disabled hidden>Choose here</option><option>Classic</option><option>Terra Nova</option><option>Terra Aurora</option><option>Terra Nostra</option></select>'
},
sidebar: '<div class="leaflet-control-layers leaflet-control" id="emcdynmapplus-sidebar"></div>',
sidebarOption: '<div class="sidebar-option"></div>',
locateInput: '<input class="sidebar-input" id="locate-input" placeholder="London">',
locateSelect: '<select class="sidebar-button" id="locate-select"><option>Town</option><option>Nation</option><option>Resident</option></select>',
archiveInput: '<input class="sidebar-input" id="archive-input" type="date">',
currentMapModeLabel: '<div class="sidebar-option" id="current-map-mode-label">Current map mode: {currentMapMode}</div>',
followingPlayer: '<h1 id="followingWarning">Click on map to unfollow player</h1>',
// For userscript
updateNotification: '<div class="leaflet-control-layers leaflet-control left-container" id="update-notification">{text}<br><span class="close-container">×</span></div>',
// For both
messageBox: '<div id="message-box"><p id="message">{message}</p><br><button id="message-close">OK</button></div>'
}
const currentMapMode = localStorage['emcdynmapplus-mapmode'] ?? 'meganations'
const isNostra = !location.href.includes('aurora')
const apiURL = 'https://api.earthmc.net/v4'
const proxyURL = 'https://api.codetabs.com/v1/proxy/?quest='
const chosenArchiveDate = parseInt(localStorage['emcdynmapplus-archive-date'])
function sendMessage(message) {
if (document.querySelector('#message-box') != null) document.querySelector('#message-box').remove()
document.body.insertAdjacentHTML('beforeend', htmlCode.messageBox.replace('{message}', message))
document.querySelector('#message-close').addEventListener('click', event => { event.target.parentElement.remove() })
}
function waitForHTMLelement(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector))
}
const observer = new MutationObserver(() => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector))
observer.disconnect()
}
})
observer.observe(document.body, { childList: true, subtree: true })
})
}
function addElement(parent, element, returnWhat, all = false) {
parent.insertAdjacentHTML('beforeend', element)
return (!all) ? parent.querySelector(returnWhat) : parent.querySelectorAll(returnWhat)
}
async function fetchJSON(url, options = null) {
try {
const response = await fetch(url, options)
let data = null
try { data = await response.json() }
finally { return {ok: response.ok, code: response.status, data: data} }
} catch {
return {ok: false, code: null, data: null}
}
}
function getArchiveURL() {
let markersURL = 'https://map.earthmc.net/tiles/minecraft_overworld/markers.json'
let date = chosenArchiveDate
if (date < 20180708) {
markersURL = 'https://map.earthmc.xyz/tiles/_markers_/marker_earth.json'
} else if (date < 20220428) {
markersURL = 'https://earthmc.net/map/tiles/_markers_/marker_earth.json'
} else if (date < 20230212) {
markersURL = `https://earthmc.net/map/${server}/tiles/_markers_/marker_earth.json`
} else if (date < 20240623) {
markersURL = `https://earthmc.net/map/${server}/standalone/MySQL_markers.php?marker=_markers_/marker_earth.json`
} else if (date < 20240704) {
date = 20240704 // Skip frequent changes that week
}
const archiveWebsite = `https://web.archive.org/web/${date}id_/`
return archiveWebsite + markersURL
}
function convertOldMarkersStructure(markers) {
return Object.entries(markers.areas).map(([key, value]) => {
if (key.includes('_Shop')) return undefined // Remove shop areas
const points = value.x.map((x, index) => ({ x, z: value.z[index] }))
return {
fillColor: value.fillcolor,
color: value.color,
popup: value.desc ?? `<div><b>${value.label}</b></div>`,
weight: value.weight,
opacity: value.opacity,
type: 'polygon',
points: points
}
}).filter(Boolean)
}
// content.js
init()
// For extension only
// injectMainScript()
function addMainMenu(parent) {
const sidebar = addElement(parent, htmlCode.sidebar, '#emcdynmapplus-sidebar')
addLocateMenu(sidebar)
const archiveContainer = addElement(sidebar, htmlCode.sidebarOption, '.sidebar-option', true)[2]
const archiveButton = addElement(archiveContainer, htmlCode.buttons.searchArchive, '#archive-button')
const archiveInput = addElement(archiveContainer, htmlCode.archiveInput, '#archive-input')
archiveButton.addEventListener('click', () => searchArchive(archiveInput.value))
archiveInput.addEventListener('keyup', event => {
if (event.key == 'Enter') searchArchive(archiveInput.value)
})
const switchMapModeButton = addElement(sidebar, htmlCode.buttons.switchMapMode + '<br>', '#switch-map-mode')
switchMapModeButton.addEventListener('click', () => switchMapMode())
const togglePlayerListButton = addElement(sidebar, htmlCode.buttons.togglePlayerList + '<br>', '#toggle-player-list')
togglePlayerListButton.addEventListener('click', () => {
if (currentMapMode == 'archive') return sendMessage(`Can't view player list in archive mode.`)
const playerList = document.getElementById('players')
const isVisible = playerList.style.display == 'grid'
playerList.style.display = isVisible ? 'none' : 'grid'
if (!isVisible && !localStorage['emcdynmapplus-first-time-player-list']) {
localStorage['emcdynmapplus-first-time-player-list'] = 'false'
sendMessage('If tracking players functionality breaks, refresh the website. You will see this message once.')
}
})
addOptions(sidebar)
const currentMapModeLabel = addElement(sidebar, htmlCode.currentMapModeLabel, '#current-map-mode-label')
currentMapModeLabel.style.display = 'block'
let currentMapModeText = currentMapMode
if ((currentMapMode == 'meganations' || currentMapMode == 'alliances') && isNostra) {
currentMapModeText += ` <a style="text-decoration: none" target="_blank" href="https://discord.gg/AVtgkcRgFs"><abbr style="text-decoration: none" title="You can register a meganation or an alliance here">ℹ️</abbr></a>`
}
currentMapModeLabel.innerHTML = currentMapModeLabel.textContent.replace('{currentMapMode}', currentMapModeText)
}
function decreaseBrightness(isChecked) {
const element = document.querySelector('.leaflet-tile-pane')
localStorage['emcdynmapplus-darkened'] = isChecked
element.style.filter = (isChecked) ? 'brightness(50%)' : ''
}
function toggleCacheArchives(isChecked) {
localStorage['emcdynmapplus-cache-archives'] = isChecked
}
function switchMapMode() {
const nextMapMode = {
meganations: 'alliances',
alliances: 'default',
default: 'meganations'
}
localStorage['emcdynmapplus-mapmode'] = nextMapMode[currentMapMode] ?? 'meganations'
location.reload()
}
function addPlayerList() {
waitForHTMLelement('#players').then(() => {
const playerList = document.getElementById('players')
const mapElement = document.getElementById('map')
mapElement.appendChild(playerList)
playerList.addEventListener('wheel', (event) => {event.stopImmediatePropagation()})
})
addElement(document.body, htmlCode.followingPlayer, '#followingWarning')
}
function init() {
// injectMainScript() - for extension only
// Initialize some variables
localStorage['emcdynmapplus-mapmode'] = localStorage['emcdynmapplus-mapmode'] ?? 'meganations'
localStorage['emcdynmapplus-darkened'] = localStorage['emcdynmapplus-darkened'] ?? true
waitForHTMLelement('.leaflet-tile-pane').then(() => {
if (localStorage['emcdynmapplus-darkened'] == 'true') decreaseBrightness(true)
})
waitForHTMLelement('.leaflet-top.leaflet-left').then(element => {
addMainMenu(element)
checkForUpdateUserscript(element) // For userscript
})
if (localStorage['emcdynmapplus-darkmode'] == 'true') loadDarkMode()
// Fix nameplates appearing over popups
waitForHTMLelement('.leaflet-nameplate-pane').then(element => element.style = '')
addPlayerList()
waitForHTMLelement('#sidebar').then(element => element.remove())
firstTimeMessage()
tick()
// For extension only
// checkForUpdate()
}
function firstTimeMessage() {
if (!localStorage['emcdynmapplus-first-time']) {
const threadURL = 'https://discord.com/channels/219863747248914433/1047061595861286912'
sendMessage(`The extension's maintainers aren't affiliated with EarthMC and responsible for archiving maps.
Please keep in mind, that the extension may temporarily render unusable due to unexpected EarthMC
or third-party updates. If that was the case, the maintainers would address potential problems
sooner or later likely through the communications channel on
<a target="_blank" href="${threadURL}">EarthMC Discord thread</a>.`)
localStorage['emcdynmapplus-first-time'] = 'false'
}
}
function tick() {
const isFollowingPlayer = document.querySelector('.following') != null
document.querySelector('#followingWarning').style.display = isFollowingPlayer ? 'unset' : 'none'
requestAnimationFrame(tick)
}
function loadDarkMode() {
document.head.insertAdjacentHTML('beforeend',
`<style id="dark-mode">
.leaflet-control, #message-box, #prompt-box, .sidebar-input,
.sidebar-button, .leaflet-bar > a, .leaflet-tooltip-top,
.leaflet-popup-content-wrapper, .leaflet-popup-tip,
.leaflet-bar > a.leaflet-disabled {
background: #111;
color: #bbb;
box-shadow: 0 0 2px 1px #bbb;
}
div.leaflet-control-layers.link img {
filter: invert(1);
}</style>`
)
}
function toggleDarkMode(isChecked) {
if (isChecked) {
localStorage['emcdynmapplus-darkmode'] = true
loadDarkMode()
}
else {
localStorage['emcdynmapplus-darkmode'] = false
document.querySelector('#dark-mode').remove()
waitForHTMLelement('.leaflet-map-pane').then(element => element.style.filter = '')
}
}
function locate(selectValue, inputValue) {
if (!isNostra) return sendMessage(`Can't locate in this world.`)
switch (selectValue) {
case 'Town': locateTown(inputValue); break
case 'Nation': locateNation(inputValue); break
case 'Resident': locateResident(inputValue); break
}
}
// For extension only
// function checkForUpdate()
function addOptions(sidebar) {
const optionsButton = addElement(sidebar, htmlCode.buttons.options, '#options-button')
const optionsMenu = addElement(sidebar, htmlCode.options.menu, '#options-menu')
optionsMenu.style.display = 'none'
optionsButton.addEventListener('click', () => {
optionsMenu.style.display = (optionsMenu.style.display == 'none') ? 'unset' : 'none'
})
const checkbox = {
decreaseBrightness: addOption(0, 'decrease-brightness', 'Decrease brightness', 'darkened'),
darkMode: addOption(1, 'toggle-darkmode', 'Toggle dark mode', 'darkmode'),
cacheArchives: addOption(2, 'cache-archives', `<abbr title="Save archive mode snapshots in your browser's Origin Private File System for its instant load upon next time. One cache weighs a few MBs.">Cache archives</abbr>`, 'cache-archives')
}
// Archive mode world
const archiveModeWorld = addElement(optionsMenu, htmlCode.options.option, '.option', true)[3]
archiveModeWorld.insertAdjacentHTML('beforeend', htmlCode.options.label
.replace('{option}', 'archive-mode-world')
.replace('{optionName}', '<abbr title="Load archived townchunks snapshots from the selected world. Towns will only be properly overlayed in Terra Nostra snapshots.">Archive mode world</abbr>'))
archiveModeWorld.style.display = 'unset'
const select = addElement(archiveModeWorld, htmlCode.options.archiveWorldMode, '#archive-mode-world')
select.addEventListener('change', event => {
localStorage['emcdynmapplus-archive-mode-world'] = select.value
updateArchiveInput()
})
checkbox.decreaseBrightness.addEventListener('change', event => decreaseBrightness(event.target.checked))
checkbox.darkMode.addEventListener('change', event => toggleDarkMode(event.target.checked))
checkbox.cacheArchives.addEventListener('change', event => toggleCacheArchives(event.target.checked))
updateArchiveInput()
}
const worldDates = {
'Classic': { min: '2017-09-06', max: '2018-07-07' },
'Terra Nova': { min: '2018-12-17', max: '2024-06-17' },
'Terra Aurora': { min: '2022-05-01', max: '2026-04-12' },
'Terra Nostra': { min: '2026-04-17', max: new Date().toLocaleDateString('en-ca') }
}
function updateArchiveInput() {
const archiveModeWorldVariable = localStorage['emcdynmapplus-archive-mode-world'] ?? 'Terra Nostra'
const archiveInput = document.querySelector('#archive-input')
const config = worldDates[archiveModeWorldVariable]
archiveInput.min = config.min
archiveInput.max = config.max
}
function searchArchive(date) {
if (date == '') return
const URLDate = date.replaceAll('-', '')
localStorage['emcdynmapplus-archive-date'] = URLDate
localStorage['emcdynmapplus-mapmode'] = 'archive'
location.reload()
}
function addLocateMenu(sidebar) {
const locateMenu = addElement(sidebar, htmlCode.sidebarOption, '.sidebar-option', true)[0]
locateMenu.id = 'locate-menu'
const locateButton = addElement(locateMenu, htmlCode.buttons.locate, '#locate-button')
const locateSubmenu = addElement(locateMenu, htmlCode.sidebarOption, '.sidebar-option')
const locateSelect = addElement(locateSubmenu, htmlCode.locateSelect, '#locate-select')
const locateInput = addElement(locateSubmenu, htmlCode.locateInput, '#locate-input')
locateSelect.addEventListener('change', () => {
switch (locateSelect.value) {
case 'Town': locateInput.placeholder = 'London'; break
case 'Nation': locateInput.placeholder = 'Germany'; break
case 'Resident': locateInput.placeholder = 'Notch'; break
}
})
locateInput.addEventListener('keyup', event => {
if (event.key != 'Enter') return
locate(locateSelect.value, locateInput.value)
})
locateButton.addEventListener('click', () => {
locate(locateSelect.value, locateInput.value)
})
}
function addOption(index, optionId, optionName, variable) {
const optionsMenu = document.querySelector('#options-menu')
const option = addElement(optionsMenu, htmlCode.options.option, '.option', true)[index]
option.insertAdjacentHTML('beforeend', htmlCode.options.label
.replace('{option}', optionId)
.replace('{optionName}', optionName))
const checkbox = addElement(option, htmlCode.options.checkbox.replace('{option}', optionId), '#' + optionId)
checkbox.checked = (localStorage['emcdynmapplus-' + variable] == 'true')
return checkbox
}
async function locateTown(town) {
town = town.trim().toLowerCase()
if (town == '') return
const coords = await getTownSpawn(town)
if (coords == false) return sendMessage('Searched town has not been found.')
if (coords == null) return sendMessage('Service is currently unavailable, please try later.')
location.href = `https://map.earthmc.net/?zoom=4&x=${coords.x}&z=${coords.z}`
}
async function locateNation(nation) {
nation = nation.trim().toLowerCase()
if (nation == '') return
if (currentMapMode == 'archive') {
return sendMessage(`Can't search for archived nations. Exit archive mode to proceed.`)
}
const query = { query: [nation], template: { capital: true } }
const data = await fetchJSON(apiURL + '/nations', {method: 'POST', body: JSON.stringify(query)})
if (!data.ok) return sendMessage('Service is currently unavailable, please try later.')
if (!data.data) return sendMessage('Searched nation has not been found.')
let capital
try { capital = data.data[0].capital.name }
catch { return sendMessage('Searched nation has not been found.') }
const coords = await getTownSpawn(capital)
if (coords == false) return sendMessage('Unexpected error occurred while searching for nation, please try later.')
if (coords == null) return sendMessage('Service is currently unavailable, please try later.')
location.href = `https://map.earthmc.net/?zoom=4&x=${coords.x}&z=${coords.z}`
}
async function locateResident(resident) {
resident = resident.trim().toLowerCase()
if (resident == '') return
if (currentMapMode == 'archive') {
return sendMessage(`Can't search for archived residents. Exit archive mode to proceed.`)
}
const query = { query: [resident], template: { town: true } }
const data = await fetchJSON(apiURL + '/players', {method: 'POST', body: JSON.stringify(query)})
if (!data.ok) return sendMessage('Service is currently unavailable, please try later.')
try {
const town = data.data[0].town.name
const coords = await getTownSpawn(town)
if (coords == false) return sendMessage('Unexpected error occurred while searching for resident, please try later.')
if (coords == null) return sendMessage('Service is currently unavailable, please try later.')
location.href = `https://map.earthmc.net/?zoom=4&x=${coords.x}&z=${coords.z}`
} catch {
return sendMessage(`The searched resident is townless or they opted out of being looked up.`)
}
}
async function getTownSpawn(town) {
// Archive mode works with towns only
if (currentMapMode == 'archive') {
markersURL = getArchiveURL()
let archive = await fetchJSON(proxyURL + markersURL)
if (!archive.ok) return null
if (!archive.data) return false
archive = {data: [{markers: []}]}
if (chosenArchiveDate < 20200322) {
archive.data[0].markers = convertOldMarkersStructure(archive.data.sets['towny.markerset'])
} else if (chosenArchiveDate < 20240623) {
archive.data[0].markers = convertOldMarkersStructure(archive.data.sets['townyPlugin.markerset'])
}
let townObject = archive.data[0].markers.find(el => el.popup.toLowerCase().includes(`>${town} (`))
if (!townObject) return false
let points = townObject.points.flat(Infinity)
let coords = { x: points[0].x, z: points[0].z }
return coords
}
const query = { query: [town], template: { coordinates: true } }
const data = await fetchJSON(apiURL + '/towns', {method: 'POST', body: JSON.stringify(query)})
if (!data.ok) return null
try { return { x: Math.round(data.data[0].coordinates.spawn.x), z: Math.round(data.data[0].coordinates.spawn.z) } }
catch { return false }
}
// main.js
const { fetch: originalFetch } = unsafeWindow
// Make this function work in userscript
unsafeWindow.lookupPlayerFunc = lookupPlayer
const alliancesURLworld = isNostra? 'nostra' : 'aurora'
const alliancesURL = `https://emcstats.bot.nu/${alliancesURLworld}/alliances`
const serverMap = {
'Classic': 'classic',
'Terra Nova': 'nova',
'Terra Aurora': 'aurora',
'Terra Nostra': 'nostra'
}
const server = serverMap[localStorage['emcdynmapplus-archive-mode-world']]
let alliances = null
if (currentMapMode != 'default' && currentMapMode != 'archive') getAlliances().then(result => alliances = result)
// Clickable player nameplates
waitForHTMLelement('.leaflet-nameplate-pane').then(element => {
element.addEventListener('click', event => {
const username = event.target.textContent || event.target.parentElement.parentElement.textContent
if (username.length > 0) lookupPlayer(username, false)
})
})
function modifySettings(data) {
data['player_tracker'].nameplates['show_heads'] = true
data['player_tracker'].nameplates['heads_url'] = 'https://mc-heads.net/avatar/{uuid}/16'
data.zoom.def = 0
data.spawn = { x: 2000, z: -10000 } // Set camera on Europe
if (currentMapMode == 'archive') data['player_tracker'].enabled = false
return data
}
function roundTo16(number) {
return Math.round(number / 16) * 16
}
// Fowler-Noll-Vo hash function
function hashCode(string) {
let hexValue = 0x811c9dc5
for (let i = 0; i < string.length; i++) {
hexValue ^= string.charCodeAt(i)
hexValue += (hexValue << 1) + (hexValue << 4) + (hexValue << 7) + (hexValue << 8) + (hexValue << 24)
}
return '#' + ((hexValue >>> 0) % 16777216).toString(16).padStart(6, '0')
}
// Shoelace formula
function getArea(vertices) {
const n = vertices.length
let area = 0
// Data has imprecise coordinates; round vertices to 16
for (let i = 0; i < n; i++) {
const j = (i + 1) % n
area += roundTo16(vertices[i].x) * roundTo16(vertices[j].z)
area -= roundTo16(vertices[j].x) * roundTo16(vertices[i].z)
}
return (Math.abs(area) / 2) / (16 * 16)
}
// By James Halliday (substack)
function pointInPolygon(vertex, polygon) {
let x = vertex.x, z = vertex.z
let n = polygon.length
let inside = false
for (let i = 0, j = n - 1; i < n; j = i++ ) {
let xi = polygon[i].x
let zi = polygon[i].z
let xj = polygon[j].x
let zj = polygon[j].z
let intersect = ((zi > z) != (zj > z))
&& (x < (xj - xi) * (z - zi) / (zj - zi) + xi)
if (intersect) inside = !inside
}
return inside
}
// Modify town descriptions for archives
function modifyOldDescription(marker) {
// Gather some information
let membersTitle = marker.popup.match(/Members <span/) ? 'Members' : 'Associates'
let residents = marker.popup.match(`${membersTitle} <span style="font-weight:bold">(.*)<\/span><br \/>Flags`)?.[1]
const residentNum = residents?.split(', ')?.length || 0
const isCapital = marker.popup.match(/capital: true/) != null
const area = getArea(marker.points)
// Modify description
if (isCapital) marker.popup = marker.popup.replace('120%">', '120%">★ ')
if (chosenArchiveDate < 20220906) {
marker.popup = marker.popup.replace(/">hasUpkeep:.+?(?<=<br \/>)/, '; white-space:pre">')
}
else marker.popup = marker.popup.replace('">pvp:', '; white-space:pre">pvp:')
marker.popup = marker.popup.replace('Flags<br />', '<br>Flags<br>')
.replace('>pvp:', '>PVP allowed:')
.replace('>mobs:', '>Mob spawning:')
.replace('>public:', '>Public status:')
.replace('>explosion:', '>Explosions:	')
.replace('>fire:', '>Fire spread:	')
.replace(/<br \/>capital:.*<\/span>/, '</span>')
.replaceAll('true<', '	<span style="color:green">Yes</span><')
.replaceAll('false<', '	<span style="color:red">No</span><')
.replace(`${membersTitle} <span`, `${membersTitle} <b>[${residentNum}]</b> <span`)
if (area > 0) {
marker.popup = marker.popup
.replace(`</span><br /> ${membersTitle}`, `</span><br>Size<span style="font-weight:bold"> ${area} </span><br> ${membersTitle}`)
}
// Scrollable resident list
if (residentNum > 50) {
marker.popup = marker.popup
.replace(`<b>[${residentNum}]</b> <span style="font-weight:bold">`,
`<b>[${residentNum}]</b> <div id="scrollable-list"><span style="font-weight:bold">`)
.replace('<br>Flags', '</div><br>Flags')
}
return marker
}
function modifyDescription(marker) {
// Gather some information
const town = marker.tooltip.match(/<b>(.*)<\/b>/)[1]
const nation = marker.tooltip.match(/\(\b(?:Member|Capital)\b of (.*)\)\n/)?.[1]
const mayor = marker.popup.match(/Mayor: <b>(.*)<\/b>/)?.[1]
let councillors = marker.popup.match(/Councillors: <b>(.*)<\/b>/)?.[1].split(', ')
councillors = councillors.filter(councillor => councillor != 'None')
const residents = marker.popup.match(/<\/summary>\n \t(.*)\n \t<\/details>/)?.[1]
const residentNum = residents.split(', ').length
const isCapital = marker.tooltip.match(/\(Capital of (.*)\)/) != null
// Town's area
let area = 0
const iteratedRegions = []
if (marker.type == 'polygon') {
for (const regionVertices of marker.points[0]) {
// Exclude non-affiliated regions entirely inside town
if (iteratedRegions.length > 0) {
let isInsidePolygon = false
for (const vertex of regionVertices) {
for (const lastPolygon of iteratedRegions) {
if (pointInPolygon(vertex, lastPolygon)) isInsidePolygon = true
}
}
if (isInsidePolygon) area -= getArea(regionVertices)
else area += getArea(regionVertices)
}
else area += getArea(regionVertices)
iteratedRegions.push(regionVertices)
}
}
// Resident lists
const residentList = (currentMapMode == 'archive' || !isNostra) ? residents :
residents.split(', ').map(resident => htmlCode.residentClickable.replaceAll('{player}', resident)).join(', ')
const councillorList = (currentMapMode == 'archive' || !isNostra) ? councillors :
councillors.map(councillor => htmlCode.residentClickable.replaceAll('{player}', councillor)).join(', ')
// Modify resident list
if (residentNum > 50) {
marker.popup = marker.popup.replace(residents, htmlCode.scrollableResidentList.replace('{list}', residentList))
} else {
marker.popup = marker.popup.replace(residents + '\n', htmlCode.residentList.replace('{list}', residentList) + '\n')
}
if (currentMapMode != 'archive' && isNostra) {
marker.popup = marker.popup
.replace(/Mayor: <b>(.*)<\/b>/, `Mayor: <b>${htmlCode.residentClickable.replaceAll('{player}', mayor)}</b>`)
.replace(/Councillors: <b>(.*)<\/b>/, `Councillors: <b>${councillorList}</b>`)
}
// Names wrapped in angle brackets
const names = {
town: town.replaceAll('<', '<').replaceAll('>', '>'),
nation: nation?.replaceAll('<', '<').replaceAll('>', '>') ?? nation
}
marker.popup = marker.popup
.replace(town, names.town)
.replace(nation, names.nation)
.replace('</details>\n \t<br>', '</details>')
.replace('Councillors:', `Size: <b>${area} chunks</b><br/>Councillors:`)
.replace('<i>/town set board [msg]</i>', '<i></i>')
.replace('<i></i> \n <br>\n', '')
.replace('\n <i>', '\n <i style="overflow-wrap: break-word">')
.replace('Councillors: <b>None</b>\n\t<br>', '')
.replace('Size: <b>0 chunks</b><br/>', '')
.replaceAll('<b>false</b>', '<b><span style="color: red">No</span></b>')
.replaceAll('<b>true</b>', '<b><span style="color: green">Yes</span></b>')
if (isCapital) marker.popup = marker.popup
.replace('<span style="font-size:120%;">', '<span style="font-size: 120%">★ ')
// Modify tooltip
marker.tooltip = marker.tooltip
.replace('<i>/town set board [msg]</i>', '<i></i>')
.replace('<br>\n <i></i>', '')
.replace('\n <i>', '\n <i id="clamped-board">')
.replace(town, names.town)
.replace(nation, names.nation)
// 'Part of' label
if (currentMapMode == 'archive' || currentMapMode == 'default') return marker
const nationAlliances = getNationAlliances(nation)
if (nationAlliances.length > 0) {
const allianceList = nationAlliances.map(alliance => alliance.name).join(', ')
const partOfLabel = htmlCode.partOfLabel.replace('{allianceList}', allianceList)
marker.popup = marker.popup.replace('</span>\n', '</span></br>' + partOfLabel)
}
return marker
}
function getNationAlliances(nation) {
const nationAlliances = []
if (alliances == null) return nationAlliances
for (const alliance of alliances) {
if (!alliance.nations.includes(nation)) continue
if (alliance.type != currentMapMode) continue
if (alliance.colours.fill == '#undefined' || alliance.colours.outline == '#undefined') {
alliance.colours.fill = alliance.colours.outline = '#3fb4ff'
}
nationAlliances.push({name: alliance.name, colours: alliance.colours})
}
return nationAlliances
}
function colorTowns(marker) {
const nation = marker.tooltip.match(/\(\b(?:Member|Capital)\b of (.*)\)\n/)?.[1]
const mayor = marker.popup.match(/Mayor: <b>(.*)<\/b>/)?.[1]
const isRuin = (mayor.match(/NPC[0-9]+/) != null)
const nationHasDefaultColor = (marker.color == '#3fb4ff' && marker.fillColor == '#3fb4ff') // Default blue
// Universal properties for the map modes
if (currentMapMode == 'alliances') {
marker.fillColor = marker.color = '#000000'
marker.weight = 0.5
} else {
if (nationHasDefaultColor) {
marker.color = '#363636' // Dark gray
marker.fillColor = hashCode(nation) // Random color
}
else marker.color = '#89c500' // Default green
}
if (isRuin) return marker.fillColor = marker.color = '#000000'
// Properties for alliances
const nationAlliances = getNationAlliances(nation)
if (nationAlliances.length == 0) return marker
marker.weight = 1.5
marker.fillColor = nationAlliances[0].colours.fill
marker.color = nationAlliances[0].colours.outline
if (nationAlliances.length > 1) marker.weight = 0.5
return marker
}
function addChunksLayer(data) {
const chunkLines = []
for (let x = -33280; x <= 33088; x += 16) {
chunkLines.push([
{ x: x, z: -16640 },
{ x: x, z: +16512 },
{ x: x, z: -16640 }
])
}
for (let z = -16640; z <= 16512; z += 16) {
chunkLines.push([
{ x: -33280, z: z },
{ x: +33088, z: z },
{ x: -33280, z: z }
])
}
data.push({
hide: true,
name: 'Chunks',
control: true,
id: 'chunks',
markers: [{
weight: 0.33,
color: '#000000',
type: 'polyline',
points: chunkLines
}]
})
return data
}
async function main(data) {
// Create town layer if there isn't
if (!data.some(layer => layer.name == 'Territory')) {
data.unshift({
hide: true,
name: 'Territory',
control: true,
id: 'towny',
markers: []
})
}
if (currentMapMode == 'archive') {
const archiveData = await getArchive(data)
if (!archiveData.ok) return null
data = archiveData.data
}
if (!isNostra) data = addChunksLayer(data)
data = await addCountryLayer(data)
if (!data?.[0]?.markers?.length && !isNostra) {
sendMessage('Unexpected error occurred while loading the map, maybe EarthMC is down? Try again later.')
return data
}
for (let marker of data[0].markers) {
if (marker.type != 'polygon' && marker.type != 'icon') continue
marker = (currentMapMode != 'archive' || chosenArchiveDate >= 20240701)
? modifyDescription(marker) : modifyOldDescription(marker)
if (marker.type != 'polygon') continue
// Universal properties
marker.opacity = 1
marker.fillOpacity = 0.33
marker.weight = 1.5
if (currentMapMode == 'default' || currentMapMode == 'archive') continue
marker = colorTowns(marker)
}
return data
}
function millerProjection(z) {
// -16640 and 16508 are vertical bounds of old map (Plate Carree projection)
// Assume old map covers every latitude
// Convert old (Aurora) map's Z-coord to latitude
const latDeg = (z - -16640) * (90 - -90) / (16508 - -16640) + -90
const latRad = latDeg * (Math.PI / 180)
// 2.304 is a magic number from 5/4 * Math.asinh(Math.tan(4/5 * (90 * (Math.PI / 180))))
// 16574 is a mean average of old map vertical bounds
const multiplier = 16574 / 2.3034125433763912
// project from Plate Carree to Miller Cylindrical
// Adjust projection of north hemisphere
const northHemisphereFactor = 0.994
let millerOldZ = 5/4 * Math.asinh(Math.tan(4/5 * latRad)) * multiplier
if (millerOldZ < 0) millerOldZ *= northHemisphereFactor
// 33148 is height of old map
// 94704 is estimated height of new (Nostra) map if it wasn't cropped
const scale = 94704 / 33148
return millerOldZ * scale
}
async function addCountryLayer(data) {
// Download & cache
if (!await getOPFS('emcdynmapplus-borders')) {
const prompt = addElement(document.body, htmlCode.promptBox.replace('{message}', 'Downloading country borders...'), '#prompt-box')
const markersURL = 'https://web.archive.org/web/2024id_/https://earthmc.net/map/aurora/standalone/MySQL_markers.php?marker=_markers_/marker_earth.json'
const fetch = await fetchJSON(proxyURL + markersURL)
prompt.remove()
if (!fetch.ok || !fetch.data) {
sendMessage('Could not download optional country borders layer, you could try again later.')
return data
}
await saveToOPFS('emcdynmapplus-borders', JSON.stringify(fetch.data.sets['borders.Country Borders'].lines))
}
try {
// Assemble
const points = []
const countries = JSON.parse(await getOPFS('emcdynmapplus-borders'))
for (const line of Object.values(countries)) {
const linePoints = []
for (const x in line.x) {
if (isNaN(parseInt(line.x[x]))) continue
// Hand-picked constants
// 1.94 is how many times Nostra map horizontally bigger is than Aurora's
// 382.5 is to how much to move layer to right by
// 8175 ... same as above but move down
// 1.0015 is a horizontal adjustment for Aurora map
let newCoords
if (isNostra) {
newCoords = {
x: line.x[x] * 1.94133 + 382.5,
z: millerProjection(line.z[x]) + 8175
}
} else {
newCoords = {
x: line.x[x] * 1.0015,
z: line.z[x]
}
}
linePoints.push(newCoords)
}
points.push(linePoints)
}
// Create
data.push({
hide: true,
name: 'Country Borders',
control: true,
id: 'borders',
order: 999,
markers: [{
weight: 1,
color: '#ffffff',
type: 'polyline',
points: points
}]
})
return data
} catch (error) {
sendMessage(`Could not set up a layer of country borders. You may need to clear this website's data.`)
return data
}
}
async function lookupPlayer(player, showOnlineStatus = true) {
if (document.querySelector('#player-lookup') != null) document.querySelector('#player-lookup').remove()
if (document.querySelector('#player-lookup-loading') != null) document.querySelector('#player-lookup-loading').remove()
const loading = addElement(document.querySelector('.leaflet-top.leaflet-left'), htmlCode.playerLookupLoading, '#player-lookup-loading')
const query = { query: [player] }
const data = await fetchJSON(apiURL + '/players', { method: 'POST', body: JSON.stringify(query) })
if (!data.ok) {
document.querySelector('#player-lookup-loading').remove()
return sendMessage('Service is currently unavailable, please try later.')
}
if (!data.data[0]) {
document.querySelector('#player-lookup-loading').remove()
return sendMessage(`This player opted out of being looked up.`)
}
loading.remove()
const lookup = addElement(document.querySelector('.leaflet-top.leaflet-left'), htmlCode.playerLookup, '#player-lookup')
// Populate with placeholders
lookup.insertAdjacentHTML('beforeend', '{show-online-status}<br>')
lookup.insertAdjacentHTML('beforeend', '<img id="player-lookup-avatar"/>')
lookup.insertAdjacentHTML('beforeend', '<center><b id="player-lookup-name">{player}</b>{about}</center>')
lookup.insertAdjacentHTML('beforeend', '<hr>{town}{nation}')
lookup.insertAdjacentHTML('beforeend', 'Rank: <b>{rank}</b><br>')
lookup.insertAdjacentHTML('beforeend', 'Balance: <b>{balance} gold</b><br>')
lookup.insertAdjacentHTML('beforeend', '{last-online}')
lookup.insertAdjacentHTML('beforeend', '<span class="close-container">×</span>')
// Gather data
const isOnline = data.data[0].status.isOnline
const balance = data.data[0].stats.balance
const town = data.data[0].town.name
const nation = data.data[0].nation.name
const lastOnline = new Date(data.data[0].timestamps.lastOnline).toLocaleDateString('fr')
let onlineStatus = '<span id="player-lookup-online" style="color: {online-color}">{online}</span>'
const about = (!data.data[0].about || data.data[0].about == '/res set about [msg]') ? '' : `<br><i>${data.data[0].about}</i>`
let rank = 'Townless'
if (data.data[0].status.hasTown) rank = 'Resident'
if (data.data[0].ranks.townRanks.includes('Councillor')) rank = 'Councillor'
if (data.data[0].status.isMayor) rank = 'Mayor'
if (data.data[0].ranks.nationRanks.includes('Chancellor')) rank = 'Chancellor'
if (data.data[0].status.isKing) rank = 'Leader'
// Modify HTML
const playerAvatarURL = 'https://mc-heads.net/avatar/' + data.data[0].uuid.replaceAll('-', '')
document.querySelector('#player-lookup-avatar').setAttribute('src', playerAvatarURL)
lookup.innerHTML = lookup.innerHTML
.replace('{player}', player)
.replace('{about}', about)
.replace('{show-online-status}', showOnlineStatus ? onlineStatus : '')
.replace('{online-color}', isOnline ? 'green' : 'red')
.replace('{online}', isOnline ? '⚫︎ Online' : '○ Offline')
.replace('{town}', town ? `Town: <b>${town}</b><br>` : '')
.replace('{nation}', nation ? `Nation: <b>${nation}</b><br>` : '')
.replace('{rank}', rank)
.replace('{balance}', balance)
.replace('{last-online}', !isOnline ? `Last online: <b>${lastOnline}</b><br>` : '')
lookup.querySelector('.close-container').addEventListener('click', event => { event.target.parentElement.remove() })
// Enable scrolling the about section
lookup.querySelector('center > i')?.addEventListener('wheel', (event) => {event.stopImmediatePropagation()})
}
async function getAlliances() {
const response = await fetchJSON(alliancesURL)
if (!response.ok || !response.data) {
try {
const cache = JSON.parse(localStorage['emcdynmapplus-alliances'])
if (response.code != 429) { // 429 = too many requests, ignore
sendMessage('Service responsible for loading alliances is currently unavailable, but locally-cached data will be used.')
}
return cache
} catch (e) {
sendMessage('Service responsible for loading alliances will be available later.')
return []
}
}
const alliances = response.data
function getAllianceByName(name) {
return alliances.find(it => it.identifier == name)
}
function findRoot(alliance, isFirstSearch = true) {
if (!alliance.parentAlliance) return (isFirstSearch) ? null : alliance
return findRoot(getAllianceByName(alliance.parentAlliance), false)
}
const nationList = new Map()
const finalArray = []
for (const alliance of alliances) {
const rootName = findRoot(alliance)?.identifier || alliance.identifier
nationList.set(rootName, [...nationList.get(rootName) || [], alliance.ownNations].flat())
}