-
Notifications
You must be signed in to change notification settings - Fork 4
/
sketch.js
executable file
·1278 lines (1157 loc) · 41 KB
/
sketch.js
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
"use strict";
// Peaks is an interactive web-visualization of Swiss mountain names. https://raphaelschaad.github.io/peaks/
// Copyright (c) 2016 Raphael Schaad
// {
// "id": "...",
// "type": "gipfel",
// "name": {
// "de": ["name1", "name2"],
// "fr": "name3"
// },
// "e": 1.23,
// "n": 4.56,
// "z": 7.89
// }
var dataFilepath = "data/peaks.min.json";
var topoFilepath = "data/ch-topo.min.json";
var data;
var topo;
var countryLines = [];
// Grid
// ncol, nrow
// margin.{top,bottom,left,right}
// gutter (width)
// DERRIVED: colwidth(), colheight(), rowheight()
var grid;
/*
// DEBUG stuff
var isLooping = true;
// stats.js -- click panel to cycle through stats
var stats = new Stats();
// 0: fps, 1: ms, 2: mb, 3+: custom
stats.showPanel(0);
*/
// See setup() data definition section for more notes on colors
var colors = {};
var keyColors = {};
var typeColors = {};
var shadowColorsForColors = {};
var hoverColorsForColors = {};
var backgroundColor;
var darkColor;
var borderColor;
var foregroundColor;
var disabledColor;
var pressedColor;
var highlightShadowColor;
// UI
var cursorPopupDiv;
// Animation
var previousTime;
var popupCycleDelay = 2 * 1000; // in ms
var popupCycleRemaining = popupCycleDelay;
var idleHoverNoiseVector;
var idleHoverDelay = 15 * 1000; // in ms
var idleHoverRemaining = idleHoverDelay;
// Peak highlight
var highlightedPeaks = [];
var highlightedPeakCurrentPopup;
// Head
var logotypeImage;
var bylineDiv;
var aboutDiv;
// Filters: Peak name language, type, altitude
var checkboxesForLangs;
var checkboxesForTypes;
var altitudeControl;
var showInFeetDiv;
var shouldShowInFeet = false;
var coloredPeaks;
// Story 1: Language Share of Peak Names
var languageShareTitleDiv;
var namesPerLanguageDiv;
var showPerSpeakersDiv;
var shouldShowPerSpeakers = false;
var languagesDivs = [];
// Story 2: Most Common Peak Names
var topNamesTitleDiv;
var topNamesDivs = [];
var secondColWidthMax = -Infinity;
// Story 3: Peak Name Origins
var nameOriginTitleDiv;
var nameOriginTextDiv;
// Scaling
var s;
var sMin = 1;
var sMax = 1.5;
function calcSize() {
s = map(windowWidth, 1280, 1920, sMin, sMax);
s = constrain(s, sMin, sMax);
return {w: round(1024*s), h: round(640*s)};
}
function windowResized() {
var size = calcSize();
resizeCanvas(size.w, size.h);
select("#centerContainer").size(width, height);
// Pre-project country line and pre-calculate length of altitude lines
mapCoord();
}
/*
* Setup
*/
function setup() {
var size = calcSize();
createCanvas(size.w, size.h).parent("centerContainer");
select("#centerContainer").size(width, height);
// Precalculate stuff
// Pre-project country line and pre-calculate length of altitude lines
mapCoord();
// Don't ever ever create p5 color() in draw() -- it's so expensive ... *(re)setting* color (stroke, fill) is surprisingly cheap.
// Use the keyColors for key (legend) and other UI elements
var keyColorIdx = 5;
var keyColorSaturationFactor = 0.9;
var keyColorBrightnessFactor = 0.6;
Object.keys(colorHexesForLangs).forEach(function(lang, idx, langs) {
var colorHexes = colorHexesForLangs[lang];
colors[lang] = colorHexes.map(function(colorHex) {
return color(colorHex);
});
var keyColor = colors[lang][keyColorIdx];
// HSB uses same values as Sketch.app. `%`-suffix is needed for S & B.
keyColor = color("hsba(" + round(hue(keyColor)) + ", " + round(saturation(keyColor) * keyColorSaturationFactor) + "%, " + round(brightness(keyColor) * keyColorBrightnessFactor) + "%, 1.0)");
keyColors[lang] = keyColor;
});
Object.keys(colorHexesForTypes).forEach(function(type, idx, types) {
typeColors[type] = color(colorHexesForTypes[type]);
});
for (lang in colors) {
var langColors = colors[lang];
for (var i = 0; i < langColors.length; i++) {
var col = langColors[i];
// Pre-calculate shadow colors
shadowColorsForColors[col] = color("hsba(" + round(hue(col)) + ", " + 6 + "%, " + 5 + "%, " + 0.25 + ")");
// Pre-calculate hover colors
hoverColorsForColors[col] = color("hsba(" + round(hue(col)) + ", " + round(saturation(col)) + "%, " + round(brightness(col)*0.64) + "%, " + 0.15 + ")");
}
}
// Other colors
backgroundColor = color("#171613");
darkColor = color("#050504");
borderColor = color("hsla(0, 0%, 0%, 0.333)");
foregroundColor = color("hsla(40, 8%, 100%, 0.45)");
disabledColor = color("#262522");
pressedColor = color("hsla(40, 10%, 100%, 0.2)");
highlightShadowColor = color("hsla(0, 0%, 0%, 0.5)");
// For display names, replace all spaces with non-breaking html entities
for (var i = 0; i < data.peaks.length; i++) {
var peak = data.peaks[i];
var langs = Object.keys(peak.name);
for (var j = 0; j < langs.length; j++) {
var lang = langs[j];
var names = peak.name[lang];
if (Array.isArray(names)) {
for (var k = 0; k < names.length; k++) {
var name = names[k];
peak.name[lang][k] = replaceSpacesWithNonBreaking(name);
}
} else {
var name = names;
peak.name[lang] = replaceSpacesWithNonBreaking(name);
}
}
}
for (var i = 0; i < data.topNames.length; i++) {
var nameCount = data.topNames[i];
var name = Object.keys(nameCount)[0];
var count = nameCount[name];
delete data.topNames[i][name];
name = replaceSpacesWithNonBreaking(name);
data.topNames[i][name] = count;
}
// Animation
// "use two different parts of the noise space, starting at 0 for x and 10,000 for y so that x and y can appear to act independently of each other" http://natureofcode.com/book/introduction/
idleHoverNoiseVector = createVector(0, 10000);
// Grid
grid = new Grid(16, // px, top margin
16, // px, bottom margin
16, // px, left margin
16, // px, right margin
4, // # columns
round(42*s), // px, gutter width
floor(28*(1+abs(s-1)/2)) // # rows -- scale but not to the full extend
);
// Hide by default
grid.togglevisibility();
grid.help.isvisible = false;
/*
// DEBUG stuff
if (!isLooping) {
noLoop();
}
document.body.appendChild(stats.domElement);
$("#peaks-about-modal").modal();
*/
}
/*
* Draw
*/
function draw() {
background(backgroundColor);
/*
// DEBUG stuff
grid.display();
fill("#ff7f7f");
noStroke();
text(nf(frameRate(), 2, 1), 10, 20);
stats.update();
*/
// Animation
if (previousTime === undefined) {
previousTime = millis();
}
var currentTime = millis();
var elapsedTime = currentTime - previousTime;
previousTime = currentTime;
// Logotype + byline + about
{
var yAdjustmentLogoType = 0;
var yAdjustmentByline = -5;
var imageScaleFactor = isRetina() ? 0.5 : 1.0;
image(logotypeImage, grid.margin.left, grid.margin.top + yAdjustmentLogoType, logotypeImage.width * imageScaleFactor, logotypeImage.height * imageScaleFactor);
if (!bylineDiv) {
var byline = "Explore the staggering amount of mapped and named peaks in the Swiss Alps. See how the four official languages contributed to the peaks’ names, and how a lesser-known language has a surprising reach. Can you discover high peaks, that can be seen from different regions, and hence have multiple names?";
bylineDiv = createDiv(byline).parent("centerContainer");
}
bylineDiv.size(grid.colwidth() + grid.gutter + grid.colwidth(), p5.AUTO);
bylineDiv.position(grid.margin.left + grid.colwidth() + grid.gutter, grid.margin.top + yAdjustmentByline);
if (!aboutDiv) {
var about = "Data from <a href=\"https://shop.swisstopo.admin.ch/en/products/landscape/names3D\" target=\"_blank\">swisstopo</a><br><a data-toggle=\"modal\" href=\"#peaks-about-modal\">About this visualization</a>";
aboutDiv = createDiv(about).class("about").parent("centerContainer");
}
var rightMargin = 60;
aboutDiv.size(grid.colwidth() - rightMargin, p5.AUTO);
aboutDiv.position(grid.margin.left + (grid.colwidth() + grid.gutter) * 3, grid.margin.top + yAdjustmentByline);
}
// Topo
// Simplyfing the geometry gives us a block aesthetic that is desired here to not distract from the texture of the peaks.
// PERFORMANCE: with pre-projecting and this level of simplification (gdal -> topojson [quantization 1e3, simplify-proportion 0.25] this takes ~<5fps.
{
noFill();
stroke(darkColor);
strokeWeight(2*s);
for (var i = 0; i < countryLines.length; i++) {
var lineSegments = countryLines[i];
beginShape();
for (var j = 0; j < lineSegments.length; j+=2) {
vertex(lineSegments[j], lineSegments[j+1]);
}
endShape();
}
}
// Peak Name Language Filter
{
strokeWeight(1.5);
strokeCap(SQUARE);
var yAdjustment = -round(9*s);
var x = grid.margin.left + (grid.colwidth() + grid.gutter) * 3;
var y = grid.margin.top + grid.rowheight() * (grid.nrow - 7) + yAdjustment;
var w = 30;
var h = 15;
var xRunning = x;
var leftMargin = 1;
var bottomMargin = 6;
if (!checkboxesForLangs) {
checkboxesForLangs = {};
for (var lang in namesForLangs) {
var name = namesForLangs[lang];
var div = createDiv(name.toUpperCase()).id(lang).parent("centerContainer");
div.class("peaks-label clickable rotated noselect");
div["hitRadius"] = max(w, h) / 2;
div["isChecked"] = true;
div.mouseClicked(function() {
toggleCheckbox(this);
});
checkboxesForLangs[lang] = div;
xRunning += w;
}
}
for (var lang in checkboxesForLangs) {
var checkbox = checkboxesForLangs[lang];
checkbox.position(xRunning+w/2+leftMargin, y-h-bottomMargin);
checkbox["center"] = createVector(xRunning+w/2, y-h/2);
fill(checkbox.isChecked ? keyColors[lang] : disabledColor);
// checkbox
stroke(borderColor);
triangle(xRunning, y, xRunning+w/2, y-h, xRunning+w, y);
// checkmark
if (checkbox.isChecked) {
noFill();
stroke(foregroundColor);
beginShape();
{
var p1 = createVector(xRunning+13, y-8);
vertex(p1.x, p1.y);
var p2 = createVector(xRunning+19, y-8);
var v = p5.Vector.sub(p2, p1);
v.rotate(radians(45));
vertex(p1.x+v.x, p1.y+v.y);
// Oddly, 90° doesn't look parallel
v.rotate(radians(-88));
v.setMag(checkbox.size().width + leftMargin + bottomMargin);
vertex(p2.x+v.x, p2.y+v.y);
}
endShape();
}
xRunning += w;
}
}
// Peak Type Filter
{
var yAdjustment = -3;
var x = grid.margin.left + (grid.colwidth() + grid.gutter) * 3;
var y = grid.margin.top + grid.rowheight() * (grid.nrow - 4) + yAdjustment;
var w = 50;
var h = 25;
var wDecrement = 10;
var hDecrement = 5;
var xOffset = 30;
var leftMargin = 1;
var bottomMargin = 6;
if (!checkboxesForTypes) {
checkboxesForTypes = {};
var types = Object.keys(namesForTypes).reverse();
for (var i = 0; i < types.length; i++) {
var type = types[i];
var name = namesForTypes[type];
var div = createDiv(name.toUpperCase()).id(type).parent("centerContainer");
div.class("peaks-label clickable rotated noselect");
div["hitRadius"] = max(w, h) / 2;
div["isChecked"] = true;
div.mouseClicked(function() {
toggleCheckbox(this);
});
checkboxesForTypes[type] = div;
x += xOffset;
w -= wDecrement;
h -= hDecrement;
}
}
for (var type in checkboxesForTypes) {
var checkbox = checkboxesForTypes[type];
checkbox.position(x+w/2+leftMargin, y-h-bottomMargin);
checkbox["center"] = createVector(x+w/2, y-h/2);
fill(checkbox.isChecked ? typeColors[type] : disabledColor);
// checkbox
stroke(borderColor);
triangle(x, y, x+w/2, y-h, x+w, y);
// checkmark
if (checkbox.isChecked) {
noFill();
stroke(foregroundColor);
beginShape();
{
var p1 = createVector(x+13, y-8);
vertex(p1.x, p1.y);
var p2 = createVector(x+19, y-8);
var v = p5.Vector.sub(p2, p1);
v.rotate(radians(45));
vertex(p1.x+v.x, p1.y+v.y);
// Oddly, 90° doesn't look parallel
v.rotate(radians(-88));
v.setMag(sqrt(pow(w/2 + leftMargin + checkbox.size().width, 2) + pow(h, 2))*0.85);
vertex(p2.x+v.x, p2.y+v.y);
}
endShape();
}
x += xOffset;
w -= wDecrement;
h -= hDecrement;
}
}
// Peak Altitude Filter
{
var yAdjustment = 5;
var x = grid.margin.left + (grid.colwidth() + grid.gutter) * 3;
var y = grid.margin.top + grid.rowheight() * (grid.nrow - 2) + yAdjustment;
var yRunning = y;
var w = 120;
var h = 2;
var knobWidth = 15;
var knobHeight = 10;
if (!altitudeControl) {
// Slight magic knob-related adjustments
altitudeControl = new RangeControl(w-knobWidth/2, h, knobWidth, knobHeight, data.zMin, data.zMax);
}
altitudeControl.x = x+knobWidth/2;
altitudeControl.y = y;
altitudeControl.display();
yRunning += knobHeight;
// SHOW IN FEET toggle
if (!showInFeetDiv) {
showInFeetDiv = createDiv().id("showInFeetDiv").parent("centerContainer");
showInFeetDiv.class("peaks-label clickable underlined noselect");
showInFeetDiv.mouseClicked(function() {
shouldShowInFeet = !shouldShowInFeet;
});
}
showInFeetDiv.html(shouldShowInFeet ? "SHOW IN METERS" : "SHOW IN FEET");
var topMargin = 10;
showInFeetDiv.position(x + w - showInFeetDiv.size().width + knobWidth/2, yRunning + topMargin);
}
// Peaks
{
if (cursorPopupDiv) {
cursorPopupDiv.hide();
}
noStroke();
// Has to be even (e.g. 4) for ellipse and stroke to perfectly line up
var diameter = 2*s;
strokeWeight(diameter);
var highlightShadowOffset = 1.5*s;
var hoverPeaks = [];
coloredPeaks = [];
var isHighlighting = false;
var interactionDistance = 36*s;
for (var i = 0; i < data.peaks.length; i++) {
var peak = data.peaks[i];
var type = peak.type;
var x = peak.x;
var y = peak.y;
var z = peak.z;
// Filters: Peak name language, type, altitude, and name
// A single peak can have names in multiple languages, and even per language multiple names.
// "name": {
// "de": ["name1", "name2"],
// "fr": "name3"
// },
var checkedLangs = [];
for (var lang in peak.name) {
if (checkboxesForLangs[lang].isChecked) {
checkedLangs.push(lang);
}
}
var shouldColor = (checkedLangs.length > 0);
shouldColor &= checkboxesForTypes[type].isChecked;
shouldColor &= (z >= altitudeControl.minValue() && z <= altitudeControl.maxValue());
if (shouldColor) {
// Here we simplify a bit and just grab the first language
var colorLang = colors[checkedLangs[0]];
var colorIndex = round(map(z, data.zMax, data.zMin, 0, colorLang.length - 1));
var col = colorLang[colorIndex];
// Associate value (for mouse interaction and idle animation)
peak["col"] = col;
// Highlight specific peaks
var shouldHighlight = false;
for (var j = 0; j < highlightedPeaks.length; j++) {
var highlightedPeak = highlightedPeaks[j];
if (peak.id === highlightedPeak.id) {
shouldHighlight = true;
break;
}
}
if (shouldHighlight) {
stroke(highlightShadowColor);
line(x-highlightShadowOffset, y-highlightShadowOffset, x-highlightShadowOffset, y-highlightShadowOffset - peak.length);
stroke(col);
line(x, y, x, y - peak.length);
noStroke();
isHighlighting = true;
}
// Mouse Interaction
// I investigated bulge effect and it looks cool but it then gets hard to point to a particular peak
var distance = dist(x, y, mouseX-2, mouseY-6);
if (distance < interactionDistance) {
// Associate value (for highlight)
peak["distance"] = distance;
hoverPeaks.push(peak);
}
coloredPeaks.push(peak);
} else {
col = darkColor;
}
fill(col);
ellipse(x, y, diameter, diameter);
// Moving from ellipse to point didn't improve performance
}
}
// To solve the problem of overlapping labels, cycle through popup one by one (use time)
if (isHighlighting) {
popupCycleRemaining -= elapsedTime;
if (popupCycleRemaining <= 0) {
popupCycleRemaining = popupCycleDelay;
var highlightedPeaksCurrentPopupIdx = highlightedPeaks.indexOf(highlightedPeakCurrentPopup);
highlightedPeaksCurrentPopupIdx = (highlightedPeaksCurrentPopupIdx + 1) % highlightedPeaks.length;
setHighlightedPeakCurrentPopupToFirstColoredPeak(highlightedPeaksCurrentPopupIdx);
}
if (highlightedPeakCurrentPopup) {
displayPopupForPeak(highlightedPeakCurrentPopup);
}
}
// Idle animation
if (isHighlighting === false && hoverPeaks.length === 0) {
// Count down
idleHoverRemaining -= elapsedTime;
if (idleHoverRemaining <= 0) {
// Steps of 0.005-0.03 work best for most applications
var noiseStep = 0.001;
idleHoverNoiseVector.x += noiseStep;
idleHoverNoiseVector.y += noiseStep;
// The resulting value will always be between 0.0 and 1.0.
var movementPadding = 100;
var idleHoverX = map(noise(idleHoverNoiseVector.x), 0, 1, round(peaksPadding.left*s)+movementPadding, width-round(peaksPadding.right*s)-movementPadding);
var idleHoverY = map(noise(idleHoverNoiseVector.y), 0, 1, round(peaksPadding.top*s)+movementPadding, height-round(peaksPadding.bottom*s)-movementPadding);
for (var i = 0; i < coloredPeaks.length; i++) {
var coloredPeak = coloredPeaks[i];
var distance = dist(coloredPeak.x, coloredPeak.y, idleHoverX, idleHoverY);
if (distance < interactionDistance) {
// Associate value (for highlight)
coloredPeak["distance"] = distance;
hoverPeaks.push(coloredPeak);
}
}
}
} else {
// Reset idle timer
idleHoverRemaining = idleHoverDelay;
}
// Highlight peak closest to mouse
if (hoverPeaks.length > 0) {
// First, draw translucent shadow lines for each line
strokeWeight(diameter * 1.5);
strokeCap(ROUND);
hoverPeaks.forEach(function(hoverPeak, index, hoverPeaks) {
var p1 = createVector(hoverPeak.x, hoverPeak.y);
var p2 = createVector(hoverPeak.x, hoverPeak.y - hoverPeak.length);
var v = p5.Vector.sub(p2, p1);
v.rotate(radians(-45));
v.mult(1.75);
stroke(shadowColorsForColors[hoverPeak.col]);
line(hoverPeak.x, hoverPeak.y, hoverPeak.x+v.x, hoverPeak.y+v.y);
});
// Draw "z-line from point origin "up" to show altitude
strokeWeight(diameter);
hoverPeaks.forEach(function(hoverPeak, index, hoverPeaks) {
stroke(hoverColorsForColors[hoverPeak.col]);
line(hoverPeak.x, hoverPeak.y, hoverPeak.x, hoverPeak.y - hoverPeak.length);
});
// Display name closest to mouse
hoverPeaks.sort(function(a, b) {
return a.distance - b.distance;
});
var closestPeak = hoverPeaks[0];
stroke(highlightShadowColor);
line(closestPeak.x-highlightShadowOffset, closestPeak.y-highlightShadowOffset, closestPeak.x-highlightShadowOffset, closestPeak.y-highlightShadowOffset - closestPeak.length);
stroke(closestPeak.col);
line(closestPeak.x, closestPeak.y, closestPeak.x, closestPeak.y - closestPeak.length);
strokeCap(SQUARE);
displayPopupForPeak(closestPeak);
}
var storiesStartRow = grid.nrow - 6;
var storyTitleYAdjustment = -12;
var rulerWidth = 1;
noStroke();
// Story 1: Language Share of Peak Names
{
var x = grid.margin.left;
var y = grid.margin.top + grid.rowheight() * storiesStartRow;
var yRunning = y;
if (!languageShareTitleDiv) {
languageShareTitleDiv = createDiv("Language Share of Peak Names").parent("centerContainer");
languageShareTitleDiv.class("storytitle");
}
languageShareTitleDiv.size(grid.colwidth(), p5.AUTO);
languageShareTitleDiv.position(x, y+storyTitleYAdjustment);
yRunning += grid.rowheight();
var labelsYAdjustment = 2;
// NAMES PER LANGUAGE label
if (!namesPerLanguageDiv) {
namesPerLanguageDiv = createDiv("NAMES PER LANGUAGE").parent("centerContainer");
namesPerLanguageDiv.class("peaks-label");
}
namesPerLanguageDiv.position(x, yRunning+labelsYAdjustment);
// SHOW PER SPEAKERS toggle
if (!showPerSpeakersDiv) {
showPerSpeakersDiv = createDiv().id("showPerSpeakersDiv").parent("centerContainer");
showPerSpeakersDiv.class("peaks-label clickable underlined noselect");
showPerSpeakersDiv.mouseClicked(function() {
shouldShowPerSpeakers = !shouldShowPerSpeakers;
// Reset idle timer
idleHoverRemaining = idleHoverDelay;
});
}
showPerSpeakersDiv.html(shouldShowPerSpeakers ? "SHOW ABSOLUTE" : "SHOW PER SPEAKERS");
showPerSpeakersDiv.position(x + grid.colwidth() - showPerSpeakersDiv.size().width, yRunning+labelsYAdjustment);
yRunning += grid.rowheight();
// Create divs with content
var langCounts = data.langCounts.slice(0);
if (languagesDivs.length === 0) {
for (var i = 0; i < langCounts.length; i++) {
var langCount = langCounts[i];
var lang = Object.keys(langCount)[0];
var count = langCount[lang];
var langName = namesForLangs[lang];
var speakerCount = speakersForLangs[lang];
var div = createDiv("<b>" + namesForLangs[lang] + "</b>").parent("centerContainer");
var langCountSpan = createSpan(" " + Number(count).toLocaleString());
langCountSpan.parent(div);
// Remember langCountSpan as property for easy access, couldn't make select() to work
div["langCountSpan"] = langCountSpan;
createSpan(Number(speakerCount).toLocaleString()).class("number safari_only_number").parent(div);
// Remember count and speakerCount for sorting and bar scaling
div["count"] = count;
div["speakerCount"] = speakerCount;
// Remember lang for bar coloring
div["lang"] = lang;
languagesDivs.push(div);
}
}
// Sort divs
languagesDivs.sort(function(a, b) {
if (shouldShowPerSpeakers) {
return (b.count / b.speakerCount) - (a.count / a.speakerCount);
} else {
return b.count - a.count;
}
});
// Lay divs out, update content, and render bar
var barWidthMax = grid.colwidth() / 2;
var barHeight = 3;
var firstCount = languagesDivs[0].count;
if (shouldShowPerSpeakers) {
firstCount /= languagesDivs[0].speakerCount;
}
for (var i = 0; i < languagesDivs.length; i++) {
var animating = false;
var div = languagesDivs[i];
div.size(grid.colwidth(), grid.rowheight());
// Pretty lame way of animating, but it does the job.
var yStep = 6;
var yCurrent = div.position().y;
var yTarget = round(yRunning);
var y = yCurrent;
var yDiff = yCurrent - yTarget;
// The height-check avoids animating in the very first loop
if (yCurrent !== height && abs(yDiff) >= yStep) {
// We have animation to do
y = yCurrent + (yDiff > 0 ? -yStep : yStep);
div["animating"] = true;
} else {
y = yTarget;
div["animating"] = false;
}
div.position(x, y);
// Do this once animation is over, not right away
if (!div.animating) {
if (shouldShowPerSpeakers) {
div.langCountSpan.hide();
} else {
// show() does "block", but we want "inline"
div.langCountSpan.style("display", "inline");
}
}
// Bar
var count = div.count;
if (shouldShowPerSpeakers) {
count /= div.speakerCount;
}
var barWidth = map(count, 0, firstCount, 0, barWidthMax);
var topMargin = 18;
fill(darkColor);
rect(x, y+topMargin, barWidthMax, barHeight);
fill(keyColors[div.lang]);
rect(x, y+topMargin, barWidth, barHeight);
yRunning += grid.rowheight();
}
}
// Story 2: Most Common Peak Names
{
var x = grid.margin.left + (grid.colwidth() + grid.gutter) * 1;
var y = grid.margin.top + grid.rowheight() * storiesStartRow;
var yRunning = y;
if (!topNamesTitleDiv) {
topNamesTitleDiv = createDiv("Most Common Peak Names").parent("centerContainer");
topNamesTitleDiv.class("storytitle");
}
topNamesTitleDiv.size(grid.colwidth(), p5.AUTO);
topNamesTitleDiv.position(x, y+storyTitleYAdjustment);
yRunning += grid.rowheight();
if (topNamesDivs.length === 0) {
for (var i = 0; i < data.topNames.length; i++) {
var nameCount = data.topNames[i];
var name = Object.keys(nameCount)[0];
var count = nameCount[name];
var div = createDiv("<b>" + name + "</b> " + count).id(name).parent("centerContainer");
// Needs a position so size().width is set
div.position(0, 0);
div.class("hoverable");
div.mouseOver(function() {
highlightedPeaks = peaksMatchingName(this.id());
updateHighlightedPeakCurrentPopup();
});
div.mouseOut(function() {
highlightedPeaks = [];
});
topNamesDivs.push(div);
if (i >= floor(data.topNames.length / 2)) {
secondColWidthMax = max(secondColWidthMax, div.size().width);
}
}
}
var xRunning = x;
for (var i = 0; i < topNamesDivs.length; i++) {
// Second col
if (i === floor(topNamesDivs.length / 2)) {
xRunning += grid.colwidth() - secondColWidthMax;
yRunning = y + grid.rowheight();
}
var div = topNamesDivs[i];
div.position(xRunning, yRunning);
yRunning += grid.rowheight();
}
}
// Story 3: Peak Name Origins
{
var x = grid.margin.left + (grid.colwidth() + grid.gutter) * 2;
var y = grid.margin.top + grid.rowheight() * storiesStartRow;
var yRunning = y;
if (!nameOriginTitleDiv) {
nameOriginTitleDiv = createDiv("Horns, Teeth, and Pyramids").parent("centerContainer");
nameOriginTitleDiv.class("storytitle");
}
nameOriginTitleDiv.size(grid.colwidth(), p5.AUTO);
nameOriginTitleDiv.position(x, y+storyTitleYAdjustment);
yRunning += grid.rowheight();
if (!nameOriginTextDiv) {
nameOriginTextDiv = createDiv("").parent("centerContainer");
nameOriginTextDiv.class("originstory");
// Color tags
var spanForColorName = {};
for (var colorName in aliasesForColorNames) {
var span = createSpan(colorName).id(colorName).parent("centerContainer");
span.class("tag hoverable");
span.mouseOver(function() {
highlightedPeaks.push.apply(highlightedPeaks, peaksContainingStrings(aliasesForColorNames[this.id()]));
updateHighlightedPeakCurrentPopup();
});
span.mouseOut(function() {
highlightedPeaks = [];
});
spanForColorName[colorName] = span;
}
createSpan("Mountain names often refer to their appearance in shape combined with themes like weather, time of day, or color. Common colors are ").parent(nameOriginTextDiv);
spanForColorName["white"].parent(nameOriginTextDiv);
createSpan(" for snow, ").parent(nameOriginTextDiv);
spanForColorName["red"].parent(nameOriginTextDiv);
createSpan(" for the sun at dawn or dusk, and ").parent(nameOriginTextDiv);
spanForColorName["black"].parent(nameOriginTextDiv);
createSpan(" for dark forest or rock.").parent(nameOriginTextDiv);
}
nameOriginTextDiv.size(grid.colwidth(), p5.AUTO);
nameOriginTextDiv.position(x, yRunning);
}
}
/*
* Cursor popup
*/
function displayPopupForPeak(peak) {
var displayNames = [];
var peakNameLangs = Object.keys(peak.name);
for (var i = 0; i < peakNameLangs.length; i++) {
var lang = peakNameLangs[i];
var names = peak.name[lang];
if (Array.isArray(names)) {
// We know there's only ever 2 names in the same language and so simplify a bit here (there's 7 such peaks btw.)
var name = names[0] + " (" + names[1] + ")";
displayNames.push("<b>" + name + "</b>");
} else {
var name = names;
if (peakNameLangs.length > 1) {
name = name + " <span style=\"color: " + keyColors[lang] + "; vertical-align: middle;\">•</span>";
}
displayNames.push("<b>" + name + "</b>");
}
}
displayNames[0] += " " + round(shouldShowInFeet ? peak.z / metersPerFoot : peak.z).toLocaleString() + altitudeUnitString();
if (!cursorPopupDiv) {
cursorPopupDiv = createDiv().parent("centerContainer");
cursorPopupDiv.class("cursorpopup noselect");
}
cursorPopupDiv.show();
cursorPopupDiv.html(displayNames.join("<br>"));
var bottomMargin = 22 + (peakNameLangs.length - 1) * 8;
cursorPopupDiv.position(peak.x, peak.y - peak.length - bottomMargin);
}
/*
* Altitude Slider
*/
function RangeControl(w, h, knobWidth, knobHeight, min, max) {
this.x = 0;
this.y = 0;
this.w = w;
this.h = h;
this.min = min;
this.max = max;
this.knobMin = new Knob(knobWidth, knobHeight, foregroundColor);
this.knobMax = new Knob(knobWidth, knobHeight, foregroundColor);
this.minTextDiv = createDiv().class("altitude rotated noselect").parent("centerContainer");
this.maxTextDiv = createDiv().class("altitude rotated noselect").parent("centerContainer");
this.display = function() {
// background line
noFill();
stroke(darkColor);
strokeWeight(this.h);
strokeCap(SQUARE);
line(this.x, this.y+this.h/2, this.x+this.w, this.y+this.h/2);
// highlight line
stroke(foregroundColor);
line(this.knobMax.x+this.knobMax.xOffset, this.y+this.h/2, this.knobMin.x+this.knobMin.xOffset, this.y+this.h/2);
// knobs
this.knobMin.x = this.x+this.w;
this.knobMin.y = this.y+this.h;
this.knobMin.display();
this.knobMax.x = this.x;
this.knobMax.y = this.y+this.h;
this.knobMax.display();
// text
this.minTextDiv.html(round(shouldShowInFeet ? this.minValue() / metersPerFoot : this.minValue()).toLocaleString() + altitudeUnitString());
this.maxTextDiv.html(round(shouldShowInFeet ? this.maxValue() / metersPerFoot : this.maxValue()).toLocaleString() + altitudeUnitString());
var xNudge = 6;
var bottomMargin = 14;
this.minTextDiv.position(this.knobMin.x+this.knobMin.xOffset - xNudge, this.knobMin.y - bottomMargin);
this.maxTextDiv.position(this.knobMax.x+this.knobMax.xOffset - xNudge, this.knobMax.y - bottomMargin);
};
this.update = function() {
// Follow mouse, constrain, space out
if (this.knobMin.isOn) {
this.knobMin.xOffset = constrain(mouseX, this.knobMax.x + this.knobMax.w/2, this.knobMin.x) - this.knobMin.x;
}
if (this.knobMax.isOn) {
this.knobMax.xOffset = constrain(mouseX, this.knobMax.x, this.knobMin.x - this.knobMin.w/2) - this.knobMax.x;
}
};
this.minValue = function() {
return map(this.knobMin.x+this.knobMin.xOffset, this.knobMin.x, this.knobMax.x, this.min, this.max);
};
this.maxValue = function() {
return map(this.knobMax.x+this.knobMax.xOffset, this.knobMax.x, this.knobMin.x, this.max, this.min);
};
}
function Knob(w, h) {
// x and y are the coordinates of the tip
this.x = 0;
this.y = 0;
this.w = w;
this.h = h;
this.xOffset = 0;
this.isOn = false;
this.display = function() {
fill(this.isOn ? pressedColor : foregroundColor);
stroke(borderColor);
strokeWeight(1.5);
triangle(this.x+this.xOffset, this.y, this.x+this.xOffset+this.w/2, this.y+this.h, this.x+this.xOffset-this.w/2, this.y+this.h);
};
this.isClicked = function() {
return dist(this.x+this.xOffset+this.w/2, this.y+this.h/2, mouseX, mouseY) < max(this.w, this.h);
};
}
/*
* Mouse Events
*/
function mousePressed() {
if (altitudeControl.knobMin.isClicked()) {
altitudeControl.knobMin.isOn = true;
} else if (altitudeControl.knobMax.isClicked()) {
altitudeControl.knobMax.isOn = true;
}
}
function mouseDragged() {
altitudeControl.update();
}
function mouseReleased() {
altitudeControl.knobMin.isOn = false;
altitudeControl.knobMax.isOn = false;
}
function mouseClicked() {
for (var lang in checkboxesForLangs) {
var checkbox = checkboxesForLangs[lang];
if (dist(checkbox.center.x, checkbox.center.y, mouseX, mouseY) < checkbox.hitRadius) {
toggleCheckbox(checkbox);
break;
}
}
var types = Object.keys(checkboxesForTypes).reverse();
for (var i = 0; i < types.length; i++) {
var type = types[i];
var checkbox = checkboxesForTypes[type];
if (dist(checkbox.center.x, checkbox.center.y, mouseX, mouseY) < checkbox.hitRadius) {
toggleCheckbox(checkbox);
break;
}
}
}
/*
* Helper Functions
*/
function mapCoord() {
// Pre-project and flatten array of coordinates
countryLines = [];
var countryLine = topojson.feature(topo, topo.objects.ch);
for (var i = 0; i < countryLine.features.length; i++) {
var feature = countryLine.features[i];
var coords = feature.geometry.coordinates;
var lineSegments = [];
for (var j = 0; j < coords.length; j++) {
var coord = coords[j];
var x = mapCoordX(coord[0]);
var y = mapCoordY(coord[1]);
lineSegments.push(x);
lineSegments.push(y);
}
countryLines.push(lineSegments);