-
Notifications
You must be signed in to change notification settings - Fork 2
/
tily.dev.js
4322 lines (3992 loc) · 140 KB
/
tily.dev.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() {
/**
* @namespace
*/
const Tily = {};
Tily.utility = {
clamp: function(a, min, max) {
if (min === undefined) { min = 0; };
if (max === undefined) { max = 1; };
return (a < min ? min : (a > max ? max : a));
},
lerp: function(a, b, i) {
return a * (1 - i) + b * i;
},
colour: function(c) {
return `rgba(${Math.round(c.r)},${Math.round(c.g)},${Math.round(c.b)},${Math.round(c.a * 100) / 100})`;
},
outline: function(s) {
const parts = s.split(' ');
return {
width: parseFloat(parts[0]) || 0.1,
colour: parts[1] || 'transparent'
};
},
shadow: function(s) {
const parts = s.split(' ');
return {
blur: parseFloat(parts[0] || 1),
xOffset: parseFloat(parts[1] || 0),
yOffset: parseFloat(parts[2] || 0),
colour: parts[3]
};
},
parseColor: (function() {
const names = {
"aliceblue": "f0f8ff",
"antiquewhite": "faebd7",
"aqua": "0ff",
"aquamarine": "7fffd4",
"azure": "f0ffff",
"beige": "f5f5dc",
"bisque": "ffe4c4",
"black": "000",
"blanchedalmond": "ffebcd",
"blue": "00f",
"blueviolet": "8a2be2",
"brown": "a52a2a",
"burlywood": "deb887",
"cadetblue": "5f9ea0",
"chartreuse": "7fff00",
"chocolate": "d2691e",
"coral": "ff7f50",
"cornflowerblue": "6495ed",
"cornsilk": "fff8dc",
"crimson": "dc143c",
"cyan": "0ff",
"darkblue": "00008b",
"darkcyan": "008b8b",
"darkgoldenrod": "b8860b",
"darkgray": "a9a9a9",
"darkgreen": "006400",
"darkgrey": "a9a9a9",
"darkkhaki": "bdb76b",
"darkmagenta": "8b008b",
"darkolivegreen": "556b2f",
"darkorange": "ff8c00",
"darkorchid": "9932cc",
"darkred": "8b0000",
"darksalmon": "e9967a",
"darkseagreen": "8fbc8f",
"darkslateblue": "483d8b",
"darkslategray": "2f4f4f",
"darkslategrey": "2f4f4f",
"darkturquoise": "00ced1",
"darkviolet": "9400d3",
"deeppink": "ff1493",
"deepskyblue": "00bfff",
"dimgray": "696969",
"dimgrey": "696969",
"dodgerblue": "1e90ff",
"firebrick": "b22222",
"floralwhite": "fffaf0",
"forestgreen": "228b22",
"fuchsia": "f0f",
"gainsboro": "dcdcdc",
"ghostwhite": "f8f8ff",
"gold": "ffd700",
"goldenrod": "daa520",
"gray": "808080",
"green": "008000",
"greenyellow": "adff2f",
"grey": "808080",
"honeydew": "f0fff0",
"hotpink": "ff69b4",
"indianred": "cd5c5c",
"indigo": "4b0082",
"ivory": "fffff0",
"khaki": "f0e68c",
"lavender": "e6e6fa",
"lavenderblush": "fff0f5",
"lawngreen": "7cfc00",
"lemonchiffon": "fffacd",
"lightblue": "add8e6",
"lightcoral": "f08080",
"lightcyan": "e0ffff",
"lightgoldenrodyellow": "fafad2",
"lightgray": "d3d3d3",
"lightgreen": "90ee90",
"lightgrey": "d3d3d3",
"lightpink": "ffb6c1",
"lightsalmon": "ffa07a",
"lightseagreen": "20b2aa",
"lightskyblue": "87cefa",
"lightslategray": "789",
"lightslategrey": "789",
"lightsteelblue": "b0c4de",
"lightyellow": "ffffe0",
"lime": "0f0",
"limegreen": "32cd32",
"linen": "faf0e6",
"magenta": "f0f",
"maroon": "800000",
"mediumaquamarine": "66cdaa",
"mediumblue": "0000cd",
"mediumorchid": "ba55d3",
"mediumpurple": "9370db",
"mediumseagreen": "3cb371",
"mediumslateblue": "7b68ee",
"mediumspringgreen": "00fa9a",
"mediumturquoise": "48d1cc",
"mediumvioletred": "c71585",
"midnightblue": "191970",
"mintcream": "f5fffa",
"mistyrose": "ffe4e1",
"moccasin": "ffe4b5",
"navajowhite": "ffdead",
"navy": "000080",
"oldlace": "fdf5e6",
"olive": "808000",
"olivedrab": "6b8e23",
"orange": "ffa500",
"orangered": "ff4500",
"orchid": "da70d6",
"palegoldenrod": "eee8aa",
"palegreen": "98fb98",
"paleturquoise": "afeeee",
"palevioletred": "db7093",
"papayawhip": "ffefd5",
"peachpuff": "ffdab9",
"peru": "cd853f",
"pink": "ffc0cb",
"plum": "dda0dd",
"powderblue": "b0e0e6",
"purple": "800080",
"rebeccapurple": "639",
"red": "f00",
"rosybrown": "bc8f8f",
"royalblue": "4169e1",
"saddlebrown": "8b4513",
"salmon": "fa8072",
"sandybrown": "f4a460",
"seagreen": "2e8b57",
"seashell": "fff5ee",
"sienna": "a0522d",
"silver": "c0c0c0",
"skyblue": "87ceeb",
"slateblue": "6a5acd",
"slategray": "708090",
"slategrey": "708090",
"snow": "fffafa",
"springgreen": "00ff7f",
"steelblue": "4682b4",
"tan": "d2b48c",
"teal": "008080",
"thistle": "d8bfd8",
"tomato": "ff6347",
"turquoise": "40e0d0",
"violet": "ee82ee",
"wheat": "f5deb3",
"white": "fff",
"whitesmoke": "f5f5f5",
"yellow": "ff0",
"yellowgreen": "9acd32",
"transparent": "00000000"
};
const clamp = (n, a, b) => n < a ? a : (n > b ? b : n), // Clamp n in interval [a, b]
round = (n, d) => { // Round n to nearest integer, or to d decimal places (if d is defined)
var p = Math.pow(10, d || 0);
return Math.round(n * p) / p;
},
hi = n => clamp(parseInt(n, 16), 0, 255), // Convert 2-digit hex to int in interval [0, 255]
hf = n => clamp(round(parseInt(n, 16) / 255, 2), 0, 1), // Convert 2-digit hex to float with 2 decimal places in interval [0, 1]
si = n => clamp(round(parseFloat(n)), 0, 255), // Convert string to int in interval [0, 255]
sf = n => clamp(round(parseFloat(n), 2), 0, 1), // Convert string to float with 2 decimal places in interval [0, 1]
pi = n => clamp(round(parseFloat(n) / 100 * 255), 0, 255), // Convert percentage string to int in interval [0, 255]
uf = n => clamp(parseFloat(n) / 360, 0, 1), // Convert hue string to float in interval [0, 1]
pf = n => clamp(parseFloat(n) / 100, 0, 1); // Convert percentage string to float in interval [0, 1]
// Convert hsl to rgb, alpha value gets passed straight through
// h, s, l values are assumed to be in interval [0, 1]
// Returns an object like { r, g, b, a }
// http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c
function hslToRgb(h, s, l, a) {
var r, g, b,
hue = function(p, q, t) {
if (t < 0) { t += 1; }
if (t > 1) { t -= 1; }
if (t < 1 / 6) { return p + (q - p) * 6 * t };
if (t < 1 / 2) { return q; }
if (t < 2 / 3) { return p + (q - p) * (2 / 3 - t) * 6 };
return p;
};
if (s == 0) {
r = g = b = l;
} else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s,
p = 2 * l - q;
r = hue(p, q, h + 1 / 3);
g = hue(p, q, h);
b = hue(p, q, h - 1 / 3);
}
return { r: round(r * 255), g: round(g * 255), b: round(b * 255), a: a };
}
return function(c) {
var o = { r: 0, g: 0, b: 0, a: 0 }, m = null;
if (typeof c == "string") {
if (c in names) { c = "#" + names[c]; }
if ((m = c.match(/#([a-f0-9])([a-f0-9])([a-f0-9])$/i)) !== null) {
o = { r: hi(m[1] + m[1]), g: hi(m[2] + m[2]), b: hi(m[3] + m[3]), a: 1 };
} else if ((m = c.match(/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i)) !== null) {
o = { r: hi(m[1]), g: hi(m[2]), b: hi(m[3]), a: 1 };
} else if ((m = c.match(/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i)) !== null) {
o = { r: hi(m[1]), g: hi(m[2]), b: hi(m[3]), a: hf(m[4]) };
} else if ((m = c.match(/rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/)) !== null) {
o = { r: si(m[1]), g: si(m[2]), b: si(m[3]), a: 1 };
} else if ((m = c.match(/rgb\(\s*(\d{1,3}\.?\d?%)\s*,\s*(\d{1,3}\.?\d?%)\s*,\s*(\d{1,3}\.?\d?%)\s*\)/)) !== null) {
o = { r: pi(m[1]), g: pi(m[2]), b: pi(m[3]), a: 1 };
} else if ((m = c.match(/rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d*?)?\s*\)/)) !== null) {
o = { r: si(m[1]), g: si(m[2]), b: si(m[3]), a: sf(m[4]) };
} else if ((m = c.match(/rgba\(\s*(\d{1,3}\.?\d?%)\s*,\s*(\d{1,3}\.?\d?%)\s*,\s*(\d{1,3}\.?\d?%)\s*,\s*(\d?\.?\d*?)?\s*\)/)) !== null) {
o = { r: pi(m[1]), g: pi(m[2]), b: pi(m[3]), a: sf(m[4]) };
} else if ((m = c.match(/hsl\(\s*(\d{1,3}\.?\d?)\s*,\s*(\d{1,3}\.?\d?%)\s*,\s*(\d{1,3}\.?\d?%)\s*\)/)) !== null) {
o = hslToRgb(uf(m[1]), pf(m[2]), pf(m[3]), 1);
} else if ((m = c.match(/hsla\(\s*(\d{1,3}\.?\d?)\s*,\s*(\d{1,3}\.?\d?%)\s*,\s*(\d{1,3}\.?\d?%)\s*,\s*(\d?\.?\d*?)?\s*\)/)) !== null) {
o = hslToRgb(uf(m[1]), pf(m[2]), pf(m[3]), sf(m[4]));
}
} else if (typeof c == "object") {
if (c.r !== undefined && c.g != undefined && c.b !== undefined) {
o = { r: si(c.r), g: si(c.g), b: si(c.b), a: sf(c.a || 1) };
} else if (c.h !== undefined && c.s !== undefined && c.l !== undefined) {
o = hslToRgb(uf(c.h), pf(c.s), pf(c.l), sf(c.a || 1));
}
}
return o;
};
}())
};
Tily.utility.__extends = (this && this.__extends) || function (d, b) {
for (var p in b) {
if (b.hasOwnProperty(p)) { d[p] = b[p]; }
}
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
"use strict";
/**
* Return a new Tily.utility.vec2 object with the specified x/y coordinates. If the first argument is an array,
* the Tily.utility.vec2 will be initialised using the first 2 elements of the array. If the first argument is
* an object with x and y properties, these will be used instead (this is useful for copying Tily.utility.vec2
* instances). If no arguments are provided, or the arguments are invalid, a zero-vector will be
* returned instead.
* @param {number|Array|Object} x The x-coordinate, or an array with at least 2 elements, or an
* object with x and y properties.
* @param {number} [y] The y-coordinate, if an x-coordinate has also been provided.
* @returns {Object} A Tily.utility.vec2 instance.
* @example
* var v1 = Tily.utility.vec2(2, 1); // v1 == { x: 2, y: 1 }
* var v2 = Tily.utility.vec2([2, 1]); // v2 == { x: 2, y: 1 }
* var v3 = Tily.utility.vec2(v1); // v3 == { x: 2, y: 1 }
*/
Tily.utility.vec2 = function(x, y) {
if (arguments.length == 1) {
if (x instanceof Array && x.length > 1) { // Tily.utility.vec2 from array
return { x: x[0], y: x[1] };
} else if (x.x !== undefined && x.y !== undefined) {
return { x: x.x, y: x.y }; // Tily.utility.vec2 from Tily.utility.vec2 (copy)
}
return { x: 0, y: 0 }; // Arguments incorrect, return [0, 0]
}
return { x: x || 0, y: y || 0 };
};
/**
* @callback mapCallback
* @param {number} x The x or y component of the vector.
* @param {...*} arguments Any additional arguments passed to Tily.utility.vec2.map.
* @returns {boolean} True if the current element is the one being searched for.
*/
/**
* Return a new vector from v by mapping it's components to f.
* @param {Tily.utility.vec2} v The vector to transform.
* @param {mapCallback} f A callback that will be called for both the x and y components.
* @param {...*} arguments Additional arguments will be passed to f for each component.
* @returns {Tily.utility.vec2} The transformed vector.
* @example
* var v = Tily.utility.vec2(1.5, 2.5);
* v = Tily.utility.vec2.map(v, Math.floor); // v == { x: 1, y: 2 }
*/
Tily.utility.vec2.map = function(v, f) {
var args = arguments.length == 1 ? [arguments[0]] : Array.apply(null, arguments);
args = Array.prototype.slice.call(args, 2);
return Tily.utility.vec2(f.apply(this, [v.x].concat(args)), f.apply(this, [v.y].concat(args)));
};
/**
* Get the length of a vector.
* @param {Tily.utility.vec2} v The vector.
* @returns {number} The vector's length.
*/
Tily.utility.vec2.len = function(v) {
return Math.sqrt(v.x * v.x + v.y * v.y);
};
/**
* Get the angle of a vector in radians.
* @param {Tily.utility.vec2} v The vector.
* @returns {number} The angle of the vector in radians.
*/
Tily.utility.vec2.rad = function(v) {
return Math.atan2(v.y, v.x);
};
/**
* Get the dot product of two vectors.
* @param {Tily.utility.vec2} v1 The first vector.
* @param {Tily.utility.vec2} v2 The second vector.
* @returns {number} The dot product of v1 and v2.
*/
Tily.utility.vec2.dot = function(v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
};
/**
* Normalise a vector
* @param {Tily.utility.vec2} v The vector.
* @returns {Tily.utility.vec2} The normalised vector.
*/
Tily.utility.vec2.norm = function(v) {
var length = Tily.utility.vec2.len(v);
if (length) {
return Tily.utility.vec2.div(v, length);
}
return Tily.utility.vec2();
};
/**
* Reflect a vector across a plane with normal n
* @param {Tily.utility.vec2} v The vector.
* @param {Tily.utility.vec2} n The plane normal vector.
* @returns {Tily.utility.vec2} The reflected vector.
*/
Tily.utility.vec2.reflect = function(v, n) {
return Tily.utility.vec2.add(v, Tily.utility.vec2.mul(Tily.utility.vec2.mul(n, Tily.utility.vec2.dot(v, n)), -2));
};
/**
* Get the cross product of two vectors. The z-coord is assumed to be 0, since these are 2d vectors.
* @param {Tily.utility.vec2} v1 The first vector.
* @param {Tily.utility.vec2} v2 The second vector.
* @returns {number} The cross product of v1 and v2.
*/
Tily.utility.vec2.cross = function(v1, v2) {
return v1.x * v2.y - v1.y * v2.x;
};
/**
* Rotate a vector.
* @param {Tily.utility.vec2} v The vector.
* @param {number} r The amount to rotate the vector by, in radians.
* @returns {Tily.utility.vec2} The rotated vector.
*/
Tily.utility.vec2.rot = function(v, r) {
var sinAngle = Math.sin(r),
cosAngle = Math.cos(r),
x = cosAngle * v.x - sinAngle * v.y,
y = sinAngle * v.x + cosAngle * v.y;
return Tily.utility.vec2(x, y);
};
/**
* Add two vectors or add a scalar to each component.
* @param {Tily.utility.vec2} v1 The first vector.
* @param {Tily.utility.vec2|number} v2 The second vector, or a scalar value to add to each component of v1.
* @returns {Tily.utility.vec2} The sum of v1 and v2.
*/
Tily.utility.vec2.add = function(v1, v2) {
if (v2.x !== undefined && v2.y !== undefined) {
return Tily.utility.vec2(v1.x + v2.x, v1.y + v2.y);
} else {
return Tily.utility.vec2(v1.x + v2, v1.y + v2);
}
};
/**
* Subtract two vectors.
* @param {Tily.utility.vec2} v1 The first vector.
* @param {Tily.utility.vec2|number} v2 The second vector, or a scalar value to subtract from each component of
* v1.
* @returns {Tily.utility.vec2} The difference of v1 and v2.
*/
Tily.utility.vec2.sub = function(v1, v2) {
if (v2.x !== undefined && v2.y !== undefined) {
return Tily.utility.vec2(v1.x - v2.x, v1.y - v2.y);
} else {
return Tily.utility.vec2(v1.x - v2, v1.y - v2);
}
};
/**
* Multiply two vectors.
* @param {Tily.utility.vec2} v1 The first vector.
* @param {Tily.utility.vec2|number} v2 The second vector, or a scalar value to multiply each component of v1 by.
* @returns {Tily.utility.vec2} The product of v1 and v2.
*/
Tily.utility.vec2.mul = function(v1, v2) {
if (v2.x !== undefined && v2.y !== undefined) {
return Tily.utility.vec2(v1.x * v2.x, v1.y * v2.y);
} else {
return Tily.utility.vec2(v1.x * v2, v1.y * v2);
}
};
/**
* Divide two vectors.
* @param {Tily.utility.vec2} v1 The first vector.
* @param {Tily.utility.vec2|number} v2 The second vector, or a scalar value to divide each component of v1 by.
* @returns {Tily.utility.vec2} The quotient of v1 and v2.
*/
Tily.utility.vec2.div = function(v1, v2) {
if (v2.x !== undefined && v2.y !== undefined) {
return Tily.utility.vec2(v1.x / v2.x, v1.y / v2.y);
} else {
return Tily.utility.vec2(v1.x / v2, v1.y / v2);
}
};
/**
* Check if two vectors are equal.
* @param {Tily.utility.vec2} v1 The first vector.
* @param {Tily.utility.vec2} v2 The second vector.
* @returns {boolean} True if the vectors are equal.
*/
Tily.utility.vec2.eq = function(v1, v2) {
return (v1.x == v2.x && v1.y == v2.y);
};
/**
* Convert a string representation of a vector (like '0,0' or '0, 0') into a Tily.utility.vec2.
* @param {string} s The string representation of the vector.
* @returns {Tily.utility.vec2} The resulting Tily.utility.vec2, or a zero-vector if the string couldn't be parsed.
*/
Tily.utility.vec2.fromString = function(s) {
var values = s.split(",", 2);
if (values.length == 2) {
var x = parseFloat(values[0]),
y = parseFloat(values[1]);
return Tily.utility.vec2(x, y);
}
return Tily.utility.vec2(0, 0);
};
/**
* Convert a Tily.utility.vec2 into a string.
* @param {Tily.utility.vec2} v The vector to convert.
* @param {string} [s=','] An optional separator string.
* @returns {string} The string representation of v.
*/
Tily.utility.vec2.toString = function(v, s) {
return v.x + (s !== undefined ? s : ",") + v.y;
};
Tily.Main = (function() {
"use strict";
/**
* @typedef Size
* @type {Object}
* @property {number} width The width.
* @property {number} height The height.
*/
/**
* @callback beforeDrawFunction
* @param {number} elapsedTime The time elapsed in seconds since the last draw call.
*/
/**
* @callback afterDrawFunction
* @param {number} elapsedTime The time elapsed in seconds since the last draw call.
*/
/**
* @typedef TilyOptions
* @type {Object}
* @property {?Size} [size=null] The viewport size, or null to use the canvas element
* dimensions.
* @property {boolean} [handleResize=true] True if the window resize event should be handled.
* @property {boolean} [showFPS=false] True if the FPS should be displayed.
* @property {boolean} [renderLoop=true] True if the render loop should be started
* automatically.
* @property {?beforeDrawFunction} [beforeDrawFunction=null] A function that will be called
* after clearing the context but before drawing the active buffer. In the context of the
* function, 'this' will point to the Tily instance.
* @property {?afterDrawFunction} [afterDrawFunction=null] A function that will be called after
* drawing the active buffer. In the context of the function, 'this' will point to the Tily instance.
*/
/**
* Default Tily options, used as a fall-back for options passed to the constructor.
* @type {TilyOptions}
*/
const _defaultTilyOptions = {
size: null,
handleResize: true,
showFPS: false,
renderLoop: true,
beforeDrawFunction: null,
afterDrawFunction: null
};
/**
* The main Tily object. Initialises a canvas element and starts drawing tiles.
* @class
* @memberof Tily
* @param {HTMLElement} canvas The canvas element in which to draw tiles.
* @param {TilyOptions} [options] An optional object containing options for configuring this
* Tily instance.
*/
function Main(canvas, options) {
if (!window) { // Check that we are in a browser (ie. window exists)
console.log("Couldn't find window. Tily.Main can only be created in the browser!");
return
}
if (!canvas.getContext) { // Check for canvas support
console.log("Canvas not supported!");
return;
}
/**
* Options for configuring this Tily instance.
* @type {TilyOptions}
*/
this.options = { ..._defaultTilyOptions, ...options || {} };
/**
* The canvas element in which to draw tiles.
* @type {HTMLElement}
*/
this.canvas = canvas;
/**
* The context on which to draw tiles.
* @type {CanvasRenderingContext2D}
*/
this.context = canvas.getContext("2d");
/**
* The viewport width.
* @type {number}
*/
this.width = 0;
/**
* The viewport height.
* @type {number}
*/
this.height = 0;
/**
* The buffer currently being rendered.
* @type {Tily.BufferBase}
*/
this.activeBuffer = null;
/**
* The currently running buffer transition or null if there is no currently running
* transition.
* @default null
* @type {?Tily.BufferTransition}
*/
this.bufferTransition = null;
/**
* A request id returned from window.requestAnimationFrame that uniquely identifies the
* entry in the callback list for the main render loop.
* @type {number}
*/
this.loop = null;
/**
* The unix epoch time of the last rendered frame.
* @type {number}
*/
this.lastFrameTime = new Date();
/**
* The number of frames rendered in the last second.
* @type {number}
*/
this.frameCount = 0;
/**
* The number of milliseconds elapsed since the last framerate update.
* @type {number}
*/
this.frameTime = 0;
/**
* The number of frames rendered per second.
* @type {number}
*/
this.frameRate = 0;
// Handle the window resize event to get the current viewport size or use a fixed size
if (!this.options.size || this.options.handleResize) {
const self = this;
function resize() {
self.canvas.width = self.width = canvas.clientWidth * window.devicePixelRatio;
self.canvas.height = self.height = canvas.clientHeight * window.devicePixelRatio;
}
window.addEventListener("resize", resize, false);
resize();
} else {
this.canvas.width = this.width = this.options.size.width;
this.canvas.height = this.height = this.options.size.height;
}
// Start the render loop
if (this.options.renderLoop) {
loop(this);
}
}
/**
* Perform a single iteration of the render loop.
* @param {Tily.Main} t The Tily instance being looped.
*/
function loop(t) {
const now = new Date(),
elapsedTime = (now - t.lastFrameTime) / 1000;
t.lastFrameTime = now;
t.frameTime += elapsedTime;
t.frameCount++;
if (t.frameTime > 1) {
t.frameRate = t.frameCount;
t.frameTime = 0;
t.frameCount = 0;
}
t.draw(elapsedTime);
t.loop = window.requestAnimationFrame(function() { loop(t) });
}
/**
* Render the Tily instance onto the canvas.
* @name draw
* @function
* @instance
* @memberof Tily.Main
* @param {number} elapsedTime The time elapsed in seconds since the last draw call.
*/
Main.prototype.draw = function(elapsedTime) {
this.context.save();
this.context.clearRect(0, 0, this.width, this.height);
if (typeof this.options.beforeDrawFunction == "function") {
this.options.beforeDrawFunction.call(this, this.canvas, this.context, this.width, this.height, elapsedTime);
}
// Draw the active buffer and handle buffer fade transition
const width = this.width,
height = this.height;
if (this.bufferTransition) {
const alpha = this.bufferTransition.update(elapsedTime);
if (this.bufferTransition.start) {
this.context.globalAlpha = 1 - alpha;
this.bufferTransition.start.draw(this.context, elapsedTime, width, height);
}
if (this.bufferTransition.finish) {
this.context.globalAlpha = alpha;
this.bufferTransition.finish.draw(this.context, elapsedTime, width, height);
}
if (this.bufferTransition.finished) { // Remove the transition when it has finished
this.bufferTransition = null;
}
} else if (this.activeBuffer) {
this.context.globalAlpha = 1;
this.activeBuffer.draw(this.context, elapsedTime, width, height);
}
if (typeof this.options.afterDrawFunction == "function") {
this.options.afterDrawFunction.call(this, this.canvas, this.context, this.width, this.height, elapsedTime);
}
this.context.restore();
if (this.options.showFPS) {
this.context.save();
this.context.font = '20px monospace';
this.context.fillStyle = 'rgba(0, 0, 0, 0.5)';
this.context.fillRect(this.width - (10 + 80), 10, 80, 30);
this.context.fillStyle = 'white';
this.context.textBaseline = 'top';
this.context.textAlign = 'right';
this.context.fillText(this.frameRate, this.width - 15, 15);
this.context.restore();
}
};
/**
* Activate a new buffer with an optional fade transition from the current buffer.
* @name activateBuffer
* @function
* @instance
* @memberof Tily.Main
* @param {Tily.Buffer} buffer The new buffer to activate.
* @param {TransitionOptions} [options] An optional options object.
* @returns {Promise} A promise instance for setting a transition finished callback.
*/
Main.prototype.activateBuffer = function(buffer, options) {
const transition = new Tily.BufferTransition(this.activeBuffer, buffer, options);
this.bufferTransition = transition;
this.activeBuffer = buffer;
return new Promise(function(resolve, reject) { transition.finishedCallback = resolve; });
};
/**
* @name size
* @description The size of this Tily element measured in pixels.
* @instance
* @memberof Tily.Main
* @type {Size}
*/
Object.defineProperty(Main.prototype, "size", {
get: function() {
return {
width: this.width,
height: this.height
};
}
});
return Main;
}());
Tily.Transition = (function() {
"use strict";
/**
* @callback easeFunction
* @param {any} a The starting value.
* @param {any} b The finishing value.
* @param {number} i The interpolation value, between 0 (start) and 1 (finish).
* @returns {any} The interpolated value between a and b.
*/
/**
* @callback finishedCallback
* @param {any} start The previous value before transitioning.
* @param {any} finish The new value after transitioning.
*/
/**
* @typedef TransitionOptions
* @type {Object}
* @property {number} [time=0] The amount of time in seconds that this transition should take
* to complete.
* @property {easeFunction} [easeFunction=Tily.utility.lerp] The easing function to use while
* transitioning.
* @property {?finishedCallback} [finishedCallback=null] A callback function that will be
* called once the transition has finished.
*/
/**
* Default transition options, used as a fall-back for options passed to the constructor.
* @type {TransitionOptions}
*/
const _defaultTransitionOptions = {
time: 0,
easeFunction: null,
finishedCallback: null
};
/**
* Represents a timed transition from one value to another.
* @class
* @memberof Tily
* @param {any} start The starting value.
* @param {any} finish The finishing value.
* @options {TransitionOptions} [options] An optional options object for configuring the
* transition.
*/
function Transition(start, finish, options) {
options = { ..._defaultTransitionOptions, ...options || {} };
/**
* The starting value.
* @type {any}
*/
this.start = start;
/**
* The finishing value.
* @type {any}
*/
this.finish = finish;
/**
* The total amount of time that this transition should take.
* @type {number}
*/
this.totalTime = options.time;
/**
* The current time elapsed since the transition began.
* @type {number}
*/
this.currentTime = 0;
/**
* The easing function to use while transitioning.
* @default Tily.utility.lerp
* @type {easeFunction}
*/
this.easeFunction = options.easeFunction || Tily.utility.lerp;
/**
* A callback function that will be called once the transition has finished.
* @default null
* @type {?finishedCallback}
*/
this.finishedCallback = options.finishedCallback || function(start, finish) { };
/**
* True if this transition has finished and can be discarded.
* @type {boolean}
*/
this.finished = false;
}
/**
* Update the transition.
* @name update
* @function
* @instance
* @memberof Tily.Transition
* @param {number} elapsedTime The number of seconds that have elapsed since the last update.
* @returns {any} An interpolated value between the start and finish values.
*/
Transition.prototype.update = function(elapsedTime) {
this.currentTime += elapsedTime;
// If transition is currently in progress, ease from start to finish value
if (this.currentTime < this.totalTime) {
return this.easeFunction(this.start, this.finish, this.amount);
}
// Otherwise, transition has finished
if (this.finishedCallback && !this.finished) {
this.finishedCallback(this.start, this.finish);
}
this.finished = true;
return this.finish;
};
/**
* @name amount
* @description The current interpolation amount between 0 and 1 (inclusive).
* @instance
* @memberof Tily.Transition
* @type {number}
*/
Object.defineProperty(Transition.prototype, "amount", {
get: function() {
return Tily.utility.clamp(this.currentTime / this.totalTime);
}
});
return Transition;
}());
Tily.BufferTransition = (function(_super) {
"use strict";
Tily.utility.__extends(BufferTransition, _super);
/**
* Represents a buffer transition for fading from one buffer to another.
* @class
* @extends Tily.Transition
* @memberof Tily
* @param {Tily.Buffer} start The starting buffer.
* @param {Tily.Buffer} finish The finishing buffer.
* @param {TransitionOptions} [options] An optional options object for configuring the
* transition.
*/
function BufferTransition(start, finish, options) {
_super.call(this, start, finish, options);
}
/**
* Update the transition.
* @name update
* @function
* @instance
* @memberof Tily.BufferTransition
* @param {number} elapsedTime The number of seconds that have elapsed since the last update.
* @returns {number} An interpolated alpha value between 0 and 1.
*/
BufferTransition.prototype.update = function(elapsedTime) {
this.currentTime += elapsedTime;
// If transition is currently in progress, ease from start to finish value
if (this.currentTime < this.totalTime) {
return this.easeFunction(0, 1, this.amount);
}
// Otherwise, transition has finished
if (this.finishedCallback && !this.finished) {
this.finishedCallback(this.start, this.finish);
}
this.finished = true;
return 1;
};
return BufferTransition;
}(Tily.Transition));
Tily.OffsetTransition = (function(_super) {
"use strict";
Tily.utility.__extends(OffsetTransition, _super);
/**
* Represents an offset position transition for moving the buffer camera with a movement
* animation.
* @class
* @extends Tily.Transition
* @memberof Tily
* @param {Tily.utility.vec2} start The starting offset.
* @param {Tily.utility.vec2} finish The finishing offset.
* @param {TransitionOptions} [options] An optional options object for configuring the
* transition.
*/
function OffsetTransition(start, finish, options) {
_super.call(this, start, finish, options);
}
/**
* Update the transition.
* @name update
* @function
* @instance
* @memberof Tily.OffsetTransition
* @param {number} elapsedTime The number of seconds that have elapsed since the last update.
* @returns {number} An interpolated offset value between the start and finish offsets.
*/
OffsetTransition.prototype.update = function(elapsedTime) {
this.currentTime += elapsedTime;
// If transition is currently in progress, ease from start to finish value
if (this.currentTime < this.totalTime) {
const amount = this.amount;
return Tily.utility.vec2(
this.easeFunction(this.start.x, this.finish.x, amount),
this.easeFunction(this.start.y, this.finish.y, amount)
);
}
// Otherwise, transition has finished
if (this.finishedCallback && !this.finished) {
this.finishedCallback(this.start, this.finish);
}
this.finished = true;
return this.finish;
};
return OffsetTransition;
}(Tily.Transition));
Tily.ScaleTransition = (function(_super) {
"use strict";
Tily.utility.__extends(ScaleTransition, _super);
/**
* Represents a scale transition for zooming a buffer in/out with a zoom animation.
* @class
* @extends Tily.Transition
* @memberof Tily
* @param {number} start The starting scale.
* @param {number} finish The finishing scale.
* @param {TransitionOptions} [options] An optional options object for configuring the
* transition.
*/
function ScaleTransition(start, finish, options) {
_super.call(this, start, finish, options);
}