-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmapviewer.js
1565 lines (1316 loc) · 41.4 KB
/
mapviewer.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
(function() {
var base_url = "";
function sformat(str) {
var args = arguments;
return str.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match;
});
}
function hex_to_rgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function get_random_color(list, id) {
var c = list[id];
if (c) {
return c;
}
else {
return list[id] = ("#"
+ Math.floor(Math.random()*(0xff-0x10)+0x10).toString(16)
+ Math.floor(Math.random()*(0xff-0x10)+0x10).toString(16)
+ Math.floor(Math.random()*(0xff-0x10)+0x10).toString(16));
}
}
var tribe_colors = { 0: "#ffffff" };
function get_tribe_color(tribe_id) {
return get_random_color(tribe_colors, tribe_id);
}
var tribe_colors_rgb = {};
function get_tribe_color_rgb(tribe_id) {
var c = tribe_colors_rgb[tribe_id]
if (!c) {
return tribe_colors_rgb[tribe_id] = hex_to_rgb(get_tribe_color(tribe_id));
} else {
return c;
}
}
var color_tribes = {};
function get_tribe_by_color(r, g, b) {
var col = "#" + ("000000" + (r << 16 | g << 8 | b).toString(16)).slice(-6);
return color_tribes[col];
}
var player_colors = {};
function get_player_color(player_id) {
return get_random_color(player_colors, player_id);
}
var tiles_width = 3400;
var tiles_height = 6200;
var map_width = tiles_width * 4;
var map_height = tiles_height;
var map_data;
var influence_image;
var cur_trans = [ 0, 0 ];
var cur_scale;
var canvas;
var canvas_ctx;
var content;
var info_text, info_text_2, cursor_text, changes_text;
var changes_button;
var canvas_width;
var canvas_height;
var xmin, xmax;
var ymin, ymax;
function on_zoom() {
var trans = zoom.translate().slice();
var scale = zoom.scale();
if (scale != cur_scale) {
transition_zoom(trans, scale, 250);
}
else {
d3.transition().duration(0); // abort transition
set_zoom(trans, scale);
draw();
}
}
var transition_end_timeout;
function transition_zoom(trans, scale, duration) {
d3.timer.flush();
var t1 = cur_trans.slice();
var s1 = cur_scale;
var t2 = trans.slice();
var s2 = scale;
d3.transition()
.delay(0)
.duration(duration)
.ease("quad-out")
.tween("zoom", function() {
itrans = d3.interpolate(t1, t2);
iscale = d3.interpolate(s1, s2);
return function(t) {
var trans = itrans(t);
var scale = iscale(t);
set_zoom(trans, scale);
draw(t == 1 && "transition end", t != 1 && "transition");
}
})
.each("end", function() {
/*
set_zoom(cur_trans, cur_scale);
//draw(true);
clearTimeout(transition_end_timeout)
transition_end_timeout = setTimeout(function() { draw(true); }, 1000);
*/
})
d3.timer.flush();
}
function transform_point(x, y) {
var tx = (x - cur_trans[0]) / cur_scale;
var ty = (y - cur_trans[1]) / cur_scale;
return [tx, ty];
}
function set_zoom(trans, scale, skip) {
cur_trans = trans;
cur_scale = scale;
if (!skip) {
zoom.translate(trans);
zoom.scale(scale);
}
// set canvas transformation
canvas_ctx.restore();
canvas_ctx.save();
// snap to grid at 100% zoom
if (scale == 1.0) {
canvas_ctx.translate(Math.floor(trans[0] + 0.5) + 0.5, Math.floor(trans[1] + 0.5) + 0.5);
}
else {
canvas_ctx.translate(trans[0] + 0.5, trans[1] + 0.5);
}
canvas_ctx.scale(scale, scale);
// update viewport extents
var margin_x = 100, margin_y = 50;
var min = transform_point(-margin_x, -margin_y);
var max = transform_point(canvas_width + margin_x, canvas_height + margin_y);
// neccesary with mirroring transforms
xmin = Math.min(min[0], max[0]) / 4; ymin = Math.min(min[1], max[1]);
xmax = Math.max(min[0], max[0]) / 4; ymax = Math.max(min[1], max[1]);
}
var mouse_raw;
var mouse_x = 0, mouse_y = 0;
var last_frame_time = 0;
function update_cursor_text() {
var x = Math.max(0, Math.min(tiles_width, Math.floor(mouse_x / 4)));
var y = Math.max(0, Math.min(tiles_height, Math.floor(mouse_y)));
cursor_text.text(sformat("{1} {2} {3}% {4} ms", x, y, Math.round(cur_scale * 100), last_frame_time.toFixed(0)));
}
function get_game_distance(x1, y1, x2, y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2) / 2;
}
function update_dist_text(obj) {
if (!obj || get_selection().length == 0) {
info_text_2.text("");
return;
}
var target = _(get_selection()).min(function(sel) { return get_game_distance(obj.x, obj.y, sel.x, sel.y); });
var dist = Math.floor(get_game_distance(obj.x, obj.y, target.x, target.y));
info_text_2.text(sformat("{1} tiles from {2}", dist, target.name));
}
function format_date(date, now) {
now = now || new Date();
var age = (now.getTime() - date.getTime());
var date_str;
if (age < 60*1000) {
var t = Math.floor(age / 1000);
date_str = t + " second" + (t == 1 ? "" : "s") + " ago";
}
else if (age < 3600*1000) {
var t = Math.floor(age / 60000);
date_str = t + " minute" + (t == 1 ? "" : "s") + " ago";
}
else if (age <= 24*3600*1000) {
var t = Math.floor(age / 3600000);
var m = Math.floor(age % 3600000 / 60000);
date_str = t + " hour" + (t == 1 ? "" : "s");
if (m > 0) {
date_str += " and " + m + " minute" + (m == 1 ? "" : "s");
}
date_str += " ago";
}
else {
date_str = date.toLocaleString();
}
return date_str;
}
function update_snapshot_timestamp() {
var date = new Date(map_data.SnapshotEnd);
var age = (new Date().getTime() - date.getTime());
var update_str = format_date(date);
if (age < 60*1000) {
setTimeout(update_snapshot_timestamp, 1000 - age % 1000);
}
else {
setTimeout(update_snapshot_timestamp, 60000 - age % 60000);
}
//if (age > (70*60*1000)) {
// load_resources(true);
//}
d3.select("#snapshot_timestamp").text("Last updated: " + update_str);
}
var frame_objects = {
forests: [],
troops: [],
barbarians: [],
cities: [],
strongholds: []
}
function get_object_by_location(x, y) {
function get_dist_sq(ox, oy) {
var dx = ox - x, dy = oy - y;
return dx * dx + dy * dy;
}
min_dist_sq = 10 * 10;
for (var i = 0; i < frame_objects.strongholds.length; ++i) {
var obj = frame_objects.strongholds[i];
var dist_sq = get_dist_sq(obj.x * 4, obj.y);
if (dist_sq < min_dist_sq) {
return [ "stronghold", obj ];
}
}
for (var i = 0; i < frame_objects.troops.length; ++i) {
var obj = frame_objects.troops[i];
var dist_sq = get_dist_sq(obj.x * 4, obj.y);
if (dist_sq < min_dist_sq) {
return [ "troop", obj ];
}
}
for (var i = 0; i < frame_objects.cities.length; ++i) {
var obj = frame_objects.cities[i];
var dist_sq = get_dist_sq(obj.x * 4, obj.y);
if (dist_sq < min_dist_sq) {
return [ "city", obj ];
}
}
}
var mouseover_timer;
function on_canvas_mousemove() {
// update mouse coords
var pos = d3.mouse(this);
var tpos = transform_point(pos[0], pos[1]);
mouse_raw = pos;
mouse_x = tpos[0];
mouse_y = tpos[1];
update_cursor_text();
// show mouseover object info
var obj = get_object_by_location(mouse_x, mouse_y);
canvas.style("cursor", obj ? "pointer" : "auto")
update_dist_text(obj && obj[1]);
if (obj) {
clearTimeout(mouseover_timer);
mouseover_timer = null;
var text = "";
switch (obj[0]) {
case "troop":
text = show_troop_info(obj[1]);
break;
case "barbarian":
text = show_barbarian_info(obj[1]);
break;
case "city":
text = show_city_info(obj[1]);
break;
case "stronghold":
text = show_stronghold_info(obj[1]);
break;
}
info_text.text(text);
}
else if (filters.influence) {
if (!mouseover_timer) {
mouseover_timer = setTimeout(update_mouseover_influence, 100);
}
}
else {
info_text.text("");
}
}
function update_mouseover_influence() {
mouseover_timer = null;
var img_data = canvas_ctx.getImageData(mouse_raw[0], mouse_raw[1], 1, 1).data;
var tribeid = get_tribe_by_color(img_data[0], img_data[1], img_data[2]);
if (tribeid) {
info_text.text(get_tribe(tribeid).name);
}
else {
info_text.text("");
}
}
var selected_objects = [];
var selection_radius = 0, selection_center = [];
function set_selection(obj) {
if (obj) {
selected_objects = [].concat(obj);
}
else {
selected_objects = [];
}
update_selection();
}
function add_selection(obj) {
selected_objects = selected_objects.concat(obj);
update_selection();
}
function get_selection() {
return selected_objects;
}
function is_selected(obj) {
return selected_objects.indexOf(obj) != -1;
}
function update_selection() {
selection_center = calc_selection_center();
selection_radius = calc_selection_radius();
}
function get_selection_center() {
return selection_center;
}
function get_selection_radius() {
return selection_radius;
}
function calc_selection_center() {
var min_x = tiles_width, max_x = 0;
var min_y = tiles_height, max_y = 0;
_(selected_objects).each(function(c) {
min_x = Math.min(min_x, c.x);
min_y = Math.min(min_y, c.y);
max_x = Math.max(max_x, c.x);
max_y = Math.max(max_y, c.y);
})
return [(max_x + min_x) / 2, (max_y + min_y) / 2];
}
function calc_selection_radius() {
var center = get_selection_center();
var dists_sq = _(selected_objects).map(function(c) {
var xd = c.x * 4 - center[0] * 4;
var yd = c.y - center[1];
return xd*xd + yd*yd;
});
return Math.sqrt(_(dists_sq).max());
}
function on_canvas_click() {
canvas.node().focus();
var obj = get_object_by_location(mouse_x, mouse_y);
if (obj) {
var sel_obj = obj[1];
if (sel_obj.playerId && d3.event.shiftKey) {
sel_obj = get_player(sel_obj.playerId);
}
select_object(sel_obj);
center_map_tile(obj[1].x, obj[1].y);
if (obj[1].name) {
update_url(obj[1].name);
}
}
else {
draw();
}
}
function get_city(group_id) {
return _(map_data.Cities).find(function(d) { return d.groupId == group_id });
}
function get_player(player_id) {
return _(map_data.Players).find(function(d) { return d.playerId == player_id });
}
function get_tribe(tribe_id, data) {
return _(data || map_data.Tribes).find(function(d) { return d.tribeId == tribe_id });
}
function show_city_info(city) {
return sformat("City: {1} / Level {2} ({3} IP) / Player: {4}{5}", city.name, city.level, city.value, get_player(city.playerId).name, city.tribeId != 0 && " (" + get_tribe(city.tribeId).name + ")" || "");
}
function show_troop_info(troop) {
var city = get_city(troop.groupId)
return sformat("Troop: {1} ({2}) / Player: {3}{4}", city.name, troop.troopId, get_player(city.playerId).name, city.tribeId != 0 && " (" + get_tribe(city.tribeId).name + ")" || "");
}
function show_stronghold_info(sh) {
return sformat("Stronghold: {1} / Level {2} / {3}", sh.name, sh.level, sh.tribeId != 0 && get_tribe(sh.tribeId).name || "Unoccupied");
}
var search_input;
var search_results;
function object_name_sort_comparer(x, y) {
return x.name < y.name ? -1 : 1;
}
function filter_object(obj) {
if (obj.x) {
return obj;
}
else {
return map_data.Cities.filter(
function(c) {
return (obj.tribeId && (obj.tribeId == c.tribeId)) || (obj.playerId && (obj.playerId == c.playerId));
});
}
}
function select_object(obj, append) {
var sel_objs = filter_object(obj);
if (append) {
add_selection(sel_objs)
}
else {
update_url(obj.name);
set_selection(sel_objs);
}
}
function set_selected_result(node) {
d3.select(".selected_search_result").classed("selected_search_result", false);
d3.select(node).classed("selected_search_result", true);
}
function search_result_click(obj) {
set_selected_result(this);
select_object(obj, d3.event.ctrlKey);
center_map_selection();
}
function do_search(q) {
if (!map_data)
return;
var match_cities = [];
var match_players = [];
var match_tribes = [];
var match_strongholds = [];
if (q && q.length > 0) {
q = q.toLowerCase();
var filter_fn = function(c) { return c.name.toLowerCase().indexOf(q) != -1; };
var exact_filter_fn = function(c) { return c.name.toLowerCase() == q; };
match_cities = map_data.Cities.filter(filter_fn);
match_players = map_data.Players.filter(filter_fn);
match_tribes = map_data.Tribes.filter(filter_fn);
match_strongholds = map_data.Strongholds.filter(filter_fn);
}
// cities
var search_results_cities = search_results.selectAll(".city_search_result").data(match_cities);
search_results_cities.exit().remove();
search_results_cities.enter().append("div");
search_results_cities
.sort(object_name_sort_comparer)
.attr("class", "search_result city_search_result")
.text(function(d) { return "City: " + d.name; })
.on("click", search_result_click);
// players
var search_results_players = search_results.selectAll(".player_search_result").data(match_players);
search_results_players.exit().remove();
search_results_players.enter().append("div");
search_results_players
.sort(object_name_sort_comparer)
.attr("class", "search_result player_search_result")
.text(function(d) { return "Player: " + d.name; })
.on("click", search_result_click);
// tribes
var search_results_tribes = search_results.selectAll(".tribe_search_result").data(match_tribes);
search_results_tribes.exit().remove();
search_results_tribes.enter().append("div");
search_results_tribes
.sort(object_name_sort_comparer)
.attr("class", "search_result tribe_search_result")
.text(function(d) { return "Tribe: " + d.name; })
.on("click", search_result_click);
// strongholds
var search_results_strongholds = search_results.selectAll(".stronghold_search_result").data(match_strongholds);
search_results_strongholds.exit().remove();
search_results_strongholds.enter().append("div");
search_results_strongholds
.sort(object_name_sort_comparer)
.attr("class", "search_result stronghold_search_result")
.text(function(d) { return "Stronghold: " + d.name; })
.on("click", search_result_click);
// if there is only one result or an exact result, jump to it
var num_results = match_cities.length + match_players.length + match_tribes.length + match_strongholds.length;
var exact = _(match_cities).find(exact_filter_fn) || _(match_players).find(exact_filter_fn) || _(match_tribes).find(exact_filter_fn) || _(match_strongholds).find(exact_filter_fn);
if (num_results == 1 || exact) {
var obj = exact || match_cities[0] || match_players[0] || match_tribes[0] || match_strongholds[0];
set_selected_result(d3.selectAll(".search_result").filter(function(d) { return d == obj; }).node());
select_object(obj);
center_map_selection();
}
// check if the user entered coordinates
var coords_regexp = /^\s*(\d+)[\s,]+(\d+)\s*$/;
var match = coords_regexp.exec(q);
if (match) {
var x = match[1], y = match[2];
if (x >= 0 && x <= tiles_width && y >= 0 && y <= tiles_height) {
center_map_tile(x, y);
update_url(q);
}
}
}
function center_map_tile(x, y, scale) {
scale = scale || cur_scale;
var trans = [(-x * 4) * scale + canvas_width / 2, (-y) * scale + canvas_height / 2];
var scale = scale;
transition_zoom(trans, scale, 1000);
}
function center_map_selection() {
var pos = get_selection_center();
var d = (get_selection_radius() + 110) * 2;
var scale = Math.max(get_min_zoom_scale(), Math.min(1, canvas_width / d, canvas_height / d));
center_map_tile(pos[0], pos[1], scale);
}
function get_min_zoom_scale() {
return Math.min(canvas_width / map_width, canvas_height / map_height)
}
function resize_canvas() {
var w = parseInt(canvas.style("width"));
var h = parseInt(canvas.style("height"));
canvas.attr("width", w);
canvas.attr("height", h);
canvas_width = w;
canvas_height = h;
}
function init_tribe_colors(data) {
for (var i = 0; i < data.length; ++i) {
var tcol = data[i];
tribe_colors[tcol.tribeId] = tcol.color;
tribe_colors_rgb[tcol.tribeId] = hex_to_rgb(tcol.color);
color_tribes[tcol.color] = tcol.tribeId;
}
draw("init_tribe_colors");
}
var city_locations;
function init_city_locations(data) {
city_locations = data;
if (update_foundations()) {
draw("init_city_locations");
}
}
function update_foundations() {
if (!city_locations || !map_data)
return false;
// create a sorted list of cities to be able to search them efficiently
var cities_pos = _(map_data.Cities).map(function(city) { return city.x + city.y * tiles_width; }).sort(function(a, b) { return a - b; });
var available_foundations = city_locations.filter(function(foundation) {
foundation.draw = draw_foundation;
return -1 == _(cities_pos).indexOf(foundation.x + foundation.y * tiles_width, true);
});
_(available_foundations).each(map_quadtree.add);
return true;
}
var first_map_update = true;
var map_quadtree;
var prev_map_data;
var map_data_apply_prev;
function init_prev_map(data) {
prev_map_data = data;
if (!map_data_apply_prev) {
return;
}
// find previous troop instances
_(map_data_apply_prev.Troops).each(function(cur) {
var prev = _(prev_map_data.Troops).find(function(pobj) { return pobj.groupId == cur.groupId && pobj.troopId == cur.troopId; });
if (prev) {
cur.prev = prev;
}
});
// find stronghold ownership changes
var cur_strongholds = map_data_apply_prev.Strongholds.slice();
var changed_strongholds = [];
_(prev_map_data.Strongholds).each(function(prev) {
var cur = _(cur_strongholds).find(function(pobj) { return pobj.id == prev.id; });
/* if (prev && prev.tribeId != cur.tribeId) */ {
prev.date = new Date(prev.time);
changed_strongholds.push([prev, cur]);
cur_strongholds[_(cur_strongholds).indexOf(cur)] = prev;
}
});
// format and display changes
var c = changes_text.selectAll("div").data(changed_strongholds);
c.exit().remove();
c.enter().append("div")
.sort(function(a, b) { return b[0].date - a[0].date; })
.html(function(shch) {
var prev_tribe = shch[0].tribeId && get_tribe(shch[0].tribeId, prev_map_data.Tribes).name || "";
var cur_tribe = shch[1].tribeId && get_tribe(shch[1].tribeId, map_data_apply_prev.Tribes).name || "(Unoccupied)";
return sformat("<span><span style='color:gold; font-weight:bold;'>{1} ({2})</span> <span style='background-color:{3}'>{4}</span> => <span style='background-color:{5}'>{6}</span><span style='display:inline-block;width:80px'>{7}</span></span>",
shch[0].name, shch[0].level,
get_tribe_color(shch[0].tribeId), prev_tribe,
get_tribe_color(shch[1].tribeId), cur_tribe,
format_date(shch[0].date, new Date(map_data_apply_prev.SnapshotBegin)));
});
update_changes_width();
map_data_apply_prev = null;
prev_map_data = null;
draw("init_prev_map");
}
function init_map(data) {
map_data = data;
// init quadtree
map_quadtree = d3.geom.quadtree([], tiles_width, tiles_height);
_(map_data.Cities).each(function(obj) { obj.draw = draw_city; map_quadtree.add(obj); })
_(map_data.Troops).each(function(obj) { obj.draw = draw_troop; map_quadtree.add(obj); })
_(map_data.Forests).each(function(obj) { obj.draw = draw_forest; map_quadtree.add(obj); })
_(map_data.Barbarians).each(function(obj) { obj.draw = draw_barbarian; map_quadtree.add(obj); })
_(map_data.Strongholds).each(function(obj) { obj.draw = draw_stronghold; map_quadtree.add(obj); })
// static info
update_snapshot_timestamp();
map_data_apply_prev = map_data;
if (prev_map_data) {
init_prev_map(prev_map_data);
}
update_foundations();
// initial draw
draw("init_map");
// first time stuff
if (first_map_update) {
first_map_update = false;
// search
search_input.on("input", function() {
clearTimeout(do_search_timeout)
do_search_timeout = setTimeout(function() {
do_search(search_input.property("value"))
}, 50);
});
search_input.node().focus();
search_input.node().select();
// canvas events
canvas.on("mousemove", on_canvas_mousemove);
canvas.on("click", on_canvas_click);
// hash url state
var q = search_input.property("value");
if (q && q.length > 0) {
do_search(q);
}
}
}
var filters = {
city: true,
stronghold: true,
influence: true,
};
var do_search_timeout;
var changes_width;
function update_changes_width() {
var widths = _(d3.selectAll("#changes_text > div > span")[0]).map(function(d) { return parseInt(d3.select(d).style("width")); });
changes_width = _(widths).max() - 5;
if (!changes_visible) {
changes_text.style("right", -changes_width + "px")
}
}
function set_changes_visibility(visible) {
if (visible) {
changes_text.style("display", "block");
changes_text.transition()
.duration(500)
.ease("cubic-out")
.style("opacity", 1)
.style("right", "5px")
.each("end", function() {
});
changes_button.text(">>");
}
else {
changes_text.transition()
.duration(500)
.ease("cubic-out")
.style("opacity", 0)
.style("right", -changes_width + "px")
.each("end", function() {
changes_text.style("display", "none");
});
changes_button.text("<<");
}
if (window.localStorage) {
window.localStorage["show_changes"] = visible;
}
}
function init() {
// filters
function update_filter_visibility(selector, checkbox) {
filters[selector] = checkbox.checked;
// enable troops when enabling troop trails
if (selector == "troop_trail" && checkbox.checked) {
d3.select("#filter_troops").node().checked = true;
filters["troop"] = true;
}
// save to localstorage
if (window.localStorage && JSON) {
window.localStorage["filters"] = JSON.stringify(filters);
}
draw("filter");
}
d3.select("#filter_cities").on("change", function() { update_filter_visibility("city", d3.event.target); });
d3.select("#filter_forests").on("change", function() { update_filter_visibility("forest", d3.event.target); });
d3.select("#filter_strongholds").on("change", function() { update_filter_visibility("stronghold", d3.event.target); });
d3.select("#filter_troops").on("change", function() { update_filter_visibility("troop", d3.event.target); });
d3.select("#filter_troop_trails").on("change", function() { update_filter_visibility("troop_trail", d3.event.target); });
d3.select("#filter_barbarians").on("change", function() { update_filter_visibility("barbarian", d3.event.target); });
d3.select("#filter_influence").on("change", function() { update_filter_visibility("influence", d3.event.target); });
d3.select("#filter_foundations").on("change", function() { update_filter_visibility("foundation", d3.event.target); });
// load filters from localStorage
if (window.localStorage && window.localStorage["filters"]) {
try {
filters = JSON.parse(window.localStorage["filters"]);
}
catch(e) {
}
}
// update filter checkboxes
d3.select("#filter_cities").node().checked = !!filters.city;
d3.select("#filter_forests").node().checked = !!filters.forest;
d3.select("#filter_strongholds").node().checked = !!filters.stronghold;
d3.select("#filter_troops").node().checked = !!filters.troop;
d3.select("#filter_troop_trails").node().checked = !!filters.troop_trail;
d3.select("#filter_barbarians").node().checked = !!filters.barbarian;
d3.select("#filter_influence").node().checked = !!filters.influence;
d3.select("#filter_foundations").node().checked = !!filters.foundation;
// info texts
cursor_text = d3.select("#cursor_text");
info_text = d3.select("#info_text");
info_text_2 = d3.select("#info_text_2");
// list of changes
changes_text = d3.select("#changes_text");
changes_button = d3.select("#changes_button");
changes_visible = true;
if (window.localStorage && window.localStorage["show_changes"]) {
changes_visible = window.localStorage["show_changes"] == "true";
}
changes_text.style("opacity", changes_visible ? 0 : 1);
set_changes_visibility(changes_visible);
changes_button.on("click", function() {
changes_visible = !changes_visible;
set_changes_visibility(changes_visible);
})
// first load resources
load_resources();
// init search elements
search_input = d3.select("#search");
search_results = d3.select("#search_results");
// init hash state
d3.select(window).on("hashchange", update_from_url);
update_from_url();
// init canvas
content = d3.select("#content");
canvas = d3.select("canvas");
canvas_ctx = canvas.node().getContext("2d");
canvas_ctx.save();
resize_canvas();
// font
init_fonts(canvas.style("font-family"));
// init zoom
cur_scale = get_min_zoom_scale();
cur_trans = [-map_width / 2 * cur_scale + canvas_width / 2, -map_height / 2 * cur_scale + canvas_height / 2];
zoom = d3.behavior.zoom()
.translate(cur_trans)
.scale(cur_scale)
.scaleExtent([get_min_zoom_scale(), 1])
.on("zoom", on_zoom);
canvas.call(zoom);
canvas.on("keydown", function() {
var scale = cur_scale;
var x_center = (2 * cur_trans[0] - canvas_width) / (2 * scale);
var y_center = (2 * cur_trans[1] - canvas_height) / (2 * scale);
var step = 500;
switch (d3.event.keyCode) {
// DOM_VK_ADD 0x6B (107) "+" on the numeric keypad.
// DOM_VK_PLUS 0xAB (171) Plus ("+") key. Requires Gecko 15.0
// +
case 107:
case 171:
case 187:
var k = Math.log(scale) / Math.LN2;
scale = Math.pow(2, Math.floor(k) + 1);
break;
// DOM_VK_SUBTRACT 0x6D (109) "-" on the numeric keypad.
// DOM_VK_HYPHEN_MINUS 0xAD (173) Hyphen-US/docs/Minus ("-") key.
// -
case 109:
case 173:
case 189:
var k = Math.log(scale) / Math.LN2;
scale = Math.pow(2, Math.ceil(k) - 1);
break;
// DOM_VK_LEFT 0x25 (37) Left arrow.
case 37:
x_center += step;
break;
// DOM_VK_UP 0x26 (38) Up arrow.
case 38:
y_center += step;
break;
// DOM_VK_RIGHT 0x27 (39) Right arrow.
case 39:
x_center -= step;
break;
// DOM_VK_DOWN 0x28 (40) Down arrow.
case 40:
y_center -= step;
break;
default:
return;
break;
}
scale = Math.min(1, Math.max(get_min_zoom_scale(), scale));
transition_zoom([
(x_center * scale + canvas_width/2),
(y_center * scale + canvas_height/2)
], scale, 250);
});
on_zoom();
d3.select(window).on("resize", function() {
resize_canvas();
var min_scale = get_min_zoom_scale()
if (zoom.scale() < min_scale || zoom.scale() == zoom.scaleExtent()[0]) {
zoom.scale(min_scale);
}
zoom.scaleExtent([min_scale, 1]);
on_zoom();
});
}
var last_load_resources;
var load_resources_timeout;
var min_load_resources_interval = 300*1000;
function load_resources(force_reload) {
if (last_load_resources) {
var age = new Date().getTime() - last_load_resources.getTime();
if (age < min_load_resources_interval) {
if (load_resources_timeout) {
var t = min_load_resources_interval - age % min_load_resources_interval;
load_resources_timeout = setTimeout(function() { load_resources(force_reload); }, t);
// increase interval after each attempt
min_load_resources_interval *= 1.5;
}
return;
}
}
last_load_resources = new Date();
clearTimeout(load_resources_timeout);
load_resources_timeout = null;
cursor_text.text("Loading..");
var query = "";
if (force_reload) {
query = "?" + (Math.random() * 1000000).toFixed();
}
d3.json(base_url + "tribe_colors.json" + query, function(error, data) {
if (error) {
cursor_text.text("Failed to load tribe colors");
}
else {
init_tribe_colors(data);