forked from dabbler0/bc18-tinyview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1463 lines (1239 loc) · 57.3 KB
/
script.js
File metadata and controls
1463 lines (1239 loc) · 57.3 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
// Constants
var UNIT_CLASSES = ['Worker', 'Knight', 'Ranger', 'Mage', 'Healer', 'Factory', 'Rocket'];
var MAX_HEALTHS = {'Worker': 100, 'Knight': 250, 'Ranger': 200, 'Mage': 80, 'Healer': 100, 'Factory': 300, 'Rocket': 200};
var TEAMS = ['Red', 'Blue'];
var TEAM_COLOR = {'Red': '#ac1c1e', 'Blue': '#3273dc'};
var ATTACK_COLOR = {'Red': 'rgba(255, 0, 0, 0.7)', 'Blue': 'rgba(0, 0, 255, 0.7)'};
var HEAL_COLOR = {'Red': 'rgba(77, 175, 74, 0.8)', 'Blue': 'rgba(77, 175, 74, 0.8)'};
var HEAD_SIZE = 0.3;
var BORDER_WIDTH = 0.2;
// Globals
var mousedown_listener, mouseup_listener, input_listener;
var research_canvas = document.getElementById('research');
var earth_canvas = document.getElementById('earth');
var graph_canvas = document.getElementById('graphs');
var research_ctx = research_canvas.getContext('2d');
var graph_ctx = graph_canvas.getContext('2d');
var earth_ctx = earth_canvas.getContext('2d');
var mars_canvas = document.getElementById('mars');
var mars_ctx = mars_canvas.getContext('2d');
var timeout = 40;
var activeID = 0;
var classIcons = {};
for (let i = 0; i < UNIT_CLASSES.length; i++) {
let img = new Image();
img.src = "images/" + UNIT_CLASSES[i] + ".svg";
classIcons[UNIT_CLASSES[i]] = img;
}
let rocketIcons = [null, null];
for (let i = 0; i < 2; i++) {
let img = new Image();
img.src = "images/RocketInSpace" + TEAMS[i] + ".svg";
rocketIcons[i] = img;
}
// Set default timeout value
document.getElementById('timeout').value = timeout;
// Allow setting replay speed
document.getElementById('timeout').addEventListener('change', function(e) {
timeout = document.getElementById('timeout').value;
});
/*
Visualize a replay file given a JSON object
corresponding to the file.
(This is prior to the messages within the replay file,
which are strings corresponding to JSON objects,
being parsed.)
*/
function lerp(p1, p2, t) {
t = Math.min(1, Math.max(0, t));
return { x: p2.x*t + p1.x*(1-t), y: p2.y*t + p1.y*(1-t) }
}
function lerpf(v1, v2, t) {
t = Math.min(1, Math.max(0, t));
return v2 * t + v1 * (1 - t);
}
function vectorSub(v1, v2) {
return { x: v2.x - v1.x, y: v2.y - v1.y }
}
function vectorRotate90(v) {
return { x: -v.y, y: v.x }
}
function vectorNormalize(v) {
var magn = Math.sqrt(v.x*v.x + v.y*v.y);
return { x: v.x/magn, y: v.y/magn }
}
function clamp01(x) {
return Math.max(0, Math.min(1, x));
}
function moveLinear(from, to, t) {
let delta = Math.abs(to - from);
t = Math.min(t, delta);
t = Math.max(t, 0);
return from + Math.sign(to - from) * t;
}
function handleLocationClick(canvas, planetName, planetWidth, planetHeight){
var tileWidth = canvas.width/planetWidth;
var tileHeight = canvas.height/planetHeight;
return function(event){
//https://stackoverflow.com/questions/55677/how-do-i-get-the-coordinates-of-a-mouse-click-on-a-canvas-element
var rect = canvas.getBoundingClientRect();
var x = Math.floor((event.clientX - rect.left)/tileWidth);
var y = planetHeight-Math.floor((event.clientY - rect.top)/tileHeight)-1;
document.getElementById('location').innerText = planetName + '[' + x + ' - ' + y + ']';
}
}
function visualize(data) {
activeID += 1;
let currentID = activeID;
// Globals
var winner;
var team_name = {}
var id2team = {};
var id2teamIndex = {};
var maturation_times = {};
var reserves = [[100, 100]]; // Precomped for every turn
// Whether or not the slider is currently being held down.
// This is used because the input event only fires
// when the slider's value is actively changing,
// but we want it to pause even if it is held in position.
var slider_held = false;
// Whether or not we're currently paused.
var paused = false;
// Whether we should restart the replay
var reset = false;
// Store team names
team_name['Red'] = data['metadata'].player1;
team_name['Blue'] = data['metadata'].player2;
// Determine who won
winner = data['metadata'].winner;
if (winner == 'player1') winner = 'Red';
else winner = 'Blue';
// Parse each turn from the replay file
data = data['message'].map(JSON.parse);
// Pop off the first "turn", whic is not a turn
// but instead an initialization object
let world = data[0].world;
data.shift();
// Clear info on the winner
document.getElementById('winner').innerText = '';
// Get impassable squares for Earth
var planet_maps = {
'Earth': world.planet_maps.Earth.is_passable_terrain,
'Mars': world.planet_maps.Mars.is_passable_terrain
};
// Get Karbonite data
// We'll precomp this for every turn
var karbonite_maps = {
'Earth': [world.planet_maps.Earth.initial_karbonite],
'Mars': [planet_maps['Mars'].map(function(x) { return x.map(function() { return 0; }); })]
};
// Get the team identities of the initial units
// (these are not given ever again so we need to remember)
var initial_units = world.planet_states.Earth.units
for (var key in initial_units) {
var unit = initial_units[key];
id2team[unit.id] = unit.team;
id2teamIndex[unit.id] = TEAMS.indexOf(unit.team);
}
// We will now precomp Karbonite data,
// reserves data, and unit teams, to allow
// scrubbing.
for (var t = 0; t < data.length; t += 1) {
// Update Karbonite reserves if necessary.
// TODO:
// This currently will result in updating reserves
// _before_ being displayed for a turn.
// If this should occur _after_ being displayed
// for a turn instead, swap the two lines below.
reserves[reserves.length - 1][t % 2] = data[t].karbonite;
reserves.push(reserves[reserves.length - 1].slice(0));
function update_for(planet) {
// If Karbonite on the board has changed, update our current counts
karbonite_maps[planet].push(
karbonite_maps[planet][karbonite_maps[planet].length - 1].map(function(x) {
return x.slice(0);
})
);
for (var i = 0; i < data[t].additional_changes.length; i += 1) {
var change = data[t].additional_changes[i];
if (change.KarboniteChanged != null &&
change.KarboniteChanged.location.planet === planet) {
karbonite_maps[planet][
karbonite_maps[planet].length - 1
][
change.KarboniteChanged.location.y
][
change.KarboniteChanged.location.x
] = change.KarboniteChanged.new_amount;
}
}
// Precomp units
for (var i = 0; i < data[t].units.length; i += 1) {
var unit = data[t].units[i];
if (unit.location.planet == planet) {
// If this unit has never been seen before, it must
// have just been made. Thus it belongs to the current player.
if (!(unit.id in id2team)) {
id2team[unit.id] = TEAMS[t % 2];
id2teamIndex[unit.id] = t % 2;
// Factories, before they reach full health,
// are actually just blueprints
if (unit.unit_type == 'Factory' || unit.unit_type == 'Rocket') {
maturation_times[unit.id] = Infinity;
}
}
// Factories and rockets mature when they reach full health
if ((unit.unit_type == 'Factory' && unit.health == 300 ||
unit.unit_type == 'Rocket' && unit.health == 200) &&
maturation_times[unit.id] == Infinity) {
maturation_times[unit.id] = t;
}
}
}
}
update_for('Earth');
update_for('Mars');
}
let unitValueByTime = [];
// Note: need to keep up to date
let unit_values = {
"Worker": 50,
"Knight": 40,
"Ranger": 40,
"Mage": 40,
"Healer": 40,
"Rocket": 150,
"Factory": 200,
};
for (var t = 0; t < data.length; t += 1) {
let values = [0, 0];
let units = data[t].units;
for (let i = 0; i < units.length; i++) {
values[id2teamIndex[units[i].id]] += unit_values[units[i].unit_type];
}
unitValueByTime.push(values);
}
// set the maximum turn we could slide to
var t = data.length - 1;
document.getElementById('turnslider').max = (t - t % 4) / 4 + 1;
// Convenience dimension variables
var earth_w = planet_maps['Earth'][0].length, earth_h = planet_maps['Earth'].length;
// Convenience dimension variables
var mars_w = planet_maps['Mars'][0].length, mars_h = planet_maps['Mars'].length;
// set canvas width / height
earth_canvas.width = 500;
earth_canvas.height = earth_canvas.width * earth_h / earth_w;
mars_canvas.width = 500;
mars_canvas.height = mars_canvas.width * mars_h / mars_w;
let researchEvents = [[], []];
for (let t = 0; t < data.length; t++) {
let eventBuffer = researchEvents[t % 2];
let changes = data[t].additional_changes;
for (let i = 0; i < changes.length; i++) {
if ("ResearchComplete" in changes[i]) {
let item = changes[i]["ResearchComplete"];
let buffer = eventBuffer;
// This is currently bugged in the engine
// Awaiting engine fix
if ("team" in item) {
// Yay! The Engine has been fixed
buffer = researchEvents[TEAMS.indexOf(item.team)];
}
for (let j = 0; j < buffer.length; j++) {
if (buffer[j].end_turn == -1) {
if (buffer[j].branch != item.branch) {
console.log("Incorrect research was completed. Expected " + buffer[j].branch + " but got " + item.branch + ". This error will be removed once a bug in the battlecode engine is patched");
break;
}
buffer[j].end_turn = t;
// Start next research
for (let q = 0; q < buffer.length; q++) {
if (buffer[q].start_active_turn == -1 && !buffer[q].cancelled) {
buffer[q].start_active_turn = t;
break;
}
}
break;
}
}
}
}
changes = data[t].changes;
for (let i = 0; i < changes.length; i++) {
if (changes[i] == "ResetResearchQueue") {
for (let j = 0; j < eventBuffer.length; j++) {
if (eventBuffer[j].end_turn == -1) {
eventBuffer[j].cancelled = true;
eventBuffer[j].end_turn = t;
}
}
} else if ("QueueResearch" in changes[i]) {
let item = changes[i]["QueueResearch"];
let anyActive = false;
for (let j = 0; j < eventBuffer.length; j++) {
// Active!
if (eventBuffer[j].end_turn == -1) {
anyActive = true;
}
}
eventBuffer.push({
branch: item.branch,
start_turn: t,
end_turn: -1,
start_active_turn: anyActive ? -1 : t,
cancelled: false,
});
}
}
}
// Note: may have to be updated if any balancing changes are done
const RocketResearchTravelTimeReduction = 80;
let rockets = [];
for (let t = 0; t < data.length; t++) {
let changes = data[t].changes;
for (let i = 0; i < changes.length; i++) {
let launch = changes[i].LaunchRocket;
if (launch !== undefined) {
let rocket = {
unitId: launch.rocket_id,
startTurn: t,
endTurn: t + 4*travel_time(t, world.orbit) + 1 - (has_research(t, "Rocket", 2, t % 2) ? RocketResearchTravelTimeReduction : 0),
teamIndex: t % 2,
location: launch.location,
};
rockets.push(rocket);
if (rocket.endTurn < data.length) {
let expectedLandingChanges = data[rocket.endTurn].additional_changes;
let found = false;
for (let j = 0; j < expectedLandingChanges.length; j++) {
var landing = expectedLandingChanges[j].RocketLanding;
if (landing !== undefined && landing.rocket_id == launch.rocket_id) {
found = true;
break;
}
}
// Note: a bug was recently fixed in the engine that caused rocket research to increase the travel time instead of reduce it, that bug can cause this message to be logged.
if (!found) {
console.log("Didn't find rocket landing, start at " + rocket.startTurn + " expected landing at " + rocket.endTurn);
}
} else if (rocket.endTurn/4 < 1000) {
console.log("Rocket should land after the game end, but before turn 1000, how is this possible?");
}
}
}
}
function travel_time_smooth(time, orbit) {
return orbit.center + orbit.amplitude * Math.sin((time/4+1) * (2*Math.PI / orbit.period));
}
function travel_time(time, orbit) {
// Note |0 is used to round towards zero, in contrast to floor which rounds towards negative infinity
return orbit.center + ((orbit.amplitude * Math.sin(Math.floor(time/4+1) * (2*Math.PI / orbit.period)))|0);
}
function has_research(time, research, level, teamIndex) {
let lev = 0;
for (let i = 0; i < researchEvents[teamIndex].length; i++) {
let item = researchEvents[teamIndex][i];
if (item.branch == research && !item.cancelled && time >= item.end_turn && item.end_turn != -1) lev++;
}
return lev >= level;
}
function test_duration() {
let period = 200;
let orbit = {
amplitude: 150,
period: period,
center: 250,
};
function duration(round, orbit) {
return Math.round(travel_time(4*round - 4, orbit));
}
for (let i = 0; i < 5; i++) {
let base = period * i;
console.assert(250 == duration(base, orbit), 250 + " == " + duration(base, orbit));
console.assert(400 == duration(base + period / 4, orbit), 400 + " == " + duration(base + period / 4, orbit));
console.assert(250 == duration(base + period / 2, orbit), 250 + " == " + duration(base + period / 2, orbit));
console.assert(100 == duration(base + period * 3 / 4, orbit), 100 + " == " + duration(base + period * 3 / 4, orbit));
console.assert(250 == duration(base + period, orbit), 250 + " == " + duration(base + period, orbit));
let dur = duration(base + period / 8, orbit);
console.assert(dur > 250 && dur < 400);
}
}
test_duration();
function render_planet_background(t, planet, ctx) {
// Convenience dimension variables
var w = planet_maps[planet][0].length, h = planet_maps[planet].length;
// This is used to invert the y-axis
function flipY(oy) { return (h - oy - 1); }
// Draw background
if (planet == 'Mars') {
ctx.fillStyle = "#e4cdc0";
} else {
ctx.fillStyle = "#FFF";
}
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// Draw the map
ctx.textBaseline = "middle";
ctx.textAlign = "center";
let karbonite_at_tick = karbonite_maps[planet][t];
for (var i = 0; i < h; i++) {
for (var j = 0; j < w; j++) {
// Flip along y-axis
var px = j, py = flipY(i);
var impassable = !planet_maps[planet][i][j];
var karbs = karbonite_at_tick[i][j] > 0;
if (impassable || karbs) {
ctx.beginPath();
// Draw a rect. It is 1 pixel larger than the tile to avoid graphical artifacts at the borders between tiles
ctx.rect(px * (ctx.canvas.width / w) - 0.5, py * (ctx.canvas.height / h) - 0.5,
ctx.canvas.width / w + 0.5, ctx.canvas.height / h + 0.5);
// Black out impassable squares
if (impassable) {
if (planet == 'Mars') {
ctx.fillStyle = '#5d1e10';
} else {
ctx.fillStyle = '#306796';
}
ctx.fill();
}
if (karbs) {
// Write amount of Karbonite at location
ctx.globalAlpha = (karbonite_at_tick[i][j] > 0 ? 0.2 : 0.0) + 0.6 * (karbonite_at_tick[i][j] / 50);
ctx.fillStyle = '#337';
ctx.fill();
ctx.globalAlpha = 1.0;
ctx.fillStyle = '#888';
ctx.fillText(karbonite_at_tick[i][j].toString(),
(px + 0.5) * (ctx.canvas.width / w), (py + 0.5) * ctx.canvas.height / h + 2);
}
}
}
}
ctx.strokeStyle = "rgba(0,0,0,0.1)";
ctx.lineWidth = 1;
// Draw grid lines
for (var y = 0; y < h; y++) {
ctx.beginPath();
ctx.moveTo(0, y * (ctx.canvas.height / h));
ctx.lineTo(ctx.canvas.width, y * (ctx.canvas.height / h));
ctx.stroke();
}
for (var x = 0; x < h; x++) {
ctx.beginPath();
ctx.moveTo(x * (ctx.canvas.width / w), 0);
ctx.lineTo(x * (ctx.canvas.width / w), ctx.canvas.height);
ctx.stroke();
}
}
const DamageTime = 0.7;
const MoveFinishedTime = 0.8;
const OverchargeTime = 0.4;
function render_units(t, fractional_t, planet, ctx, unit_locations, unit_types, prevUnits, unit_count) {
// Convenience dimension variables
var w = planet_maps[planet][0].length, h = planet_maps[planet].length;
// This is used to invert the y-axis
function flipY(oy) { return (h - oy - 1); }
let units = data[t].units;
for (var i = 0; i < units.length; i += 1) {
var unit = units[i];
var prevUnit = prevUnits[unit.id];
if (prevUnit === undefined) prevUnit = unit;
let interpLocation = lerp(prevUnit.location, unit.location, fractional_t / MoveFinishedTime);
unit_locations[unit.id] = [interpLocation.x, interpLocation.y, unit.location.planet];
unit_types[unit.id] = unit.unit_type;
if (unit.location.planet == planet) {
// Increment unit_count for the scoreboard
unit_count[id2team[unit.id]][unit.unit_type]++;
// Render the unit in the correct color.
// Blueprints will be given an alpha
if ((unit.unit_type === "Factory" || unit.unit_type === "Rocket") &&
maturation_times[unit.id] > t) {
ctx.globalAlpha = 0.5;
}
let unitTypeStyle = "";
// The border of the square will represent the unit type.
switch (unit.unit_type) {
case "Worker":
// Workers will be yellow, because whatever.
unitTypeStyle = '#FF0'; break;
case "Knight":
// Knights will be some kind of maroon
unitTypeStyle = '#800'; break;
case "Ranger":
// Rangers will be some kind of dark green
unitTypeStyle = '#080'; break;
case "Mage":
// Rangers will be some kind of dark blue
unitTypeStyle = '#008'; break;
case "Healer":
// Healers will be some kind of purple
unitTypeStyle = '#808'; break;
case "Factory":
// Factories will be gray
unitTypeStyle = '#000'; break;
case "Rocket":
// Rockets
unitTypeStyle = '#000'; break;
default:
// Unimplemented unit type
unitTypeStyle = '#FFF';
}
// Flip along the y-axis for drawing.
// This is because canvas is top-left based.
var px = interpLocation.x;
var py = flipY(interpLocation.y);
// The inside of the square represents the team allegiance
// and also health
if (fractional_t > DamageTime) {
health = lerpf(prevUnit.health, unit.health, (fractional_t - DamageTime)/(1 - DamageTime)) / MAX_HEALTHS[unit.unit_type];
} else {
health = prevUnit.health / MAX_HEALTHS[unit.unit_type];
}
if (unit.unit_type == "Factory") {
// Fill the border
ctx.fillStyle = unitTypeStyle;
ctx.fillRect(
px * ctx.canvas.width / w, py * ctx.canvas.height / h,
ctx.canvas.width / w, ctx.canvas.height / h
)
ctx.fillStyle = '#FFF';
ctx.fillRect(
(px + BORDER_WIDTH) * ctx.canvas.width / w, (py + BORDER_WIDTH) * ctx.canvas.height / h,
(1 - 2 * BORDER_WIDTH) * ctx.canvas.width / w, (1 - 2 * BORDER_WIDTH) * ctx.canvas.height / h
);
ctx.fillStyle = ctx.strokeStyle = TEAM_COLOR[id2team[unit.id]];
ctx.lineWidth = 1;
ctx.strokeRect(
(px + BORDER_WIDTH) * ctx.canvas.width / w, (py + BORDER_WIDTH) * ctx.canvas.height / h,
(1 - 2 * BORDER_WIDTH) * ctx.canvas.width / w, (1 - 2 * BORDER_WIDTH) * ctx.canvas.height / h
);
ctx.fillRect(
(px + BORDER_WIDTH) * ctx.canvas.width / w,
(py + BORDER_WIDTH + (1 - 2 * BORDER_WIDTH) * (1 - health)) * ctx.canvas.height / h,
(1 - 2 * BORDER_WIDTH) * ctx.canvas.width / w,
(1 - 2 * BORDER_WIDTH) * health * ctx.canvas.height / h
);
} else {
var cx = (px + 0.5) * ctx.canvas.width / w;
var cy = (py + 0.5) * ctx.canvas.height / h;
var radius = 0.3 * ctx.canvas.width / w;
let lineWidthMultiplier = 20 / w;
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, 2 * Math.PI);
ctx.strokeStyle = TEAM_COLOR[id2team[unit.id]];
ctx.lineWidth = 6 * lineWidthMultiplier;
ctx.stroke();
if (health < 1) {
ctx.fillStyle = "#FFF";
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, 2 * Math.PI);
ctx.fill();
}
ctx.fillStyle = unitTypeStyle;
ctx.beginPath();
// Fill from bottom to top. Don't let angle be exactly Math.PI or
// rounding error can cause the circle not to fill at all.
let angle = Math.asin((health * 2 - 1) * (1 - 1e-3));
//ctx.arc(cx, cy, radius, Math.PI * 0.5, -angle, true);
//ctx.arc(cx, cy, radius, Math.PI + angle, Math.PI * 0.5, true);
ctx.arc(cx, cy, radius, Math.PI + angle, -angle, true);
// Radial health
// ctx.arc(cx, cy, health * radius, 0, 2 * Math.PI);
ctx.fill();
if (unit.unit_type == "Rocket") {
// Draw how many units are inside
// ctx.fillStyle = '#888';
// ctx.fillText(karbonite_at_tick[i][j].toString(),
// (px + 0.4) * (500 / w), (py + 0.6) * 500 / h);
}
}
ctx.globalAlpha = 1;
}
}
}
function render_attacks(t, fractional_t, planet, ctx, unit_locations, unit_types, prevUnits) {
// Convenience dimension variables
var w = planet_maps[planet][0].length, h = planet_maps[planet].length;
// This is used to invert the y-axis
function flipY(oy) { return (h - oy - 1); }
let attacksByUnit = {};
// Render attacks
// (these are technically made the next turn,
// but are rendered this turn for ease of viewing)
for (var i = 0; i < data[t].changes.length; i += 1) {
var change = data[t].changes[i];
// Required to avoid exceptions when trying to use the 'in' operator.
// It will not work on the 'ResetResearchQueue' event which is a string, not an object.
if (typeof change !== 'object') continue;
let target = null;
let robot = null;
let isAbility = false;
if ('Overcharge' in change) {
let heal = change['Overcharge'];
target = heal.target_robot_id;
robot = heal.healer_id;
isAbility = true;
}
if ('Attack' in change) {
let attack = change['Attack'];
target = attack.target_unit_id;
robot = attack.robot_id;
}
if ('Heal' in change) {
let heal = change['Heal'];
target = heal.target_robot_id;
robot = heal.healer_id;
}
if (robot != null) {
if (unit_locations[target][2] != planet || unit_locations[robot][2] != planet)
continue;
// Store positions.
// While we do this we flip the y-axis
// for rendering to the canvas.
var rpos = {
x: unit_locations[robot][0],
y: flipY(unit_locations[robot][1])
};
var tpos = {
x: unit_locations[target][0],
y: flipY(unit_locations[target][1])
};
if (!(robot in attacksByUnit)) {
attacksByUnit[robot] = 0;
}
let previousAttacks = attacksByUnit[robot];
attacksByUnit[robot] = previousAttacks + 1;
let attackTime = fractional_t;
if (!isAbility) {
// Will modify time to make later attacks happen later during the frame
// Will still happen during 0...1
attackTime = clamp01(1 - (1 - attackTime) * (previousAttacks + 1));
}
if (unit_types[robot] == 'Ranger') {
var interPos1 = lerp(rpos, tpos, (attackTime - 0.3) / DamageTime);
var interPos2 = lerp(rpos, tpos, (attackTime) / DamageTime);
ctx.strokeStyle = ATTACK_COLOR[id2team[robot]];
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(
(interPos1.x + 0.5) * ctx.canvas.width / w,
(interPos1.y + 0.5) * ctx.canvas.height / h);
ctx.lineTo(
(interPos2.x + 0.5) * ctx.canvas.width / w,
(interPos2.y + 0.5) * ctx.canvas.height / h);
ctx.stroke();
if (attackTime > DamageTime && attackTime < DamageTime + 0.1) {
let size = (attackTime - DamageTime)/0.1;
ctx.beginPath();
ctx.arc(
(tpos.x + 0.5) * ctx.canvas.width / w,
(tpos.y + 0.5) * ctx.canvas.height / h,
size * HEAD_SIZE * ctx.canvas.width / w,
// size * HEAD_SIZE * ctx.canvas.height / h,
0,
2 * Math.PI
);
ctx.fillStyle = '#F0F';
ctx.fill();
}
} else if (unit_types[robot] == 'Healer') {
if (isAbility) {
// Overcharge!
var t0 = (attackTime - 0.3) / OverchargeTime;
var t1 = (attackTime) / OverchargeTime;
var interPos1 = lerp(rpos, tpos, t0);
var interPos2 = lerp(rpos, tpos, t1);
ctx.strokeStyle = "#12e5ca";
ctx.lineWidth = 3;
ctx.beginPath();
let normal = vectorNormalize(vectorRotate90(vectorSub(interPos2, interPos1)));
for (let i = 0; i <= 20; i++) {
let tx = lerpf(t0, t1, i * 0.05);
let p = lerp(rpos, tpos, tx);
let offset = 0.05 * Math.sin(tx * 30);
p.x += normal.x * offset;
p.y += normal.y * offset;
if (i == 0) ctx.moveTo((p.x + 0.5) * ctx.canvas.width / w, (p.y + 0.5) * ctx.canvas.height / h);
else ctx.lineTo((p.x + 0.5) * ctx.canvas.width / w, (p.y + 0.5) * ctx.canvas.height / h);
}
ctx.stroke();
let effectEnd = 0.9;
let effectStart = 0.1;
if (attackTime > 0.1 && attackTime < 0.9) {
let tposx = (tpos.x + 0.5) * ctx.canvas.width / w;
let tposy = (tpos.y + 0.5) * ctx.canvas.height / h;
ctx.beginPath();
let lines = 9;
let innerRadius = 0.5;
let outerRadius = 0.8 + attackTime * 0.2;
let angleOffset = attackTime * 0.5 * Math.PI;
for (let i = 0; i < 9; i++) {
let angle = (i / lines) * 2 * Math.PI;
ctx.moveTo(tposx + innerRadius * Math.cos(angle + angleOffset) * (ctx.canvas.width / w),
tposy + innerRadius * Math.sin(angle + angleOffset) * (ctx.canvas.height / h));
ctx.lineTo(tposx + outerRadius * Math.cos(angle + angleOffset) * (ctx.canvas.width / w),
tposy + outerRadius * Math.sin(angle + angleOffset) * (ctx.canvas.height / h));
}
ctx.strokeStyle = "#12e5ca";
ctx.lineWidth = 2;
ctx.globalAlpha = clamp01((effectEnd - attackTime) / 0.1);
ctx.stroke();
ctx.globalAlpha = 1.0;
}
} else {
// Heal
var t0 = (attackTime - 0.3) / DamageTime;
var t1 = (attackTime) / DamageTime;
var interPos1 = lerp(rpos, tpos, t0);
var interPos2 = lerp(rpos, tpos, t1);
ctx.strokeStyle = HEAL_COLOR[id2team[robot]];
ctx.lineWidth = 3;
ctx.beginPath();
let normal = vectorNormalize(vectorRotate90(vectorSub(interPos2, interPos1)));
for (let i = 0; i <= 20; i++) {
let tx = lerpf(t0, t1, i * 0.05);
let p = lerp(rpos, tpos, tx);
let offset = 0.05 * Math.sin(tx * 30);
p.x += normal.x * offset;
p.y += normal.y * offset;
if (i == 0) ctx.moveTo((p.x + 0.5) * ctx.canvas.width / w, (p.y + 0.5) * ctx.canvas.height / h);
else ctx.lineTo((p.x + 0.5) * ctx.canvas.width / w, (p.y + 0.5) * ctx.canvas.height / h);
}
ctx.stroke();
if (attackTime > DamageTime && attackTime < DamageTime + 0.1) {
let size = (attackTime - DamageTime)/0.1;
ctx.beginPath();
ctx.arc(
(tpos.x + 0.5) * ctx.canvas.width / w,
(tpos.y + 0.5) * ctx.canvas.height / h,
size * HEAD_SIZE * ctx.canvas.width / w,
// size * HEAD_SIZE * ctx.canvas.height / h,
0,
2 * Math.PI
);
ctx.fillStyle = '#F0F';
ctx.fill();
}
}
} else if (unit_types[robot] == 'Knight') {
var interPos1 = lerp(rpos, tpos, (attackTime - 0.3) / DamageTime);
var interPos2 = lerp(rpos, tpos, (attackTime) / DamageTime);
ctx.strokeStyle = ATTACK_COLOR[id2team[robot]];
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(
(interPos1.x + 0.5) * ctx.canvas.width / w,
(interPos1.y + 0.5) * ctx.canvas.height / h);
ctx.lineTo(
(interPos2.x + 0.5) * ctx.canvas.width / w,
(interPos2.y + 0.5) * ctx.canvas.height / h);
ctx.stroke();
if (attackTime > DamageTime && attackTime < DamageTime + 0.1) {
let size = (attackTime - DamageTime)/0.1;
ctx.beginPath();
ctx.arc(
(tpos.x + 0.5) * ctx.canvas.width / w,
(tpos.y + 0.5) * ctx.canvas.height / h,
size * HEAD_SIZE * ctx.canvas.width / w,
// size * HEAD_SIZE * ctx.canvas.height / h,
0,
2 * Math.PI
);
ctx.fillStyle = '#F0F';
ctx.fill();
}
} else if (unit_types[robot] == 'Mage') {
var interPos1 = lerp(rpos, tpos, (attackTime - 0.3) / DamageTime);
var interPos2 = lerp(rpos, tpos, (attackTime) / DamageTime);
ctx.strokeStyle = ATTACK_COLOR[id2team[robot]];
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(
(interPos1.x + 0.5) * ctx.canvas.width / w,
(interPos1.y + 0.5) * ctx.canvas.height / h);
ctx.lineTo(
(interPos2.x + 0.5) * ctx.canvas.width / w,
(interPos2.y + 0.5) * ctx.canvas.height / h);
ctx.stroke();
if (attackTime > DamageTime && attackTime < DamageTime + 0.1) {
let size = (attackTime - DamageTime)/0.1;
ctx.beginPath();
ctx.arc(
(tpos.x + 0.5) * ctx.canvas.width / w,
(tpos.y + 0.5) * ctx.canvas.height / h,
size * HEAD_SIZE * ctx.canvas.width / w,
// size * HEAD_SIZE * ctx.canvas.height / h,
0,
2 * Math.PI
);
ctx.fillStyle = '#F0F';
ctx.fill();
}
// Render splash damage from mages
if (attackTime > DamageTime - 0.1 && attackTime < DamageTime + 0.05) {
for (var dx = -1; dx <= 1; dx += 1) {
for (var dy = -1; dy <= 1; dy += 1) {
ctx.strokeStyle = '#F0F';
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(
(tpos.x + 0.5) * ctx.canvas.width / w,
(tpos.y + 0.5) * ctx.canvas.height / h);
ctx.lineTo(
(tpos.x + 0.5 + dx) * ctx.canvas.width / w,
(tpos.y + 0.5 + dy) * ctx.canvas.height / h);
ctx.stroke();
}
}
}
} else {
console.log("Unknown attack type for " + unit_types[robot]);
// ???
}
}
}
}
function render_rocket_landings(t, ctx, canvas) {
// Convenience dimension variables
var w = mars_w, h = mars_h;
// This is used to invert the y-axis
function flipY(oy) { return (h - oy - 1); }
const effectDurations = [4*18, 4*5];
const effectOffsets = [4*5, 4*2];
const effectRadii = [1.5, 1];
for (let i = 0; i < rockets.length; i++) {
const rocket = rockets[i];
for (let k = 0; k < 2; k++) {
const effectDuration = effectDurations[k];
const effectOffset = effectOffsets[k];
const effectRadius = effectRadii[k];
if (t >= rocket.endTurn - effectDuration + effectOffset && t < rocket.endTurn + effectOffset) {
ctx.save();
ctx.translate((rocket.location.x + 0.5) * 500 / mars_w, (flipY(rocket.location.y) + 0.5) * 500 / mars_h);
ctx.fillStyle = "#8b3c0d";
const relativeTime = 1 - (rocket.endTurn + effectOffset - t) / effectDuration;
for (let j = 0; j < 10; j++) {
// const rad = (j+1) * (relativeTime - 1 + 1 / (j + 1));
const rad = Math.pow(j+1, 0.4) * ( relativeTime - (j+1) / 10)
if (rad > 0) {
//const rad2 = Math.pow(j+1, 0.8) * (relativeTime - 1 + 1 / (j + 1));
ctx.beginPath();
ctx.arc(0, 0, rad * effectRadius * (500 / mars_w), 0, 2 * Math.PI);
if (j == 0) {
ctx.globalCompositeOperation = "multiply";
} else {
ctx.globalCompositeOperation = "lighter";
}
ctx.globalAlpha = clamp01(2*(1 - Math.pow(relativeTime, 0.5)));
ctx.fill();
}
}
ctx.restore();
}
}
}
}
// Now, to render an animation frame:
function render_planet(t, fractional_t, planet, ctx, canvas, unit_count) {
// Convenience dimension variables
var w = planet_maps[planet][0].length, h = planet_maps[planet].length;
// This is used to invert the y-axis
function flipY(oy) { return (h - oy - 1); }
ctx.clearRect(0, 0, canvas.width, canvas.height);
render_planet_background(t, planet, ctx);
if (planet == "Mars") render_rocket_landings(t + fractional_t, ctx, canvas);
// Render units
var unit_locations = {};
var unit_types = {};
let prevUnits = {}
if (t > 0) {
for (var i = 0; i < data[t - 1].units.length; i += 1) {
var unit = data[t - 1].units[i];
unit_locations[unit.id] = [unit.location.x, unit.location.y, unit.location.planet];
prevUnits[unit.id] = unit;
}
}
render_units(t, fractional_t, planet, ctx, unit_locations, unit_types, prevUnits, unit_count);
render_attacks(t, fractional_t, planet, ctx, unit_locations, unit_types, prevUnits);
}
function render_graph(ctx, values, x, y, w, h, colors) {
ctx.save();
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.fillStyle = "#222";
ctx.strokeStyle = "#000";
ctx.fill();