forked from GameJs/gamejs
/
gamejs.js
874 lines (807 loc) · 23.4 KB
/
gamejs.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
var matrix = require('./gamejs/utils/matrix');
var objects = require('./gamejs/utils/objects');
/**
* @fileoverview This module holds the essential `Rect` and `Surface` classes as
* well as static methods for preloading assets. `gamejs.ready()` is maybe
* the most important as it kickstarts your app.
*
*/
var DEBUG_LEVELS = ['info', 'warn', 'error', 'fatal'];
var debugLevel = 2;
/**
* set logLevel as string or number
* * 0 = info
* * 1 = warn
* * 2 = error
* * 3 = fatal
*
* @example
* gamejs.setLogLevel(0); // debug
* gamejs.setLogLevel('error'); // equal to setLogLevel(2)
*/
exports.setLogLevel = function(logLevel) {
if (typeof logLevel === 'string' && DEBUG_LEVELS.indexOf(logLevel)) {
debugLevel = DEBUG_LEVELS.indexOf(logLevel);
} else if (typeof logLevel === 'number') {
debugLevel = logLevel;
} else {
throw new Error('invalid logLevel ', logLevel, ' Must be one of: ', DEBUG_LEVELS);
}
return debugLevel;
};
/**
* Log a msg to the console if console is enable
* @param {String} msg the msg to log
*/
var log = exports.log = function() {
// IEFIX can't call apply on console
var args = Array.prototype.slice.apply(arguments, [0]);
args.unshift(Date.now());
if (window.console !== undefined && console.log.apply) {
console.log.apply(console, args);
}
};
exports.info = function() {
if (debugLevel <= DEBUG_LEVELS.indexOf('info')) {
log.apply(this, arguments);
}
};
exports.warn = function() {
if (debugLevel <= DEBUG_LEVELS.indexOf('warn')) {
log.apply(this, arguments);
}
};
exports.error = function() {
if (debugLevel <= DEBUG_LEVELS.indexOf('error')) {
log.apply(this, arguments);
}
};
exports.fatal = function() {
if (debugLevel <= DEBUG_LEVELS.indexOf('fatal')) {
log.apply(this, arguments);
}
};
/**
* Normalize various ways to specify a Rect into {left, top, width, height} form.
*
*/
function normalizeRectArguments() {
var left = 0;
var top = 0;
var width = 0;
var height = 0;
if (arguments.length === 2) {
if (arguments[0] instanceof Array && arguments[1] instanceof Array) {
left = arguments[0][0];
top = arguments[0][1];
width = arguments[1][0];
height = arguments[1][1];
} else {
left = arguments[0];
top = arguments[1];
}
} else if (arguments.length === 1 && arguments[0] instanceof Array) {
left = arguments[0][0];
top = arguments[0][1];
width = arguments[0][2];
height = arguments[0][3];
} else if (arguments.length === 1 && arguments[0] instanceof Rect) {
left = arguments[0].left;
top = arguments[0].top;
width = arguments[0].width;
height = arguments[0].height;
} else if (arguments.length === 4) {
left = arguments[0];
top = arguments[1];
width = arguments[2];
height = arguments[3];
} else {
throw new Error('not a valid rectangle specification');
}
return {left: left || 0, top: top || 0, width: width || 0, height: height || 0};
}
/**
* Creates a Rect. Rects are used to hold rectangular areas. There are a couple
* of convinient ways to create Rects with different arguments and defaults.
*
* Any function that requires a `gamejs.Rect` argument also accepts any of the
* constructor value combinations `Rect` accepts.
*
* Rects are used a lot. They are good for collision detection, specifying
* an area on the screen (for blitting) or just to hold an objects position.
*
* The Rect object has several virtual attributes which can be used to move and align the Rect:
*
* top, left, bottom, right
* topleft, bottomleft, topright, bottomright
* center
* width, height
* w,h
*
* All of these attributes can be assigned to.
* Assigning to width or height changes the dimensions of the rectangle; all other
* assignments move the rectangle without resizing it. Notice that some attributes
* are Numbers and others are pairs of Numbers.
*
* @example
* new Rect([left, top]) width & height default to 0
* new Rect(left, top) width & height default to 0
* new Rect(left, top, width, height)
* new Rect([left, top], [width, height])
* new Rect(oldRect) clone of oldRect is created
*
* @property {Number} right
* @property {Number} bottom
* @property {Number} center
*
* @param {Array|gamejs.Rect} position Array holding left and top coordinates
* @param {Array} dimensions Array holding width and height
*/
var Rect = exports.Rect = function() {
var args = normalizeRectArguments.apply(this, arguments);
/**
* Left, X coordinate
* @type Number
*/
this.left = args.left;
/**
* Top, Y coordinate
* @type Number
*/
this.top = args.top;
/**
* Width of rectangle
* @type Number
*/
this.width = args.width;
/**
* Height of rectangle
* @type Number
*/
this.height = args.height;
return this;
};
objects.accessors(Rect.prototype, {
/**
* Bottom, Y coordinate
* @name Rect.prototype.bottom
* @type Number
*/
'bottom': {
get: function() {
return this.top + this.height;
},
set: function(newValue) {
this.top = newValue - this.height;
return;
}
},
/**
* Right, X coordinate
* @name Rect.prototype.right
* @type Number
*/
'right': {
get: function() {
return this.left + this.width;
},
set: function(newValue) {
this.left = newValue - this.width;
}
},
/**
* Center Position. You can assign a rectangle form.
* @name Rect.prototype.center
* @type Array
*/
'center': {
get: function() {
return [this.left + (this.width / 2),
this.top + (this.height / 2)
];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.left = args.left - (this.width / 2);
this.top = args.top - (this.height / 2);
return;
}
},
/**
* Top-left Position. You can assign a rectangle form.
* @name Rect.prototype.topleft
* @type Array
*/
'topleft': {
get: function() {
return [this.left, this.top];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.left = args.left;
this.top = args.top;
return;
}
},
/**
* Bottom-left Position. You can assign a rectangle form.
* @name Rect.prototype.bottomleft
* @type Array
*/
'bottomleft': {
get: function() {
return [this.left, this.bottom];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.left = args.left;
this.bottom = args.bottom;
return;
}
},
/**
* Top-right Position. You can assign a rectangle form.
* @name Rect.prototype.topright
* @type Array
*/
'topright': {
get: function() {
return [this.right, this.top];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.right = args.right;
this.top = args.top;
return;
}
},
/**
* Bottom-right Position. You can assign a rectangle form.
* @name Rect.prototype.bottomright
* @type Array
*/
'bottomright': {
get: function() {
return [this.right, this.bottom];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.right = args.right;
this.bottom = args.bottom;
return;
}
},
/**
* Position x value, alias for `left`.
* @name Rect.prototype.y
* @type Array
*/
'x': {
get: function() {
return this.left;
},
set: function(newValue) {
this.left = newValue;
return;
}
},
/**
* Position y value, alias for `top`.
* @name Rect.prototype.y
* @type Array
*/
'y': {
get: function() {
return this.top;
},
set: function(newValue) {
this.top = newValue;
return;
}
}
});
/**
* Move returns a new Rect, which is a version of this Rect
* moved by the given amounts. Accepts any rectangle form.
* as argument.
*
* @param {Number|gamejs.Rect} x amount to move on x axis
* @param {Number} y amount to move on y axis
*/
Rect.prototype.move = function() {
var args = normalizeRectArguments.apply(this, arguments);
return new Rect(this.left + args.left, this.top + args.top, this.width, this.height);
};
/**
* Move this Rect in place - not returning a new Rect like `move(x, y)` would.
*
* `moveIp(x,y)` or `moveIp([x,y])`
*
* @param {Number|gamejs.Rect} x amount to move on x axis
* @param {Number} y amount to move on y axis
*/
Rect.prototype.moveIp = function() {
var args = normalizeRectArguments.apply(this, arguments);
this.left += args.left;
this.top += args.top;
return;
};
/**
* Return the area in which this Rect and argument Rect overlap.
*
* @param {gamejs.Rect} Rect to clip this one into
* @returns {gamejs.Rect} new Rect which is completely inside the argument Rect,
* zero sized Rect if the two rectangles do not overlap
*/
Rect.prototype.clip = function(rect) {
if(!this.collideRect(rect)) {
return new Rect(0,0,0,0);
}
var x, y, width, height;
// Left
if ((this.left >= rect.left) && (this.left < rect.right)) {
x = this.left;
} else if ((rect.left >= this.left) && (rect.left < this.right)) {
x = rect.left;
}
// Right
if ((this.right > rect.left) && (this.right <= rect.right)) {
width = this.right - x;
} else if ((rect.right > this.left) && (rect.right <= this.right)) {
width = rect.right - x;
}
// Top
if ((this.top >= rect.top) && (this.top < rect.bottom)) {
y = this.top;
} else if ((rect.top >= this.top) && (rect.top < this.bottom)) {
y = rect.top;
}
// Bottom
if ((this.bottom > rect.top) && (this.bottom <= rect.bottom)) {
height = this.bottom - y;
} else if ((rect.bottom > this.top) && (rect.bottom <= this.bottom)) {
height = rect.bottom - y;
}
return new Rect(x, y, width, height);
};
/**
* Join two rectangles
*
* @param {gamejs.Rect} union with this rectangle
* @returns {gamejs.Rect} rectangle containing area of both rectangles
*/
Rect.prototype.union = function(rect) {
var x, y, width, height;
x = Math.min(this.left, rect.left);
y = Math.min(this.top, rect.top);
width = Math.max(this.right, rect.right) - x;
height = Math.max(this.bottom, rect.bottom) - y;
return new Rect(x, y, width, height);
};
/**
* Check for collision with a point.
*
* `collidePoint(x,y)` or `collidePoint([x,y])` or `collidePoint(new Rect(x,y))`
*
* @param {Array|gamejs.Rect} point the x and y coordinates of the point to test for collision
* @returns {Boolean} true if the point collides with this Rect
*/
Rect.prototype.collidePoint = function() {
var args = normalizeRectArguments.apply(this, arguments);
return (this.left <= args.left && args.left <= this.right) &&
(this.top <= args.top && args.top <= this.bottom);
};
/**
* Check for collision with a Rect.
* @param {gamejs.Rect} rect the Rect to test check for collision
* @returns {Boolean} true if the given Rect collides with this Rect
*/
Rect.prototype.collideRect = function(rect) {
return !(this.left > rect.right || this.right < rect.left ||
this.top > rect.bottom || this.bottom < rect.top);
};
/**
* @param {Array} pointA start point of the line
* @param {Array} pointB end point of the line
* @returns true if the line intersects with the rectangle
* @see http://stackoverflow.com/questions/99353/how-to-test-if-a-line-segment-intersects-an-axis-aligned-rectange-in-2d/293052#293052
*
*/
Rect.prototype.collideLine = function(p1, p2) {
var x1 = p1[0];
var y1 = p1[1];
var x2 = p2[0];
var y2 = p2[1];
function linePosition(point) {
var x = point[0];
var y = point[1];
return (y2 - y1) * x + (x1 - x2) * y + (x2 * y1 - x1 * y2);
}
var relPoses = [[this.left, this.top],
[this.left, this.bottom],
[this.right, this.top],
[this.right, this.bottom]
].map(linePosition);
var noNegative = true;
var noPositive = true;
var noZero = true;
relPoses.forEach(function(relPos) {
if (relPos > 0) {
noPositive = false;
} else if (relPos < 0) {
noNegative = false;
} else if (relPos === 0) {
noZero = false;
}
}, this);
if ( (noNegative || noPositive) && noZero) {
return false;
}
return !((x1 > this.right && x2 > this.right) ||
(x1 < this.left && x2 < this.left) ||
(y1 < this.top && y2 < this.top) ||
(y1 > this.bottom && y2 > this.bottom)
);
};
/**
* @returns {String} Like "[x, y][w, h]"
*/
Rect.prototype.toString = function() {
return ["[", this.left, ",", this.top, "]"," [",this.width, ",", this.height, "]"].join("");
};
/**
* @returns {gamejs.Rect} A new copy of this rect
*/
Rect.prototype.clone = function() {
return new Rect(this);
};
/**
* A Surface represents a bitmap image with a fixed width and height. The
* most important feature of a Surface is that they can be `blitted`
* onto each other.
*
* @example
* new gamejs.Surface([width, height]);
* new gamejs.Surface(width, height);
* new gamejs.Surface(rect);
* @constructor
*
* @param {Array} dimensions Array holding width and height
*/
var Surface = exports.Surface = function() {
var args = normalizeRectArguments.apply(this, arguments);
var width = args.left;
var height = args.top;
// unless argument is rect:
if (arguments.length == 1 && arguments[0] instanceof Rect) {
width = args.width;
height = args.height;
}
// only for rotatation & scale
/** @ignore */
this._matrix = matrix.identity();
/** @ignore */
this._canvas = document.createElement("canvas");
this._canvas.width = width;
this._canvas.height = height;
/** @ignore */
this._blitAlpha = 1.0;
/** @ignore */
this._context = this._canvas.getContext('2d')
this._smooth();
return this;
};
/** @ignore */
Surface.prototype._noSmooth = function() {
// disable image scaling
// see https://developer.mozilla.org/en/Canvas_tutorial/Using_images#Controlling_image_scaling_behavior
// and https://github.com/jbuck/processing-js/commit/65de16a8340c694cee471a2db7634733370b941c
this.context.mozImageSmoothingEnabled = false;
this.canvas.style.setProperty("image-rendering", "optimizeSpeed", "important");
this.canvas.style.setProperty("image-rendering", "-moz-crisp-edges", "important");
this.canvas.style.setProperty("image-rendering", "-webkit-optimize-contrast", "important");
this.canvas.style.setProperty("image-rendering", "optimize-contrast", "important");
this.canvas.style.setProperty("-ms-interpolation-mode", "nearest-neighbor", "important");
return;
};
Surface.prototype._smooth = function() {
this.canvas.style.setProperty("image-rendering", "optimizeQuality", "important");
this.canvas.style.setProperty("-ms-interpolation-mode", "bicubic", "important");
this.context.mozImageSmoothingEnabled = true;
};
/**
* Blits another Surface on this Surface. The destination where to blit to
* can be given (or it defaults to the top left corner) as well as the
* Area from the Surface which should be blitted (e.g., for cutting out parts of
* a Surface).
*
* @example
* // blit flower in top left corner of display
* displaySurface.blit(flowerSurface);
*
* // position flower at 10/10 of display
* displaySurface.blit(flowerSurface, [10, 10])
*
* // ... `dest` can also be a rect whose topleft position is taken:
* displaySurface.blit(flowerSurface, new gamejs.Rect([10, 10]);
*
* // only blit half of the flower onto the display
* var flowerRect = flowerSurface.rect;
* flowerRect = new gamejs.Rect([0,0], [flowerRect.width/2, flowerRect.height/2])
* displaySurface.blit(flowerSurface, [0,0], flowerRect);
*
* @param {gamejs.Surface} src The Surface which will be blitted onto this one
* @param {gamejs.Rect|Array} dst the Destination x, y position in this Surface.
* If a Rect is given, it's top and left values are taken. If this argument
* is not supplied the blit happens at [0,0].
* @param {gamesjs.Rect|Array} area the Area from the passed Surface which
* should be blitted onto this Surface.
* @param {Number} [special_flags] FIXME add special flags for composite operations
* @returns {gamejs.Rect} Rect actually repainted
*/
Surface.prototype.blit = function(src, dest, area, special_flags) {
var rDest, rArea;
if (dest instanceof Rect) {
rDest = dest.clone();
var srcSize = src.getSize();
if (!rDest.width) {
rDest.width = srcSize[0];
}
if (!rDest.height) {
rDest.height = srcSize[1];
}
} else if (dest && dest instanceof Array && dest.length == 2) {
rDest = new Rect(dest, src.getSize());
} else {
rDest = new Rect([0,0], src.getSize());
}
// area within src to be drawn
if (area instanceof Rect) {
rArea = area;
} else if (area && area instanceof Array && area.length == 2) {
var size = src.getSize();
rArea = new Rect(area, [size[0] - area[0], size[1] - area[1]]);
} else {
rArea = new Rect([0,0], src.getSize());
}
if (isNaN(rDest.left) || isNaN(rDest.top) || isNaN(rDest.width) || isNaN(rDest.height)) {
throw new Error('[blit] bad parameters, destination is ' + rDest);
}
this.context.save();
// first translate, then rotate
var m = matrix.translate(matrix.identity(), rDest.left, rDest.top);
m = matrix.multiply(m, src._matrix);
this.context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
var srcRect = src.getRect();
// drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
this.context.globalAlpha = src._blitAlpha;
this.context.drawImage(src.canvas, rArea.left, rArea.top, rArea.width, rArea.height, 0, 0, rDest.width, rDest.height);
this.context.restore();
return;
};
/**
* @returns {Number[]} the width and height of the Surface
*/
Surface.prototype.getSize = function() {
return [this.canvas.width, this.canvas.height];
};
/**
* Obsolte, only here for compatibility.
* @deprecated
* @ignore
* @returns {gamejs.Rect} a Rect of the size of this Surface
*/
Surface.prototype.getRect = function() {
return new Rect([0,0], this.getSize());
};
/**
* Fills the whole Surface with a color. Usefull for erasing a Surface.
* @param {String} CSS color string, e.g. '#0d120a' or '#0f0' or 'rgba(255, 0, 0, 0.5)'
*/
Surface.prototype.fill = function(color) {
this.context.save();
this.context.fillStyle = color || "#000000";
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.restore();
return;
};
/**
* Clear the surface.
*/
Surface.prototype.clear = function() {
var size = this.getSize();
this.context.clearRect(0, 0, size[0], size[1]);
return;
};
objects.accessors(Surface.prototype, {
/**
* @type gamejs.Rect
*/
'rect': {
get: function() {
return this.getRect();
}
},
/**
* @ignore
*/
'context': {
get: function() {
return this._context;
}
},
'canvas': {
get: function() {
return this._canvas;
}
}
});
/**
* @returns {gamejs.Surface} a clone of this surface
*/
Surface.prototype.clone = function() {
var newSurface = new Surface(this.getRect());
newSurface.blit(this);
return newSurface;
};
/**
* @returns {Number} current alpha value
*/
Surface.prototype.getAlpha = function() {
return (1 - this._blitAlpha);
};
/**
* Set the alpha value for the whole Surface. When blitting the Surface on
* a destination, the pixels will be drawn slightly transparent.
* @param {Number} alpha value in range 0.0 - 1.0
* @returns {Number} current alpha value
*/
Surface.prototype.setAlpha = function(alpha) {
if (isNaN(alpha) || alpha < 0 || alpha > 1) {
return;
}
this._blitAlpha = (1 - alpha);
return (1 - this._blitAlpha);
};
/**
* The data must be represented in left-to-right order, row by row top to bottom,
* starting with the top left, with each pixel's red, green, blue, and alpha components
* being given in that order for each pixel.
* @see http://dev.w3.org/html5/2dcontext/#canvaspixelarray
* @returns {ImageData} an object holding the pixel image data {data, width, height}
*/
Surface.prototype.getImageData = function() {
var size = this.getSize();
return this.context.getImageData(0, 0, size[0], size[1]);
};
/**
* @ignore
*/
exports.display = require('./gamejs/display');
/**
* @ignore
*/
exports.draw = require('./gamejs/draw');
/**
* @ignore
*/
exports.event = require('./gamejs/event');
/**
* @ignore
*/
exports.font = require('./gamejs/font');
/**
* @ignore
*/
exports.http = require('./gamejs/http');
/**
* @ignore
*/
exports.image = require('./gamejs/image');
/**
* @ignore
*/
exports.mask = require('./gamejs/mask');
/**
* @ignore
*/
exports.mixer = require('./gamejs/mixer');
/**
* @ignore
*/
exports.sprite = require('./gamejs/sprite');
/**
* @ignore
*/
exports.surfacearray = require('./gamejs/surfacearray');
/**
* @ignore
*/
exports.time = require('./gamejs/time');
/**
* @ignore
*/
exports.transform = require('./gamejs/transform');
/**
* @ignore
*/
exports.utils = {
arrays: require('./gamejs/utils/arrays'),
objects: require('./gamejs/utils/objects'),
matrix: require('./gamejs/utils/matrix'),
vectors: require('./gamejs/utils/vectors'),
math: require('./gamejs/utils/math')
};
/**
* @ignore
*/
exports.pathfinding = {
astar: require('./gamejs/pathfinding/astar')
};
// preloading stuff
var gamejs = exports;
var RESOURCES = {};
/**
* ReadyFn is called once all modules and assets are loaded.
* @param {Function} readyFn the function to be called once gamejs finished loading
* @name ready
*/
exports.ready = function(readyFn) {
var getMixerProgress = null;
var getImageProgress = null;
// init time instantly - we need it for preloaders
gamejs.time.init();
// 2.
function _ready() {
if (!document.body) {
return window.setTimeout(_ready, 50);
}
getImageProgress = gamejs.image.preload(RESOURCES);
try {
getMixerProgress = gamejs.mixer.preload(RESOURCES);
} catch (e) {
gamejs.debug('Error loading audio files ', e);
}
window.setTimeout(_readyResources, 50);
}
// 3.
function _readyResources() {
if (getImageProgress() < 1 || getMixerProgress() < 1) {
return window.setTimeout(_readyResources, 100);
}
gamejs.display.init();
gamejs.image.init();
gamejs.mixer.init();
gamejs.event.init();
readyFn();
}
// 1.
window.setTimeout(_ready, 13);
function getLoadProgress() {
if (getImageProgress) {
return (0.5 * getImageProgress()) + (0.5 * getMixerProgress());
}
return 0.1;
}
return getLoadProgress;
};
function resourceBaseHref() {
return (window.$g && window.$g.resourceBaseHref) || '.';
}
/**
* Preload resources.
* @param {Array} resources list of resources paths
* @name preload
*/
var preload = exports.preload = function(resources) {
var basehref = resourceBaseHref();
if(basehref.slice(-1) == '/') {
basehref = basehref.slice(0, basehref.length-1);
}
// attach appBaseUrl to resources
resources.forEach(function(res) {
// normalize slashses
RESOURCES[res] = resourceBaseHref() + ('/' + res).replace(/\/+/g, '/');
}, this);
return;
};