-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive.js
More file actions
1542 lines (1337 loc) · 51.2 KB
/
Copy pathinteractive.js
File metadata and controls
1542 lines (1337 loc) · 51.2 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
/*
* Retro Redrawn
* -- Interactive Script
*
* Backend operations of the Redrawn Viewer.
* Uses Implementation script for data related to a particular implementation.
*
* Dependencies: RedrawnArtistDataUtils.js, ArtistData.js (https://vulture-boy.github.io/Retro-Redrawn-Data/)
*
* Authors: Jerky, Tyson Moll (vvvvvvv)
*
* Contributors: dodocommando
*
* Created in 2023
*/
// Core
var app = null;
var loading = true; // Whether data is being loaded (e.g. images)
var layersLoaded = 0;
// Navigation
var zoomLevel = 1; // must be whole number
var zoomMin = 0.25;
var zoomMax = 4;
var currentZoom = 1; //lerp
var zoomCenter = {x: 0, y: 0}; // must be whole numbers
var currentPos = {x: 0, y: 0}; //lerp
// URL Args
const urlFocus = parseFocusFromUrl();
// Update layer if applicable
if (urlFocus&& urlFocus.layer) {
for (let i=0; i< redrawnLayers.length; i++) {
if (redrawnLayers[i].name === urlFocus.layer) {
activeLayerIndex = i;
break;
}
}
}
setActiveLayerDOM();
// Map
const NEW_STYLE_NAME = 'new';
const OLD_STYLE_NAME = 'old';
var activeAreas = redrawnLayers[activeLayerIndex].areas; // Active array of areas (and initial area)
var layerCount = redrawnLayers.length; // Total number of layers
var canvasDimensions = redrawnLayers[activeLayerIndex].canvasSize; // Dimension of active canvas
var map = null;
var mapbg; // Background for the map
var background; // Background behind the canvas
var mapImages = null;
var mapZones = null;
var currentMapStyle = NEW_STYLE_NAME;
var viewport = null;
var bordersDisabled = false;
var preferStaticImages = false; // When true, use .png versions even if animation is available
// Auto Highlight
var autoHighlightEnabled = true;
var highlightedArea = null;
// Filters
var blurFilter = null; // Motion blur used when zooming
var bulgeFilter = null;
var colorFilter = null; // Used for fade-to-black sequences (e.g. in tour mode)
// Interaction
var mouseDown = false;
var dragging = false;
var dragVelocity = { x: 0, y: 0 };
var zoomMousePos = { x: 0, y: 0 };
var previousTouch = null;
var previousPinchDistance = 0;
var pinchForTick = null;
// Track last pointer position so toasts can be shown at cursor location
var lastPointerPos = { x: 0, y: 0 };
// Capture pointerdown early so we have coordinates for inline onclick handlers
document.addEventListener('pointerdown', function (e) {
try {
lastPointerPos.x = e.clientX || (e.touches && e.touches[0] && e.touches[0].clientX) || 0;
lastPointerPos.y = e.clientY || (e.touches && e.touches[0] && e.touches[0].clientY) || 0;
} catch (ex) { }
}, {capture: true, passive: true});
// Tour
var tourMode = false;
var tourTransition = false;
var areasToTour = [];
var tourFadeTimer = 100;
// Camera movement
var _defaultCameraSpeed = 0.008;
var _defaultTourCameraSpeed = 0.002;
var cameraSpeed = _defaultCameraSpeed;
var tourCameraSpeed = _defaultTourCameraSpeed;
var cameraAnimation = {
speed: cameraSpeed,
playing: false,
progress: 0,
startPos: {x: 0, y:0 },
endPos: {x: 0, y: 0},
startZoom: 1,
endZoom: 1,
easing: true
}
// Layers
var layerNewImages = fillWithArrays(Array.apply(null, Array(layerCount))); // Array of length matching Layer Names
var layerOldImages = fillWithArrays(Array.apply(null, Array(layerCount)));
var redrawImages = [layerNewImages, layerOldImages];
var redrawsCount = redrawImages.length; // Total number of redraw layers
// Start up
loadImages()
window.addEventListener('wheel', onMouseWheel);
window.addEventListener('resize', onResize);
window.addEventListener('keydown', onKeyDown);
/** Loads new & old images pertaining to a single layer.
*
* @param {Array} areaArray Array of areas particular to a layer.
* @param {Array} areaImageArray Array of images tied to areas in a layer.
* @param {Array} areaOldImageArray Array of old versions of images tied to a layer.
* @param {string} layerSubfolder Subfolder directory name of the layer's new & old images.
*/
function loadLayer (areaArray, areaImageArray, areaOldImageArray, layerSubfolder) {
for (let i = 0; i < areaArray.length; i++)
{
var area = areaArray[i];
// Create and set up new image
var img = new Image();
areaImageArray.push(img); // Add to array before loading to maintain order
// Assign a function as the onload handler (don't call it immediately)
img.onload = function() { onAreaImageLoaded(areaImageArray); };
// Use GIF extension only when the area explicitly requests animation
var newExt = (area && area.animation) ? '.gif' : '.png'; // Use animated image?
img.src = createImageLink(layerSubfolder, NEW_STYLE_NAME, area.ident, NEW_SLICE_SUFFIX, newExt);
// Create and set up old image
var oldimg = new Image();
areaOldImageArray.push(oldimg); // Add to array before loading to maintain order
// Assign correct onload handler and pass the old-image array
oldimg.onload = function() { onAreaImageLoaded(areaOldImageArray); };
oldimg.src = createImageLink(layerSubfolder, OLD_STYLE_NAME, area.ident, OLD_SLICE_SUFFIX, '.png');
}
}
/** Produces an image link from area details. */
function createImageLink (layerName, mapStyle, areaName, mapSuffix) {
var link = `img/${layerName}/${mapStyle}/${areaName}`;
if (!(mapSuffix === undefined || mapSuffix === '')) {
link += mapSuffix;
}
// Default to .png unless an explicit extension is provided as the 5th argument
var extension = '.png';
if (arguments.length >= 5 && arguments[4]) {
extension = arguments[4];
}
link += extension;
return link;
}
/** Loads all new & old images pertaining to each layer */
function loadImages () {
for (let i = 0; i < layerCount; i++) {
// Need areas in the layer to load images
if (redrawnLayers[i].areas.length != 0) {
loadLayer(redrawnLayers[i].areas, layerNewImages[i], layerOldImages[i], redrawnLayers[i].name);
}
else {
redrawsCount -= 2; // Ignore & subtract from this var, otherwise will never finish loading.
// TODO: fix magic number reference
}
}
}
/** Callback triggered when an image is loaded; checks if images in the layer are done loading. */
function onAreaImageLoaded (areaImageArray) {
var loadedImages = areaImageArray.filter(x => x.complete).length
document.querySelector('.loading-bar__inner').style.width = `${(loadedImages / areaImageArray.length) * 100}%`
if (loadedImages === areaImageArray.length && loading) {
layersLoaded += 1;
if (layersLoaded >= redrawsCount) {
completeLoading();
}
}
}
/** Completes the loading process. */
function completeLoading () {
loading = false;
// Deactivate loading element
document.querySelector('#loading').classList.remove('active');
if (window.innerWidth < 768) { // Hide the menu if screen is not wide enough
toggleMenu();
}
init();
}
/** Initializes the canvas and its content. */
function init () {
// Construct the PIXI canvas with pixel perfect settings
try {
PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST // Nearest neighbour scaling
app = new PIXI.Application(
{
width: window.innerWidth,
height: window.innerHeight,
antialias: false,
view: document.querySelector('#canvas'),
autoResize: true
});
globalThis.__PIXI_APP__ = app;
} catch (error) {
// alert('Application cannot start - Please ensure Hardware Acceleration is enabled on your web browser.')
// document.querySelector('#error').innerHTML = '<p>Application cannot start - Please ensure Hardware Acceleration is enabled on your web browser.</p><a>View full image</a>'
document.querySelector('#error').innerHTML = '<p>Application cannot start - Please ensure Hardware Acceleration is enabled on your web browser.</p>'
document.querySelector('#error').classList.add('active')
}
// Prepare the canvas display
setupCanvas(true);
// Select & focus on a random area & open it in DOM
// Use URL-provided area if offered, otherwise random
var startingArea = activeAreas[Math.floor(Math.random() * activeAreas.length)]
if (urlFocus && urlFocus.ident) {
const areaToFocus = activeAreas.find(a => a.ident === urlFocus.ident);
if (areaToFocus) {
startingArea = areaToFocus;
}
}
focusOnArea(startingArea)
openAreaInDOM(startingArea)
// Advance an animation frame
requestAnimationFrame(tick)
}
/** Prepares the canvas display */
function setupCanvas (useDefaultPosition) {
app.stage.removeChildren()
// Establish PIXI containers
viewport = new PIXI.Container({width: window.innerWidth, height: window.innerHeight})
viewport.name = "Viewport"
map = new PIXI.Container()
map.name = "Map";
if (CANVAS_BACKGROUND_IMAGE !== '') {
mapbg = new PIXI.TilingSprite(new PIXI.Texture.from(CANVAS_BACKGROUND_IMAGE), canvasDimensions.width, canvasDimensions.height)
mapbg.name = "Map Background"
mapbg.zIndex = -1
map.addChild(mapbg)
}
mapImages = new PIXI.Container()
mapImages.name = "Map Images"
map.addChild(mapImages)
mapZones = new PIXI.Container()
mapZones.name = "Map Zones"
map.addChild(mapZones)
let oldx = currentPos.x;
let oldy = currentPos.y;
buildMap()
background = new PIXI.Graphics()
background.name = "Background Fill"
background.beginFill(WINDOW_BACKGROUND_COLOR)
background.drawRect(0,0,window.innerWidth, window.innerHeight)
background.endFill()
if (WINDOW_BACKGROUND_IMAGE !== '') {
background = new PIXI.TilingSprite(new PIXI.Texture.from(WINDOW_BACKGROUND_IMAGE), window.innerWidth, window.innerHeight)
}
viewport.addChild(background)
viewport.addChild(map)
app.stage.addChild(viewport)
map.interactive = true
viewport.interactive = true
// Establish navigation listeners
viewport.on('pointerdown', onDragStart)
viewport.on('pointerup', onDragEnd)
viewport.on('click', onClick)
viewport.on('pointerupoutside', onDragEnd)
viewport.on('pointermove', onDragMove)
setUpAreas()
// Prepare filters
blurFilter = new PIXI.filters.ZoomBlurFilter()
bulgeFilter = new PIXI.filters.BulgePinchFilter()
colorFilter = new PIXI.filters.AlphaFilter()
colorFilter.alpha = 1 // Start fully visible (transparent)
// Apply filters to viewport
viewport.filters = [colorFilter]
// Set default position/zoom
if (useDefaultPosition) {
map.scale.set(zoomMin)
map.x = -((map.width) - (window.innerWidth / 2)) * map.scale.x
map.y = -((map.height) - (window.innerHeight / 2)) * map.scale.x
currentPos.x = map.x
currentPos.y = map.y
zoomCenter.x = map.x
zoomCenter.y = map.y
}
else
{
map.scale.set(currentZoom)
map.x = oldx;
map.y = oldy;
currentPos.x = oldx;
currentPos.y = oldy;
zoomCenter.x = oldx;
zoomCenter.y = oldy;
}
}
function buildMap () {
// Properly stop/destroy any existing children (including GIF-backed objects) before clearing
while (mapImages.children[0]) {
var ch = mapImages.children[0];
try {
// If the object exposes a stop() or destroy() method, call it
if (typeof ch.stop === 'function') { try { ch.stop(); } catch (e) {} }
if (typeof ch.destroy === 'function') { try { ch.destroy({children:true, texture:true, baseTexture:true}); } catch (e) { ch.destroy && ch.destroy(); } }
// If we attached a GifPlayer, destroy it
try { cleanupDisplayObjectGif(ch); } catch (e) {}
} catch (e) {}
mapImages.removeChild(mapImages.children[0]);
}
for (let i = 0; i < activeAreas.length; i++) {
// Get area image and create a PIXI sprite. If the active image is a GIF (for new style
// with area.animation === true) we create a canvas-backed texture and update it each frame.
var area = activeAreas[i];
var activeImages = getActiveLayerAreaImages();
var areaImage = activeImages[i];
var sprite = null;
if (currentMapStyle === NEW_STYLE_NAME && area && area.animation && !preferStaticImages && areaImage && areaImage.src && areaImage.src.match(/\.gif$/i)) {
sprite = createCanvasGifSprite(area, areaImage);
} else {
// Fallback: use the normal texture path
var src = createImageLink(redrawnLayers[activeLayerIndex].name, currentMapStyle, area.ident);
sprite = new PIXI.Sprite.from(src);
}
sprite.name = `AREA: ${redrawnLayers[activeLayerIndex].name} (${currentMapStyle}) - ${area.ident}`;
// Apply offset to new versions (always relative to old versions)
if (currentMapStyle === NEW_STYLE_NAME) {
sprite.position.set(area.point.x + area.offset.x, area.point.y + area.offset.y)
} else {
sprite.position.set(area.point.x, area.point.y)
}
mapImages.addChild(sprite)
}
}
/** Switches between Old and New map styles */
function toggleMapStyle () {
var lastMapStyle = currentMapStyle;
if (currentMapStyle == NEW_STYLE_NAME)
{
currentMapStyle = OLD_STYLE_NAME;
}
else
{
currentMapStyle = NEW_STYLE_NAME;
}
// Build map if changed
if (!(lastMapStyle === currentMapStyle))
{
buildMap();
}
updateActiveAreaZone()
}
//** Fetches the current active layer's area images based on the current style */
function getActiveLayerAreaImages(styleOverride = "") {
// Use current style or override?
var style = styleOverride === "" ? currentMapStyle : styleOverride;
if (style === NEW_STYLE_NAME) {
return layerNewImages[activeLayerIndex];
}
if (style == OLD_STYLE_NAME) {
return layerOldImages[activeLayerIndex];
}
log.error("current map style not defined as new or old");
return null
}
/** Regenerates all area zones. */
function RegenerateAreaZones() {
if (!activeAreas) {
return
}
// Cleanup existing zones, if any.
for (let i = 0; i < mapZones.children.length; i++) {
var zone = mapZones.children[i];
zone.destroy();
}
mapZones.removeChildren();
// Generate new zones
for (let i = 0; i < activeAreas.length; i++) {
// Prepare PIXI area tile
var area = activeAreas[i];
var activeImages = getActiveLayerAreaImages();
var areaImage = activeImages[i];
generateAreaZone(area);
}
}
/** Prepares PIXI area tiles and their associated HTML artist information blocks. */
function setUpAreas () {
if (!activeAreas) {
return
}
// Query the areas list
var areaList = document.querySelector('#areas')
areaList.innerHTML = ''
RegenerateAreaZones();
// Loop through all active areas
for (let i = 0; i < activeAreas.length; i++) {
var area = activeAreas[i];
// Get biome data
var backgroundColor = 'rgb(0 0 0)';
var materialIcon = '';
for (let j=0; j< biomes.length; j++) {
let biome = biomes[j];
if (biome.ident === area.type) {
backgroundColor = biome.color;
materialIcon = biome.iconId;
break;
}
}
// Prep artist image HTML
var artistData = GetArtistData(area.artistId);
var artistName = artistData.name;
var artistUrl = artistData.url;
var artistImgPath = GetArtistImagePath(artistData);
var artistImageHTML = '';
if (!(artistImgPath === '')) {
artistImageHTML = artistUrl ? `<a href="${artistUrl}" target="_blank" title="${artistName}">
<img src="${artistImgPath}" alt="${artistName}" /></a>` : `<img src="${artistImgPath}" alt="${artistName}" />`;
}
var iconBlock =
`<span class="material-icons">
${materialIcon}
</span>`;
for (let k = 0; k< iconFiles.length; k++) {
if (iconFiles[k].iconId === materialIcon)
{
iconBlock = `<img src=${iconFiles[k].path} class="custom-icons">`;
k = iconFiles.length;
}
}
// Prepare the HTML block corresponding to an area and its associated credts
var html =
`<li class="area" title="${area.title}" style="background-color:${backgroundColor}" onclick="focusOnArea('${area.title}')">
<div class="area__header" >
${iconBlock}<span>${area.title}</span>
<button class="area__copy" title="Copy link" onclick="event.stopPropagation(); copyAreaLink('${redrawnLayers[activeLayerIndex].name}','${area.ident}')">🔗</button>
</div>
<div class="area__info">
<div class="area__info__inner">
<div class="area__info__img">
${artistImageHTML}
</div>
<div class="area__info__name">
${artistUrl ? `<a href="${artistUrl}" target="_blank" title="${artistName}">${artistName}</a>` : `<a>${artistName}</a>`}
${area.post_url ? `<a href="${area.post_url}" target="_blank" title="View Post">[View Post]</a>` : ''}
</div>
</div>
</div>
</li>`
areaList.innerHTML += html
}
}
// Copy area link to clipboard (uses current path + query params)
function copyAreaLink(layerName, areaIdent) {
var base;
try {
base = window.location.origin + window.location.pathname;
} catch (e) {
base = window.location.href.split('?')[0];
}
var url = base + `?layer=${encodeURIComponent(layerName)}&ident=${encodeURIComponent(areaIdent)}`;
// Use modern Clipboard API when available (requires HTTPS or localhost)
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
navigator.clipboard.writeText(url).then(function() {
showCopyToast('Link copied', lastPointerPos);
}).catch(function(err) {
CopyLinkPrompt(url);
});
return;
}
CopyLinkPrompt(url);
}
/**
* Fallback for older browsers: show prompt with URL for manual copy
*/
function CopyLinkPrompt(url) {
try { window.prompt('Copy this URL for a direct focus link!', url); } catch (e) { /* ignore */ }
}
/**
* Show a small floating toast near the given screen position (client coordinates).
* text: string to display
* pos: {x,y} client coordinates; if missing, defaults to center top
*/
function showCopyToast(text, pos) {
try {
var existing = document.querySelector('.copy-toast');
if (!existing) {
existing = document.createElement('div');
existing.className = 'copy-toast';
existing.style.position = 'fixed';
existing.style.pointerEvents = 'none';
existing.style.zIndex = 99999;
document.body.appendChild(existing);
}
existing.textContent = text || '';
// position
var x = (pos && pos.x) ? pos.x : (window.innerWidth / 2);
var y = (pos && pos.y) ? pos.y : 40;
existing.style.left = x + 'px';
existing.style.top = y + 'px';
existing.style.opacity = '1';
existing.classList.remove('copy-toast--hide');
// force reflow then allow hide
window.getComputedStyle(existing).opacity;
const showTime = 1200;
const hideTime = 1000;
setTimeout(function() {
existing.classList.add('copy-toast--hide');
}, showTime);
// remove after hide transition
clearTimeout(existing._copyToastTimeout);
existing._copyToastTimeout = setTimeout(function() {
try { existing.style.opacity = '0'; } catch (e) {}
}, hideTime);
} catch (e) {
// swallow
}
}
/** Creates a rectangular fill relative to a PIXIjs graphic (effectively its outline) */
function UpdateFill(graphic, areaBox) {
if (!bordersDisabled) { // Outline properties
graphic.beginFill(0xffffff, 0)
graphic.lineStyle(4, 0xffffff, 0.5, 1, false)
graphic.drawRect(areaBox.x, areaBox.y, areaBox.width, areaBox.height);
graphic.endFill()
}
}
/** Creates PIXI Graphics corresponding to new and old versions of an area. */
function generateAreaZone(area) {
if (!area) { console.error('oopsie, no area'); return }
var oldZone = new PIXI.Graphics();
oldZone.name = `ZONE: ${area.ident} (${OLD_STYLE_NAME})`;
var areaBox = getAreaBox(area, OLD_STYLE_NAME);
UpdateFill(oldZone, areaBox);
oldZone.alpha = 0;
area.old_zone = oldZone;
mapZones.addChild(oldZone);
var newZone = new PIXI.Graphics();
newZone.name = `ZONE: ${area.ident} (${NEW_STYLE_NAME})`;
areaBox = getAreaBox(area, NEW_STYLE_NAME);
UpdateFill(newZone, areaBox);
newZone.alpha = 0;
area.new_zone = newZone;
mapZones.addChild(newZone);
}
function hideAreaZone (area) {
if (!area) { console.error('oopsie, no area'); return }
area.old_zone.alpha = 0
area.new_zone.alpha = 0
}
function showAreaZone (area) {
if (!area) { console.error('oopsie, no area'); return }
if (currentMapStyle === NEW_STYLE_NAME) {
area.old_zone.alpha = 0
area.new_zone.alpha = 1
} else {
area.old_zone.alpha = 1
area.new_zone.alpha = 0
}
}
function updateActiveAreaZone () {
var activeArea = getActiveArea()
if (activeArea) {
showAreaZone(activeArea.obj)
}
}
/** Gets the position of an area's box,
* with an optional offset applied to 'redrawn' maps to accomodate bleeds and stylistic extensions.
*
* @param {*} area The struct describing the area.
* @param {*} areaImage The image used for this area.
* @param {string} styleOverride Forces the returned box dimensions to be based on a particular style, if defined.
* */
function getAreaBox (area, styleOverride = "") {
if (!area) { console.error('oopsie, no area'); return }
// Use current style or override?
var style = styleOverride === "" ? currentMapStyle : styleOverride;
if (style === NEW_STYLE_NAME) {
return {x: area.point.x + area.offset.x, y: area.point.y + area.offset.y, width: area.point.width + area.offset.width, height: area.point.height + area.offset.height}
} else {
return {x: area.point.x, y: area.point.y, width: area.point.width, height: area.point.height}
}
}
/** Gets the image associated with the provided area for the active layer. */
function getAreaImage(area, styleOverride = "") {
var activeImages = getActiveLayerAreaImages(styleOverride);
var imageIndex = activeAreas.indexOf(area);
return activeImages[imageIndex];
}
/** Actions peformed on update (each frame). */
function tick () {
let motion_blur_target = MOTIONBLUR_VIEWPORT ? viewport : map;
motion_blur_target.filters = []
if (cameraAnimation.progress >= 1) {
cameraAnimation.playing = false
cameraAdjustment.progress = 1;
}
if (!cameraAnimation.playing) {
if (zoomLevel !== currentZoom) {
if (!blurIsDisabled()) {
motion_blur_target.filters = [blurFilter]
}
currentZoom = lerp(currentZoom, zoomLevel, 0.2)
if (Math.abs(zoomLevel - currentZoom) < 0.005) { // Floating point rounding
currentZoom = zoomLevel
map.x = currentPos.x = zoomCenter.x;
map.y = currentPos.y = zoomCenter.y;
}
map.scale.set(currentZoom)
blurFilter.strength = .2 * (Math.abs((currentZoom - zoomLevel)) / zoomLevel)
blurFilter.center = [ zoomMousePos.x, zoomMousePos.y ]
}
if (!mouseDown && (dragVelocity.x !== 0 || dragVelocity.y !== 0)) {
if (dragVelocity.x !== 0) {
map.x += Math.round(dragVelocity.x)
dragVelocity.x = dragVelocity.x * .9
if (Math.abs(dragVelocity.x) < 1) { dragVelocity.x = 0 }
}
if (dragVelocity.y !== 0) {
map.y += Math.round(dragVelocity.y)
dragVelocity.y = dragVelocity.y * .9
if (Math.abs(dragVelocity.y) < 1) { dragVelocity.y = 0 }
}
currentZoom.x = zoomCenter.x = map.x
currentZoom.y = zoomCenter.y = map.y
} else if (!mouseDown && (currentPos.x !== zoomCenter.x || currentPos.y !== zoomCenter.y)) {
var newx = lerp(currentPos.x, zoomCenter.x, 0.2)
var newy = lerp(currentPos.y, zoomCenter.y, 0.2)
currentPos = { x: newx, y: newy }
map.x = currentPos.x
map.y = currentPos.y
}
if (pinchForTick) {
instantZoom(pinchForTick.factor, pinchForTick.x, pinchForTick.y)
if (map.scale.x < zoomMax && map.scale.x > zoomMin) {
if (!blurIsDisabled()) {
motion_blur_target.filters = [blurFilter]
}
blurFilter.strength = .1
blurFilter.center = [ pinchForTick.x, pinchForTick.y ]
}
pinchForTick = null
}
checkMapBoundaries()
checkAutoHighlight()
if (urlFocus && dragging) {
clearParamsFromUrl();
}
} else {
// Calculate position and scale changes relative to a camera animation adjustment
cameraAnimation.progress += cameraAnimation.speed
// cameraAnimation.progress = ((cameraAnimation.progress * 100) + (cameraAnimation.speed * 100)) / 100
var newScale = cameraAdjustment(cameraAnimation.startZoom, cameraAnimation.endZoom);
var newPosX = cameraAdjustment(cameraAnimation.startPos.x, cameraAnimation.endPos.x);
var newPosY = cameraAdjustment(cameraAnimation.startPos.y, cameraAnimation.endPos.y);
map.scale.set(newScale)
map.x = newPosX
map.y = newPosY
}
if (tourMode) {
if ((!cameraAnimation.playing || cameraAnimation.progress > (1 - (cameraAnimation.speed * 100))) && !tourTransition) {
tourTransition = true
tourFadeTimer = 100
}
if (tourTransition) {
tourFadeTimer--
colorFilter.alpha = tourFadeTimer / 100
// map.alpha = tourFadeTimer / 100
}
if (tourTransition && tourFadeTimer <= 0) {
tourFadeTimer = 0
colorFilter.alpha = 0
// map.alpha = 0
newTourArea()
tourTransition = false
}
if (!tourTransition && colorFilter.alpha < 1) {
tourFadeTimer++
colorFilter.alpha += .01
// map.alpha += .01
}
}
// Update any GIF-backed sprites by drawing the underlying <img> into their canvas and
// notifying PIXI that the base texture needs updating.
try {
if (mapImages && mapImages.children && mapImages.children.length) {
for (let mi = 0; mi < mapImages.children.length; mi++) {
let child = mapImages.children[mi];
if (!child) continue;
// If the canvas is animated by GifPlayer, just request PIXI to update its base texture
if (child._isGif && child._gifCanvas) {
try {
updateGifSprite(child);
} catch (e) {
// ignore per-frame draw errors
}
}
}
}
} catch (e) {
// ignore overall GIF update errors to avoid breaking the render loop
}
requestAnimationFrame(tick)
}
/** Calculate the current position of a camera adjustment. */
function cameraAdjustment(start, end) {
return start + ((end - start) *
(cameraAnimation.easing ? easeInOutCubic(cameraAnimation.progress) : cameraAnimation.progress) );
}
/** Toggles active state of the menu, focusing on the active area. */
function toggleMenu () {
var elem = document.querySelector('.menu')
elem.classList.toggle('active')
var activeArea = getActiveArea()
if (activeArea) {
openAreaInDOM(activeArea.obj)
}
}
/** Opens the menu. */
function openMenu () {
var elem = document.querySelector('.menu')
elem.classList.add('active')
var activeArea = getActiveArea()
showAreaZone(activeArea.obj)
}
/** Checks DOM if blur is disabled. */
function blurIsDisabled () {
return document.querySelector('#disableBlur').checked
}
/** Called when the area border visibility DOM is toggled.
*
* @param isHidden {Boolean} whether the border should be hidden.
*/
function onAreaBorderToggled(isHidden) {
bordersDisabled = isHidden;
RegenerateAreaZones();
}
/** Callback occurring when a drag action starts. */
function onDragStart () {
previousTouch = null
previousPinchDistance = 0
mouseDown = true
dragVelocity = { x: 0, y: 0 }
}
/** Callback occurring when a drag action ends. */
function onDragEnd () {
previousTouch = null
previousPinchDistance = 0
mouseDown = false
dragging = false
}
/** Changes a menu tab. */
function changeTab (n) {
var tabs = document.querySelectorAll('.menu__tab')
var elems = document.querySelectorAll('.menu__content >*')
for (let i = 0; i < tabs.length; i++) {
var tab = tabs[i]
tab.classList.remove('active')
elems[i].classList.remove('active')
}
elems[n].scrollTo(0,0); // Reset scroll
tabs[n].classList.add('active')
elems[n].classList.add('active')
// Focus on selected area if in the areas list
if (n === 0) {
const activeArea = elems[n].querySelector('.area.active');
if (activeArea) {
activeArea.scrollIntoView();
}
}
}
function onClick (e) {
if (!dragging && !cameraAnimation.playing) {
zoomCenter = { x: Math.round(-(e.data.global.x - map.x) + window.innerWidth / 2),
y: Math.round(-(e.data.global.y - map.y) + window.innerHeight / 2) }
currentPos = { x: map.x, y: map.y }
dragVelocity = { x: 0, y: 0 }
}
}
/** Callback occurring when a drag move occurs */
function onDragMove (e) {
if (mouseDown && !cameraAnimation.playing) {
if (e.data.originalEvent.type === 'touchmove' && e.data.originalEvent.touches && e.data.originalEvent.touches.length === 2) {
var touches = e.data.originalEvent.touches
var pinchX = touches[0].pageX - touches[1].pageX
var pinchY = touches[0].pageY - touches[1].pageY
var currentPinchDistance = Math.sqrt((pinchX * pinchX) + (pinchY * pinchY))
// console.log(currentPinchDistance, currentPinchDistance > previousPinchDistance ? 'Zoom In' : 'Zoom Out')
if (previousPinchDistance) {
var diff = Math.abs(currentPinchDistance - previousPinchDistance)
if (diff > 1) {
// Set x and y positions relative to pinch middle
if (currentPinchDistance > previousPinchDistance) { // Zoom / Pinch outwards
pinchForTick = {
factor: 1.06,
x: touches[0].pageX - (pinchX / 2),
y: touches[0].pageY - (pinchY / 2),
}
}
if (currentPinchDistance < previousPinchDistance) { // Zoom / Pinch inwards
pinchForTick = {
factor: .94,
x: touches[0].pageX - (pinchX / 2),
y: touches[0].pageY - (pinchY / 2),
}
}
}
}
previousPinchDistance = currentPinchDistance
}
dragging = true
var velocityX = 0
var velocityY = 0
if (e.data.originalEvent.type === 'touchmove') {
var touch = e.data.originalEvent.touches[0]
if (previousTouch && touch) {
velocityX = touch.pageX - previousTouch.pageX
velocityY = touch.pageY - previousTouch.pageY
}
previousTouch = touch || null
} else {
velocityX = e.data.originalEvent.movementX
velocityY = e.data.originalEvent.movementY
}
dragVelocity = { x: velocityX, y: velocityY }
map.x += dragVelocity.x
map.y += dragVelocity.y
zoomCenter = { x: map.x, y: map.y }
currentPos = zoomCenter
checkMapBoundaries()
}
}
/** Callback occurring when the mousewheel is rotated.
* (TODO: would like to support this functionality on the trackpad, too, if it doesn't already)
*
* @param {*} e Event data relating to the mouse wheel action.
*/
function onMouseWheel (e) {
if (e.target.id === 'canvas') {
zoomMousePos = { x: e.x, y: e.y }
if (!mouseDown && !cameraAnimation.playing) {
var zoomAmount = e.deltaY < 0 ? 2 : .5
if ((zoomLevel > zoomMin && e.deltaY > 0) || (zoomLevel < zoomMax && e.deltaY < 0)) {
currentPos = {...zoomCenter}
dragVelocity = { x: 0, y: 0 }
zoom(zoomAmount, e.x, e.y)
}
}
}
}
/** Prepare to zoom to a particular scale focused around a point. */
function zoom(s,x,y){
if (currentZoom !== zoomLevel) {
map.scale.set(zoomLevel);
currentZoom = zoomLevel
if (zoomCenter.x || zoomCenter.y) {
map.x = zoomCenter.x; map.y = zoomCenter.y;
}
}
var worldPos = {x: (x - zoomCenter.x) / zoomLevel, y: (y - zoomCenter.y)/zoomLevel};
var newScale = {x: zoomLevel * s, y: zoomLevel * s};
zoomLevel = newScale.x
checkZoomLimit()
var newScreenPos = {x: (worldPos.x ) * newScale.x + zoomCenter.x, y: (worldPos.y) * newScale.y + zoomCenter.y};
zoomCenter.x = zoomCenter.x - (newScreenPos.x-x)
zoomCenter.y = zoomCenter.y - (newScreenPos.y-y)
}
/**
* Immediately zoom to a particular scale focused around a point.
*/
function instantZoom(s,x,y){