forked from inexorabletash/travellermap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.js
More file actions
2418 lines (2114 loc) · 70.5 KB
/
map.js
File metadata and controls
2418 lines (2114 loc) · 70.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export class Util {
/**
* Element selector shorthand.
* @param {string} s
* @returns {any}
*/
static $(s) {
return document.querySelector(s);
}
/**
* Element selector shorthand for multiple elements.
* @param {string} s
* @returns {any[]}
*/
static $$(s) {
return Array.from(document.querySelectorAll(s));
}
/**
* Constructs a URL by appending query parameters to a base URL.
* Existing query parameters on the base URL are discarded.
* Relative URLs are resolved against the current page (`location.href`).
*
* @param {string|URL|Location} base - The base URL. May be absolute,
* root-relative, or page-relative.
* @param {Object.<string,
* string|number|boolean|Array.<string|number|boolean>>} [params] - Query
* parameters to append. Null/undefined values are skipped.
* @returns {string} The constructed URL with query parameters.
*
* @example
* makeURL('./print/route', { scale: 2, layer: ['A', 'B'] });
* // => './print/route?scale=2&layer=A&layer=B' (resolved absolute URL)
*/
static makeURL(base, params) {
const url = new URL(String(base), location.href);
url.search = '';
if (params) {
const searchParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value == null)
continue;
for (const v of (Array.isArray(value) ? value : [value])) {
searchParams.append(key, String(v));
}
}
url.search = searchParams.toString();
}
return url.toString();
}
// Replace with URL/searchParams
static parseURLQuery(url) {
const o = Object.create(null);
if (url.search && url.search.length > 1) {
for (const pair of url.search.substring(1).split('&')) {
if (!pair)
continue;
const kv = pair.split('=', 2);
if (kv.length === 2)
o[kv[0]] = decodeURIComponent(kv[1].replace(/\+/g, ' '));
else
o[kv[0]] = true;
}
}
return o;
}
static escapeHTML(s) {
return String(s).replace(/[&<>"']/g, c => {
switch (c) {
case '&':
return '&';
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case '\'':
return ''';
default:
return c;
}
});
}
static once(func) {
let run = false;
return /** @this {unknown} */ function() {
if (run)
return;
run = true;
func.apply(this, arguments);
};
}
/**
* Returns a debounced version of the provided function that delays until the
* sp;ecified time has elapsed since the last call.
* @param {function} func - The function to debounce.
* @param {number} delay - The delay in milliseconds to wait before invoking
* the function after the last call.
* @param {boolean} [immediate=false] - Whether to execute the function
* immediately on the leading edge instead of the trailing edge.
* @returns {function}
*/
static debounce(func, delay, immediate = false) {
let timeoutId = null;
/** @this {unknown} */
return function(...args) {
const callNow = immediate && !timeoutId;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timeoutId = null;
if (!immediate)
func.apply(this, args);
}, delay);
if (callNow)
func.apply(this, args);
};
}
static memoize(f) {
const cache = Object.create(null);
/** @this {unknown} */
return function() {
const key = JSON.stringify([].slice.call(arguments));
return (key in cache) ? cache[key] :
cache[key] = f.apply(this, arguments);
};
}
/**
* Fetches an image from the specified URL, returning a promise that resolves
* with an image element.
* @param {string} url
* @param {Object} [options]
* @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel the
* image request.
* @param {HTMLImageElement} [options.imageElement] - Optional existing image
* element to reuse.
* @returns {Promise<HTMLImageElement>} A promise that resolves with the
* loaded image.
*/
static fetchImage(url, options = {}) {
return new Promise((resolve, reject) => {
options.signal?.addEventListener('abort', () => {
img.src = '';
reject(new DOMException('Aborted', 'AbortError'));
});
const img = options.imageElement ?? document.createElement('img');
img.decoding = 'async';
img.src = url;
img.onload = () => {
resolve(img);
};
img.onerror = () => {
reject(Error('Image failed to load'));
};
});
}
/** @returns {object} */
static parseCookies() {
const cookies = {};
for (const pair of document.cookie.split(/; +/g)) {
const i = pair.indexOf('=');
if (i === -1)
cookies[''] = pair;
else
cookies[pair.substring(0, i)] = pair.substring(i + 1);
}
return cookies;
}
/** @returns {undefined} */
static copyTextToClipboard(text) {
const ta = document.createElement('textarea');
ta.value = text;
document.body.append(ta);
if (navigator.userAgent.match(/iPad|iPhone|iPod/)) {
ta.contentEditable = 'true';
ta.readOnly = true;
const range = document.createRange();
range.selectNodeContents(ta);
const sel = window.getSelection();
sel?.removeAllRanges();
sel?.addRange(range);
ta.setSelectionRange(0, text.length);
} else {
ta.select();
}
document.execCommand('copy');
ta.remove();
}
static fromHex(c) {
return '0123456789ABCDEFGHJKLMNPQRSTUVW'.indexOf(c.toUpperCase());
}
/**
* Parses a sector from tab-delimited data.
* @param {string} tabDelimitedData
* @returns {{ worlds: { [hex: string]: any } }} sector
*/
static parseSector(tabDelimitedData) {
const sector = {worlds: {}};
const lines = tabDelimitedData.split(/\r?\n/);
// @ts-ignore
const header = lines.shift().toLowerCase().split('\t').map(
h => h.replace(/[^a-z]/g, ''));
for (const line of lines) {
if (!line.length)
break;
const world = {};
for (const [index, field] of line.split('\t').entries()) {
world[header[index]] = field;
}
sector.worlds[world.hex] = world;
}
return sector;
}
}
//----------------------------------------------------------------------
// General Traveller stuff
//----------------------------------------------------------------------
const SERVICE_BASE = ((l) => {
if ((l.hostname === 'localhost' && l.pathname.indexOf('~') !== -1) ||
(l.protocol === 'file:'))
return 'https://travellermap.com';
return '';
})(window.location);
const LEGACY_STYLES = true;
//----------------------------------------------------------------------
// Enumerated types
//----------------------------------------------------------------------
export const MapOptions = {
SectorGrid: 0x0001,
SubsectorGrid: 0x0002,
GridMask: 0x0003,
SectorsSelected: 0x0004,
SectorsAll: 0x0008,
SectorsMask: 0x000c,
BordersMajor: 0x0010,
BordersMinor: 0x0020,
BordersMask: 0x0030,
NamesMajor: 0x0040,
NamesMinor: 0x0080,
NamesMask: 0x00c0,
WorldsCapitals: 0x0100,
WorldsHomeworlds: 0x0200,
WorldsMask: 0x0300,
RoutesSelectedDeprecated: 0x0400,
PrintStyleDeprecated: 0x0800,
CandyStyleDeprecated: 0x1000,
StyleMaskDeprecated: 0x1800,
ForceHexes: 0x2000,
WorldColors: 0x4000,
FilledBorders: 0x8000,
Mask: 0xffff
};
export const Styles = {
Poster: 'poster',
Atlas: 'atlas',
Print: 'print',
Candy: 'candy',
Draft: 'draft',
FASA: 'fasa'
};
//----------------------------------------------------------------------
// Astrometric Constants
//----------------------------------------------------------------------
export class Astrometrics {
static ParsecScaleX = Math.cos(Math.PI / 6); // cos(30)
static ParsecScaleY = 1.0;
static SectorWidth = 32;
static SectorHeight = 40;
static ReferenceHexX = 1; // Reference is at Core 0140
static ReferenceHexY = 40;
static TileWidth = 256;
static TileHeight = 256;
static MinScale = 0.0078125;
static MaxScale = 512;
static HexEdge = Math.tan(Math.PI / 6) / 4 / Math.cos(Math.PI / 6);
// World-space: Hex coordinate, centered on Reference
static sectorHexToWorld(sx, sy, hx, hy) {
return {
x: (sx * this.SectorWidth) + hx - this.ReferenceHexX,
y: (sy * this.SectorHeight) + hy - this.ReferenceHexY
};
}
static worldToSectorHex(x, y) {
x += this.ReferenceHexX - 1;
y += this.ReferenceHexY - 1;
const sx = Math.floor(x / this.SectorWidth);
const sy = Math.floor(y / this.SectorHeight);
const hx = (x - (sx * this.SectorWidth) + 1);
const hy = (y - (sy * this.SectorHeight) + 1);
return {sx: sx, sy: sy, hx: hx, hy: hy};
}
// Map-space: Cartesian coordinates, centered on Reference
static sectorHexToMap(sx, sy, hx, hy) {
const world = this.sectorHexToWorld(sx, sy, hx, hy);
return this.worldToMap(world.x, world.y);
}
static worldToMap(wx, wy) {
let x = wx;
let y = wy;
// Offset from the "corner of the hex
x -= 0.5;
y -= ((wx % 2) !== 0) ? 0 : 0.5;
// Scale to non-homogenous coordinates
x *= this.ParsecScaleX;
y *= -this.ParsecScaleY;
// Drop precision (avoid animations, etc)
x = Math.round(x * 1000) / 1000;
y = Math.round(y * 1000) / 1000;
return {x, y};
}
static mapToWorld(x, y) {
const wx = Math.round((x / this.ParsecScaleX) + 0.5);
const wy =
Math.round((-y / this.ParsecScaleY) + ((wx % 2 === 0) ? 0.5 : 0));
return {x: wx, y: wy};
}
// World-space Coordinates (Reference is 0,0)
static hexDistance(ax, ay, bx, by) {
function even(x) {
return (x % 2) == 0;
}
function odd(x) {
return (x % 2) != 0;
}
const dx = bx - ax;
const dy = by - ay;
let adx = Math.abs(dx);
let ody = dy + Math.floor(adx / 2);
if (even(ax) && odd(bx))
ody += 1;
return Math.max(adx - ody, ody, adx);
}
};
const Defaults = {
options: MapOptions.SectorGrid | MapOptions.SubsectorGrid |
MapOptions.SectorsSelected | MapOptions.BordersMajor |
MapOptions.BordersMinor | MapOptions.NamesMajor |
MapOptions.WorldsCapitals | MapOptions.WorldsHomeworlds,
scale: 2,
style: Styles.Poster
};
const STYLE_DEFAULTS = {
overlay_color: '#8080ff',
route_color: '#048104',
main_s_color: 'pink',
main_m_color: '#FFCC00',
main_l_color: 'cyan',
main_opacity: 0.25,
ew_color: '#FFCC00',
you_are_here_url: 'res/ui/youarehere.svg',
};
const STYLE_SHEETS = new Map([
[Styles.Poster, STYLE_DEFAULTS],
[Styles.Candy, STYLE_DEFAULTS],
[Styles.Draft, STYLE_DEFAULTS],
[
Styles.Atlas, {
...STYLE_DEFAULTS,
overlay_color: '#808080',
you_are_here_url: 'res/ui/youarehere-gray.svg'
}
],
[
Styles.FASA,
{...STYLE_DEFAULTS, you_are_here_url: 'res/ui/youarehere-gray.svg'}
],
[
Styles.Print,
{...STYLE_DEFAULTS, you_are_here_url: 'res/ui/youarehere-gray.svg'}
],
]);
function styleLookup(style, property) {
const sheet = STYLE_SHEETS.get(style) ?? STYLE_SHEETS.get(Defaults.style) ??
STYLE_DEFAULTS;
return sheet[property];
}
// ======================================================================
// Data Services
// ======================================================================
export class MapService {
// Internal abort controllers for each service function
static #abortControllers = {};
static #getAbortController(key) {
if (this.#abortControllers[key]) {
this.#abortControllers[key].abort();
}
this.#abortControllers[key] = new AbortController();
return this.#abortControllers[key];
}
/**
* Generic service function to make HTTP requests. If options.abortKey and
* options.signal are provided, will use an abortSignal.
* @param {string} url - The URL to send the request to.
* @param {Object} [options] - Optional parameters for the request.
* @param {string} [options.method] - HTTP method (default: 'GET')
* @param {string} [options.accept] - Optional Accept ContentType header value
* to specify the desired response format. Defaults to 'application/json'.
* @param {string} [options.abortKey] - Optional key when provided will
* automatically abort when a new request is made with the same key.
* @param {AbortController} [options.abortController] - Optional
* AbortController to cancel the request.
* @returns {Promise<any>} The response data, parsed as JSON if the response
* is application/json, or as text otherwise.
*/
static async #service(url, options = {}) {
let signal = undefined;
let abortController;
if (options.abortKey !== undefined && options.abortKey !== null) {
abortController =
options.abortController ?? this.#getAbortController(options.abortKey);
} else {
abortController = options.abortController;
}
if (abortController) {
signal = abortController.signal;
}
const accept = options.accept ?? 'application/json';
const response = await fetch(
url,
{method: options.method ?? 'GET', headers: {Accept: accept}, signal});
if (!response.ok)
throw new Error(response.statusText);
return (accept === 'application/json') ? await response.json() :
await response.text();
}
static #makeServiceUrl(path, options = {}) {
// remove non-query parameters from options without mutating options object
const {signal, method, accept, abortKey, abortController, ...queryOptions} =
options;
return Util.makeURL(SERVICE_BASE + path, queryOptions);
}
static makeURL(path, options = {}) {
return this.#makeServiceUrl(path, options);
}
static coordinates(sector, hex, options = {}) {
const urlOptions = {...options, sector, hex};
const url = this.#makeServiceUrl('/api/coordinates', urlOptions);
options.accept = options.accept ?? 'application/json';
return this.#service(url, options);
}
/**
* Fetch the credits for the world at the specified coordinates.
* @param {number} worldX - The X coordinate of the world.
* @param {number} worldY - The Y coordinate of the world.
* @param {string} milieu - The milieu context for the credits request.
* @param {Object} [options] - Optional parameters for the request.
* @param {string} [options.method] - HTTP method (default: 'GET')
* @param {string} [options.accept] - Optional Accept ContentType header value
* to specify the desired response format. Defaults to 'application/json'.
* @param {string} [options.abortKey] - Optional key when provided will
* automatically abort when a new request is made with the same key.
* @param {AbortController} [options.abortController] - Optional
* AbortController to cancel the request.
* @returns {any} The credits data, parsed as JSON if the response is
* application/json, or as text otherwise.
*/
static credits(worldX, worldY, milieu, options = {}) {
const urlOptions = {...options, x: worldX, y: worldY, milieu};
const url = this.#makeServiceUrl('/api/credits', urlOptions);
return this.#service(url, options);
}
static search(query, milieu, options = {}) {
const urlOptions = {...options, q: query, milieu};
const url = this.#makeServiceUrl('/api/search', urlOptions);
return this.#service(url, options);
}
static sectorData(sector, options = {}) {
const urlOptions = {...options, sector};
const url = this.#makeServiceUrl('/api/sec', urlOptions);
return this.#service(url, options);
}
static sectorDataTabDelimited(sector, options = {}) {
const urlOptions = {...options, sector, type: 'TabDelimited'};
const url = this.#makeServiceUrl('/api/sec', urlOptions);
options.accept = options.accept ?? 'text/plain';
return this.#service(url, options);
}
static sectorMetaData(sector, options = {}) {
const urlOptions = {...options, sector};
const url = this.#makeServiceUrl('/api/metadata', urlOptions);
return this.#service(url, options);
}
static MSEC(sector, options = {}) {
const urlOptions = {...options, sector};
const url = this.#makeServiceUrl('/api/msec', urlOptions);
options.accept = options.accept ?? 'text/plain';
return this.#service(url, options);
}
static universe(options = {}) {
const urlOptions = {...options};
const url = this.#makeServiceUrl('/api/universe', urlOptions);
return this.#service(url, options);
}
}
// ======================================================================
// Least-Recently-Used Cache
// ======================================================================
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.map = {};
this.queue = [];
}
ensureCapacity(capacity) {
if (this.capacity < capacity)
this.capacity = capacity;
}
clear() {
this.map = {};
this.queue = [];
}
fetch(key) {
key = '$' + key;
const value = this.map[key];
if (value === undefined)
return undefined;
const index = this.queue.indexOf(key);
if (index !== -1)
this.queue.splice(index, 1);
this.queue.push(key);
return value;
}
insert(key, value) {
key = '$' + key;
// Remove previous instances
const index = this.queue.indexOf(key);
if (index !== -1)
this.queue.splice(index, 1);
this.map[key] = value;
this.queue.push(key);
while (this.queue.length > this.capacity) {
key = this.queue.shift();
delete this.map[key];
}
}
}
// ======================================================================
// Image Stash
// ======================================================================
class ImageStash {
constructor() {
this.map = new Map();
}
get(url, callback) {
if (this.map.has(url))
return this.map.get(url);
this.map.set(url, undefined);
Util.fetchImage(url).then(img => {
this.map.set(url, img);
callback(img);
});
return undefined;
}
}
const stash = new ImageStash();
// ======================================================================
// Animation Utilities
// ======================================================================
function isCallable(o) {
return typeof o === 'function';
}
class Animation {
/**
* Creates an animation that runs for a specified duration and optionally
* applies a smoothing function to the animation progress. set onanimate to
* function called with animation position (0.0 ... 1.0)
* @param {number} dur - The total duration of the animation in seconds.
* @param {Function} smooth - An optional smoothing function that takes a
* position (0.0 to 1.0) and returns a modified position for easing
* effects.
*/
constructor(dur, smooth) {
const start = Date.now();
this.onanimate = null;
this.oncancel = null;
this.oncomplete = null;
const tickFunc = () => {
const f = (Date.now() - start) / 1000 / dur;
if (f < 1.0)
this.timerid = requestAnimationFrame(tickFunc);
let p = f;
if (isCallable(smooth))
p = smooth(p);
if (isCallable(this.onanimate))
this.onanimate(p);
if (f >= 1.0 && isCallable(this.oncomplete))
this.oncomplete();
};
this.timerid = requestAnimationFrame(tickFunc);
}
cancel() {
if (this.timerid) {
cancelAnimationFrame(this.timerid);
if (isCallable(this.oncancel))
this.oncancel();
}
}
/**
* @param {number} a
* @param {number} b
* @param {number} p
* @return {number}
*/
static interpolate(a, b, p) {
return a * (1.0 - p) + b * p;
}
/**
* Time smoothing function - input time is t within duration dur.
* Acceleration period is a, deceleration period is d.
* Reference: http://www.w3.org/TR/2005/REC-SMIL2-20050107/smil-timemanip.html
* @usage t_filtered = Animation.smooth( t, 1.0, 0.25, 0.25 );
* @param {number} t
* @param {number} dur
* @param {number} a
* @param {number} d
* @return {number}
*/
static smooth(t, dur, a, d) {
const dacc = dur * a;
const ddec = dur * d;
const r = 1 / (1 - a / 2 - d / 2);
let r_t, tdec, pd;
if (t < dacc) {
r_t = r * (t / dacc);
return t * r_t / 2;
} else if (t <= (dur - ddec)) {
return r * (t - dacc / 2);
} else {
tdec = t - (dur - ddec);
pd = tdec / ddec;
return r * (dur - dacc / 2 - ddec + tdec * (2 - pd) / 2);
}
}
}
// ======================================================================
// Observable name/value map
// ======================================================================
class NamedOptions {
/** @type {string[]} */
NAMES = [];
constructor(notify) {
this._options = {};
this._notify = notify;
}
keys() {
return Object.keys(this._options);
}
get(key) {
return this._options[key];
}
set(key, value) {
this._options[key] = value;
this._notify(key);
}
delete(key) {
delete this._options[key];
this._notify(key);
}
/**
* Iterates over each key/value pair in the options, invoking the provided
* callback function with the value, key, and index as arguments.
* @param {function} fn
* @param {any} thisArg
*/
forEach(fn, thisArg = undefined) {
const keys = Object.keys(this._options);
for (let i = 0; i < keys.length; ++i) {
const k = keys[i];
fn.call(thisArg, this._options[k], k, i);
}
}
}
//----------------------------------------------------------------------
//
// Usage:
//
// let map = new Map( document.getElementById('YourMapDiv') );
//
// map.onPositionChanged = () => { update permalink }
// map.onScaleChanged = () => { update scale indicator }
// map.onStyleChanged = () => { update control panel }
// map.onOptionsChanged = () => { update control panel }
//
// map.onHover = ( {x, y} ) => { show data }
// map.onClick = ( {x, y} ) => { show data }
// map.onDoubleClick = ( {x, y} ) => { show data }
//
// Read-Only:
// map.worldX
// map.worldY
//
// Read/Write:
// map.x
// map.y
// map.position ~= [map.x, map.y]
// map.scale
// map.style
// map.options
//
// map.namedOptions
// .keys()
// .get(k)
// .set(k, v)
// .delete(k)
// .forEach((value, key, index) => { ... });
//
// map.CenterAtSectorHex( sx, sy, hx, hy, {scale, immediate} );
// map.Scroll( dx, dy, fAnimate );
// map.ZoomIn();
// map.ZoomOut();
//
// map.ApplyURLParameters()
//
// map.SetRoute()
// map.AddMarker(id, x, y, opt_url); // should have CSS style for .marker#<id>
// map.AddOverlay({type:'rectangle', x, y, w, h}); // should have CSS style
// for .overlay map.AddOverlay({type:'circle', x, y, r}); // should have CSS
// style for .overlay
//
//----------------------------------------------------------------------
// ======================================================================
// Slippy Map using Tiles
// ======================================================================
/**
* @param {number} v
*/
function log2(v) {
return Math.log(v) / Math.LN2;
}
/**
* @param {number} v
*/
function pow2(v) {
return Math.pow(2, v);
}
/**
* @param {number} x
* @param {number} y
*/
function dist(x, y) {
return Math.sqrt(x * x + y * y);
}
const SINK_OFFSET = 1000;
const INT_OPTIONS = [
'routes', 'rifts', 'dimunofficial', 'sscoords', 'allhexes', 'dw', 'an', 'mh',
'po', 'im', 'cp', 'stellar'
];
const STRING_OPTIONS = ['ew', 'qz', 'as', 'hw', 'milieu'];
const ZOOM_DELTA = 0.5;
function roundScale(s) {
return Math.round(s / ZOOM_DELTA) * ZOOM_DELTA;
}
export class TravellerMap {
constructor(container, boundingElement) {
this.container = container;
this.rect = boundingElement.getBoundingClientRect();
this.min_scale = -5;
this.max_scale = 10;
// Exposed via getters/setters
this._options = Defaults.options;
this._style = Defaults.style;
this._logScale = 1;
this._tx = 0;
this._ty = 0;
this.tilesize = 256;
this.cache = new LRUCache(64);
this.namedOptions = new NamedOptions(Util.debounce((key) => {
this.invalidate();
this._optionsChanged(this.options);
}, 1));
this.namedOptions.NAMES = INT_OPTIONS.concat(STRING_OPTIONS);
/**
* Batch tile load redraws to avoid thrashing on rapid tile loads
* @type {Function}
*/
this._tileLoadDebounce = Util.debounce(() => this.invalidate(), 10);
/**
* Active tile requests and their abortControllers, keyed by tile URL
* @type {Map<string, AbortController>}
*/
this._activeTileRequests = new Map();
this._maxConcurrentTileRequests = 8;
this._tileRequestTimeout = 30000; // 30 seconds
this.defer_loading = true;
const CLICK_SCALE_DELTA = -0.5;
const SCROLL_SCALE_DELTA = -0.15;
const KEY_SCROLL_DELTA = 15;
container.style.position = 'relative';
// Event target, so it doesn't change during refreshes
const sink = document.createElement('div');
sink.style.position = 'absolute';
sink.style.left = sink.style.top = sink.style.right = sink.style.bottom =
(-SINK_OFFSET) + 'px';
sink.style.zIndex = '1000';
container.appendChild(sink);
this.canvas = document.createElement('canvas');
this.canvas.style.position = 'absolute';
this.canvas.style.zIndex = '0';
container.appendChild(this.canvas);
this.ctx = this.canvas.getContext('2d');
if (!this.ctx) {
throw new Error(
'2D context not supported or canvas initialization failed.');
}
this.markers = [];
this.overlays = [];
/** @param {any[]|null} route */
this.route = null;
this.main = null;
// ======================================================================
// Event Handlers
// ======================================================================
// ----------------------------------------------------------------------
// Mouse
// ----------------------------------------------------------------------
let dragging, drag_coords, was_dragged, previous_focus;
container.addEventListener('mousedown', event => {
if (event.button !== 0)
return;
this.cancelAnimation();
previous_focus = document.activeElement;
container.focus();
dragging = true;
was_dragged = false;
drag_coords = this.eventCoords(event);
container.classList.add('dragging');
event.preventDefault();
event.stopPropagation();
}, true);
let hover_coords;
container.addEventListener('mousemove', event => {
const coords = this.eventCoords(event);
// Ignore mousemove immediately following mousedown with same coords.
if (dragging && coords.x === drag_coords.x && coords.y === drag_coords.y)
return;
if (dragging) {
was_dragged = true;
this._offset(drag_coords.x - coords.x, drag_coords.y - coords.y);
drag_coords = coords;
event.preventDefault();
event.stopPropagation();
}
const wc = this.eventToWorldCoords(event);
// Throttle the events
if (hover_coords && hover_coords.x === wc.x && hover_coords.y === wc.y)
return;
hover_coords = wc;
this._hovered(hover_coords);
}, true);
document.addEventListener('mouseup', event => {
if (event.button !== 0)
return;
if (dragging) {
dragging = false;
container.classList.remove('dragging');
event.preventDefault();
event.stopPropagation();
}
});
container.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
if (!was_dragged) {
this._clicked(
{...this.eventToWorldCoords(event), activeElement: previous_focus});
}
});
container.addEventListener('dblclick', event => {
event.preventDefault();
event.stopPropagation();
this.cancelAnimation();
const MAX_DOUBLECLICK_SCALE = 9;
if (this._logScale < MAX_DOUBLECLICK_SCALE) {
let newscale =
this._logScale + CLICK_SCALE_DELTA * (event.altKey ? 1 : -1);
newscale = Math.min(newscale, MAX_DOUBLECLICK_SCALE);
const coords = this.eventCoords(event);
this._setScale(newscale, coords.x, coords.y);
}