· 6 years ago · Jan 12, 2020, 03:26 PM
1//=============================================================================
2// rpg_core.js v1.6.2
3//=============================================================================
4
5//-----------------------------------------------------------------------------
6/**
7 * This is not a class, but contains some methods that will be added to the
8 * standard Javascript objects.
9 *
10 * @class JsExtensions
11 */
12function JsExtensions() {
13 throw new Error('This is not a class');
14}
15
16/**
17 * Returns a number whose value is limited to the given range.
18 *
19 * @method Number.prototype.clamp
20 * @param {Number} min The lower boundary
21 * @param {Number} max The upper boundary
22 * @return {Number} A number in the range (min, max)
23 */
24Number.prototype.clamp = function(min, max) {
25 return Math.min(Math.max(this, min), max);
26};
27
28/**
29 * Returns a modulo value which is always positive.
30 *
31 * @method Number.prototype.mod
32 * @param {Number} n The divisor
33 * @return {Number} A modulo value
34 */
35Number.prototype.mod = function(n) {
36 return ((this % n) + n) % n;
37};
38
39/**
40 * Replaces %1, %2 and so on in the string to the arguments.
41 *
42 * @method String.prototype.format
43 * @param {Any} ...args The objects to format
44 * @return {String} A formatted string
45 */
46String.prototype.format = function() {
47 var args = arguments;
48 return this.replace(/%([0-9]+)/g, function(s, n) {
49 return args[Number(n) - 1];
50 });
51};
52
53/**
54 * Makes a number string with leading zeros.
55 *
56 * @method String.prototype.padZero
57 * @param {Number} length The length of the output string
58 * @return {String} A string with leading zeros
59 */
60String.prototype.padZero = function(length){
61 var s = this;
62 while (s.length < length) {
63 s = '0' + s;
64 }
65 return s;
66};
67
68/**
69 * Makes a number string with leading zeros.
70 *
71 * @method Number.prototype.padZero
72 * @param {Number} length The length of the output string
73 * @return {String} A string with leading zeros
74 */
75Number.prototype.padZero = function(length){
76 return String(this).padZero(length);
77};
78
79Object.defineProperties(Array.prototype, {
80 /**
81 * Checks whether the two arrays are same.
82 *
83 * @method Array.prototype.equals
84 * @param {Array} array The array to compare to
85 * @return {Boolean} True if the two arrays are same
86 */
87 equals: {
88 enumerable: false,
89 value: function(array) {
90 if (!array || this.length !== array.length) {
91 return false;
92 }
93 for (var i = 0; i < this.length; i++) {
94 if (this[i] instanceof Array && array[i] instanceof Array) {
95 if (!this[i].equals(array[i])) {
96 return false;
97 }
98 } else if (this[i] !== array[i]) {
99 return false;
100 }
101 }
102 return true;
103 }
104 },
105 /**
106 * Makes a shallow copy of the array.
107 *
108 * @method Array.prototype.clone
109 * @return {Array} A shallow copy of the array
110 */
111 clone: {
112 enumerable: false,
113 value: function() {
114 return this.slice(0);
115 }
116 },
117 /**
118 * Checks whether the array contains a given element.
119 *
120 * @method Array.prototype.contains
121 * @param {Any} element The element to search for
122 * @return {Boolean} True if the array contains a given element
123 */
124 contains : {
125 enumerable: false,
126 value: function(element) {
127 return this.indexOf(element) >= 0;
128 }
129 }
130});
131
132/**
133 * Checks whether the string contains a given string.
134 *
135 * @method String.prototype.contains
136 * @param {String} string The string to search for
137 * @return {Boolean} True if the string contains a given string
138 */
139String.prototype.contains = function(string) {
140 return this.indexOf(string) >= 0;
141};
142
143/**
144 * Generates a random integer in the range (0, max-1).
145 *
146 * @static
147 * @method Math.randomInt
148 * @param {Number} max The upper boundary (excluded)
149 * @return {Number} A random integer
150 */
151Math.randomInt = function(max) {
152 return Math.floor(max * Math.random());
153};
154
155//-----------------------------------------------------------------------------
156/**
157 * The static class that defines utility methods.
158 *
159 * @class Utils
160 */
161function Utils() {
162 throw new Error('This is a static class');
163}
164
165/**
166 * The name of the RPG Maker. 'MV' in the current version.
167 *
168 * @static
169 * @property RPGMAKER_NAME
170 * @type String
171 * @final
172 */
173Utils.RPGMAKER_NAME = 'MV';
174
175/**
176 * The version of the RPG Maker.
177 *
178 * @static
179 * @property RPGMAKER_VERSION
180 * @type String
181 * @final
182 */
183Utils.RPGMAKER_VERSION = "1.6.1";
184
185/**
186 * Checks whether the option is in the query string.
187 *
188 * @static
189 * @method isOptionValid
190 * @param {String} name The option name
191 * @return {Boolean} True if the option is in the query string
192 */
193Utils.isOptionValid = function(name) {
194 if (location.search.slice(1).split('&').contains(name)) {return 1;};
195 if (typeof nw !== "undefined" && nw.App.argv.length > 0 && nw.App.argv[0].split('&').contains(name)) {return 1;};
196 return 0;
197};
198
199/**
200 * Checks whether the platform is NW.js.
201 *
202 * @static
203 * @method isNwjs
204 * @return {Boolean} True if the platform is NW.js
205 */
206Utils.isNwjs = function() {
207 return typeof require === 'function' && typeof process === 'object';
208};
209
210/**
211 * Checks whether the platform is a mobile device.
212 *
213 * @static
214 * @method isMobileDevice
215 * @return {Boolean} True if the platform is a mobile device
216 */
217Utils.isMobileDevice = function() {
218 var r = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
219 return !!navigator.userAgent.match(r);
220};
221
222/**
223 * Checks whether the browser is Mobile Safari.
224 *
225 * @static
226 * @method isMobileSafari
227 * @return {Boolean} True if the browser is Mobile Safari
228 */
229Utils.isMobileSafari = function() {
230 var agent = navigator.userAgent;
231 return !!(agent.match(/iPhone|iPad|iPod/) && agent.match(/AppleWebKit/) &&
232 !agent.match('CriOS'));
233};
234
235/**
236 * Checks whether the browser is Android Chrome.
237 *
238 * @static
239 * @method isAndroidChrome
240 * @return {Boolean} True if the browser is Android Chrome
241 */
242Utils.isAndroidChrome = function() {
243 var agent = navigator.userAgent;
244 return !!(agent.match(/Android/) && agent.match(/Chrome/));
245};
246
247/**
248 * Checks whether the browser can read files in the game folder.
249 *
250 * @static
251 * @method canReadGameFiles
252 * @return {Boolean} True if the browser can read files in the game folder
253 */
254Utils.canReadGameFiles = function() {
255 var scripts = document.getElementsByTagName('script');
256 var lastScript = scripts[scripts.length - 1];
257 var xhr = new XMLHttpRequest();
258 try {
259 xhr.open('GET', lastScript.src);
260 xhr.overrideMimeType('text/javascript');
261 xhr.send();
262 return true;
263 } catch (e) {
264 return false;
265 }
266};
267
268/**
269 * Makes a CSS color string from RGB values.
270 *
271 * @static
272 * @method rgbToCssColor
273 * @param {Number} r The red value in the range (0, 255)
274 * @param {Number} g The green value in the range (0, 255)
275 * @param {Number} b The blue value in the range (0, 255)
276 * @return {String} CSS color string
277 */
278Utils.rgbToCssColor = function(r, g, b) {
279 r = Math.round(r);
280 g = Math.round(g);
281 b = Math.round(b);
282 return 'rgb(' + r + ',' + g + ',' + b + ')';
283};
284
285Utils._id = 1;
286Utils.generateRuntimeId = function(){
287 return Utils._id++;
288};
289
290Utils._supportPassiveEvent = null;
291/**
292 * Test this browser support passive event feature
293 *
294 * @static
295 * @method isSupportPassiveEvent
296 * @return {Boolean} this browser support passive event or not
297 */
298Utils.isSupportPassiveEvent = function() {
299 if (typeof Utils._supportPassiveEvent === "boolean") {
300 return Utils._supportPassiveEvent;
301 }
302 // test support passive event
303 // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
304 var passive = false;
305 var options = Object.defineProperty({}, "passive", {
306 get: function() { passive = true; }
307 });
308 window.addEventListener("test", null, options);
309 Utils._supportPassiveEvent = passive;
310 return passive;
311}
312
313//-----------------------------------------------------------------------------
314/**
315 * The resource class. Allows to be collected as a garbage if not use for some time or ticks
316 *
317 * @class CacheEntry
318 * @constructor
319 * @param {ResourceManager} resource manager
320 * @param {string} key, url of the resource
321 * @param {string} item - Bitmap, HTML5Audio, WebAudio - whatever you want to store in the cache
322 */
323function CacheEntry(cache, key, item) {
324 this.cache = cache;
325 this.key = key;
326 this.item = item;
327 this.cached = false;
328 this.touchTicks = 0;
329 this.touchSeconds = 0;
330 this.ttlTicks = 0;
331 this.ttlSeconds = 0;
332 this.freedByTTL = false;
333}
334
335/**
336 * frees the resource
337 */
338CacheEntry.prototype.free = function (byTTL) {
339 this.freedByTTL = byTTL || false;
340 if (this.cached) {
341 this.cached = false;
342 delete this.cache._inner[this.key];
343 }
344};
345
346/**
347 * Allocates the resource
348 * @returns {CacheEntry}
349 */
350CacheEntry.prototype.allocate = function () {
351 if (!this.cached) {
352 this.cache._inner[this.key] = this;
353 this.cached = true;
354 }
355 this.touch();
356 return this;
357};
358
359/**
360 * Sets the time to live
361 * @param {number} ticks TTL in ticks, 0 if not set
362 * @param {number} time TTL in seconds, 0 if not set
363 * @returns {CacheEntry}
364 */
365CacheEntry.prototype.setTimeToLive = function (ticks, seconds) {
366 this.ttlTicks = ticks || 0;
367 this.ttlSeconds = seconds || 0;
368 return this;
369};
370
371CacheEntry.prototype.isStillAlive = function () {
372 var cache = this.cache;
373 return ((this.ttlTicks == 0) || (this.touchTicks + this.ttlTicks < cache.updateTicks )) &&
374 ((this.ttlSeconds == 0) || (this.touchSeconds + this.ttlSeconds < cache.updateSeconds ));
375};
376
377/**
378 * makes sure that resource wont freed by Time To Live
379 * if resource was already freed by TTL, put it in cache again
380 */
381CacheEntry.prototype.touch = function () {
382 var cache = this.cache;
383 if (this.cached) {
384 this.touchTicks = cache.updateTicks;
385 this.touchSeconds = cache.updateSeconds;
386 } else if (this.freedByTTL) {
387 this.freedByTTL = false;
388 if (!cache._inner[this.key]) {
389 cache._inner[this.key] = this;
390 }
391 }
392};
393
394/**
395 * Cache for images, audio, or any other kind of resource
396 * @param manager
397 * @constructor
398 */
399function CacheMap(manager) {
400 this.manager = manager;
401 this._inner = {};
402 this._lastRemovedEntries = {};
403 this.updateTicks = 0;
404 this.lastCheckTTL = 0;
405 this.delayCheckTTL = 100.0;
406 this.updateSeconds = Date.now();
407}
408
409/**
410 * checks ttl of all elements and removes dead ones
411 */
412CacheMap.prototype.checkTTL = function () {
413 var cache = this._inner;
414 var temp = this._lastRemovedEntries;
415 if (!temp) {
416 temp = [];
417 this._lastRemovedEntries = temp;
418 }
419 for (var key in cache) {
420 var entry = cache[key];
421 if (!entry.isStillAlive()) {
422 temp.push(entry);
423 }
424 }
425 for (var i = 0; i < temp.length; i++) {
426 temp[i].free(true);
427 }
428 temp.length = 0;
429};
430
431/**
432 * cache item
433 * @param key url of cache element
434 * @returns {*|null}
435 */
436CacheMap.prototype.getItem = function (key) {
437 var entry = this._inner[key];
438 if (entry) {
439 return entry.item;
440 }
441 return null;
442};
443
444CacheMap.prototype.clear = function () {
445 var keys = Object.keys(this._inner);
446 for (var i = 0; i < keys.length; i++) {
447 this._inner[keys[i]].free();
448 }
449};
450
451CacheMap.prototype.setItem = function (key, item) {
452 return new CacheEntry(this, key, item).allocate();
453};
454
455CacheMap.prototype.update = function(ticks, delta) {
456 this.updateTicks += ticks;
457 this.updateSeconds += delta;
458 if (this.updateSeconds >= this.delayCheckTTL + this.lastCheckTTL) {
459 this.lastCheckTTL = this.updateSeconds;
460 this.checkTTL();
461 }
462};
463
464function ImageCache(){
465 this.initialize.apply(this, arguments);
466}
467
468ImageCache.limit = 10 * 1000 * 1000;
469
470ImageCache.prototype.initialize = function(){
471 this._items = {};
472};
473
474ImageCache.prototype.add = function(key, value){
475 this._items[key] = {
476 bitmap: value,
477 touch: Date.now(),
478 key: key
479 };
480
481 this._truncateCache();
482};
483
484ImageCache.prototype.get = function(key){
485 if(this._items[key]){
486 var item = this._items[key];
487 item.touch = Date.now();
488 return item.bitmap;
489 }
490
491 return null;
492};
493
494ImageCache.prototype.reserve = function(key, value, reservationId){
495 if(!this._items[key]){
496 this._items[key] = {
497 bitmap: value,
498 touch: Date.now(),
499 key: key
500 };
501 }
502
503 this._items[key].reservationId = reservationId;
504};
505
506ImageCache.prototype.releaseReservation = function(reservationId){
507 var items = this._items;
508
509 Object.keys(items)
510 .map(function(key){return items[key];})
511 .forEach(function(item){
512 if(item.reservationId === reservationId){
513 delete item.reservationId;
514 }
515 });
516};
517
518ImageCache.prototype._truncateCache = function(){
519 var items = this._items;
520 var sizeLeft = ImageCache.limit;
521
522 Object.keys(items).map(function(key){
523 return items[key];
524 }).sort(function(a, b){
525 return b.touch - a.touch;
526 }).forEach(function(item){
527 if(sizeLeft > 0 || this._mustBeHeld(item)){
528 var bitmap = item.bitmap;
529 sizeLeft -= bitmap.width * bitmap.height;
530 }else{
531 delete items[item.key];
532 }
533 }.bind(this));
534};
535
536ImageCache.prototype._mustBeHeld = function(item){
537 // request only is weak so It's purgeable
538 if(item.bitmap.isRequestOnly()) return false;
539 // reserved item must be held
540 if(item.reservationId) return true;
541 // not ready bitmap must be held (because of checking isReady())
542 if(!item.bitmap.isReady()) return true;
543 // then the item may purgeable
544 return false;
545};
546
547ImageCache.prototype.isReady = function(){
548 var items = this._items;
549 return !Object.keys(items).some(function(key){
550 return !items[key].bitmap.isRequestOnly() && !items[key].bitmap.isReady();
551 });
552};
553
554ImageCache.prototype.getErrorBitmap = function(){
555 var items = this._items;
556 var bitmap = null;
557 if(Object.keys(items).some(function(key){
558 if(items[key].bitmap.isError()){
559 bitmap = items[key].bitmap;
560 return true;
561 }
562 return false;
563 })) {
564 return bitmap;
565 }
566
567 return null;
568};
569function RequestQueue(){
570 this.initialize.apply(this, arguments);
571}
572
573RequestQueue.prototype.initialize = function(){
574 this._queue = [];
575};
576
577RequestQueue.prototype.enqueue = function(key, value){
578 this._queue.push({
579 key: key,
580 value: value,
581 });
582};
583
584RequestQueue.prototype.update = function(){
585 if(this._queue.length === 0) return;
586
587 var top = this._queue[0];
588 if(top.value.isRequestReady()){
589 this._queue.shift();
590 if(this._queue.length !== 0){
591 this._queue[0].value.startRequest();
592 }
593 }else{
594 top.value.startRequest();
595 }
596};
597
598RequestQueue.prototype.raisePriority = function(key){
599 for(var n = 0; n < this._queue.length; n++){
600 var item = this._queue[n];
601 if(item.key === key){
602 this._queue.splice(n, 1);
603 this._queue.unshift(item);
604 break;
605 }
606 }
607};
608
609RequestQueue.prototype.clear = function(){
610 this._queue.splice(0);
611};
612//-----------------------------------------------------------------------------
613/**
614 * The point class.
615 *
616 * @class Point
617 * @constructor
618 * @param {Number} x The x coordinate
619 * @param {Number} y The y coordinate
620 */
621function Point() {
622 this.initialize.apply(this, arguments);
623}
624
625Point.prototype = Object.create(PIXI.Point.prototype);
626Point.prototype.constructor = Point;
627
628Point.prototype.initialize = function(x, y) {
629 PIXI.Point.call(this, x, y);
630};
631
632/**
633 * The x coordinate.
634 *
635 * @property x
636 * @type Number
637 */
638
639/**
640 * The y coordinate.
641 *
642 * @property y
643 * @type Number
644 */
645
646//-----------------------------------------------------------------------------
647/**
648 * The rectangle class.
649 *
650 * @class Rectangle
651 * @constructor
652 * @param {Number} x The x coordinate for the upper-left corner
653 * @param {Number} y The y coordinate for the upper-left corner
654 * @param {Number} width The width of the rectangle
655 * @param {Number} height The height of the rectangle
656 */
657function Rectangle() {
658 this.initialize.apply(this, arguments);
659}
660
661Rectangle.prototype = Object.create(PIXI.Rectangle.prototype);
662Rectangle.prototype.constructor = Rectangle;
663
664Rectangle.prototype.initialize = function(x, y, width, height) {
665 PIXI.Rectangle.call(this, x, y, width, height);
666};
667
668/**
669 * @static
670 * @property emptyRectangle
671 * @type Rectangle
672 * @private
673 */
674Rectangle.emptyRectangle = new Rectangle(0, 0, 0, 0);
675
676/**
677 * The x coordinate for the upper-left corner.
678 *
679 * @property x
680 * @type Number
681 */
682
683/**
684 * The y coordinate for the upper-left corner.
685 *
686 * @property y
687 * @type Number
688 */
689
690/**
691 * The width of the rectangle.
692 *
693 * @property width
694 * @type Number
695 */
696
697/**
698 * The height of the rectangle.
699 *
700 * @property height
701 * @type Number
702 */
703
704//-----------------------------------------------------------------------------
705/**
706 * The basic object that represents an image.
707 *
708 * @class Bitmap
709 * @constructor
710 * @param {Number} width The width of the bitmap
711 * @param {Number} height The height of the bitmap
712 */
713function Bitmap() {
714 this.initialize.apply(this, arguments);
715}
716
717//for iOS. img consumes memory. so reuse it.
718Bitmap._reuseImages = [];
719
720
721/**
722 * Bitmap states(Bitmap._loadingState):
723 *
724 * none:
725 * Empty Bitmap
726 *
727 * pending:
728 * Url requested, but pending to load until startRequest called
729 *
730 * purged:
731 * Url request completed and purged.
732 *
733 * requesting:
734 * Requesting supplied URI now.
735 *
736 * requestCompleted:
737 * Request completed
738 *
739 * decrypting:
740 * requesting encrypted data from supplied URI or decrypting it.
741 *
742 * decryptCompleted:
743 * Decrypt completed
744 *
745 * loaded:
746 * loaded. isReady() === true, so It's usable.
747 *
748 * error:
749 * error occurred
750 *
751 */
752
753
754Bitmap.prototype._createCanvas = function(width, height){
755 this.__canvas = this.__canvas || document.createElement('canvas');
756 this.__context = this.__canvas.getContext('2d');
757
758 this.__canvas.width = Math.max(width || 0, 1);
759 this.__canvas.height = Math.max(height || 0, 1);
760
761 if(this._image){
762 var w = Math.max(this._image.width || 0, 1);
763 var h = Math.max(this._image.height || 0, 1);
764 this.__canvas.width = w;
765 this.__canvas.height = h;
766 this._createBaseTexture(this._canvas);
767
768 this.__context.drawImage(this._image, 0, 0);
769 }
770
771 this._setDirty();
772};
773
774Bitmap.prototype._createBaseTexture = function(source){
775 this.__baseTexture = new PIXI.BaseTexture(source);
776 this.__baseTexture.mipmap = false;
777 this.__baseTexture.width = source.width;
778 this.__baseTexture.height = source.height;
779
780 if (this._smooth) {
781 this._baseTexture.scaleMode = PIXI.SCALE_MODES.LINEAR;
782 } else {
783 this._baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST;
784 }
785};
786
787Bitmap.prototype._clearImgInstance = function(){
788 this._image.src = "";
789 this._image.onload = null;
790 this._image.onerror = null;
791 this._errorListener = null;
792 this._loadListener = null;
793
794 Bitmap._reuseImages.push(this._image);
795 this._image = null;
796};
797
798//
799//We don't want to waste memory, so creating canvas is deferred.
800//
801Object.defineProperties(Bitmap.prototype, {
802 _canvas: {
803 get: function(){
804 if(!this.__canvas)this._createCanvas();
805 return this.__canvas;
806 }
807 },
808 _context: {
809 get: function(){
810 if(!this.__context)this._createCanvas();
811 return this.__context;
812 }
813 },
814
815 _baseTexture: {
816 get: function(){
817 if(!this.__baseTexture) this._createBaseTexture(this._image || this.__canvas);
818 return this.__baseTexture;
819 }
820 }
821});
822
823Bitmap.prototype._renewCanvas = function(){
824 var newImage = this._image;
825 if(newImage && this.__canvas && (this.__canvas.width < newImage.width || this.__canvas.height < newImage.height)){
826 this._createCanvas();
827 }
828};
829
830Bitmap.prototype.initialize = function(width, height) {
831 if(!this._defer){
832 this._createCanvas(width, height);
833 }
834
835 this._image = null;
836 this._url = '';
837 this._paintOpacity = 255;
838 this._smooth = false;
839 this._loadListeners = [];
840 this._loadingState = 'none';
841 this._decodeAfterRequest = false;
842
843 /**
844 * Cache entry, for images. In all cases _url is the same as cacheEntry.key
845 * @type CacheEntry
846 */
847 this.cacheEntry = null;
848
849 /**
850 * The face name of the font.
851 *
852 * @property fontFace
853 * @type String
854 */
855 this.fontFace = 'GameFont';
856
857 /**
858 * The size of the font in pixels.
859 *
860 * @property fontSize
861 * @type Number
862 */
863 this.fontSize = 28;
864
865 /**
866 * Whether the font is italic.
867 *
868 * @property fontItalic
869 * @type Boolean
870 */
871 this.fontItalic = false;
872
873 /**
874 * The color of the text in CSS format.
875 *
876 * @property textColor
877 * @type String
878 */
879 this.textColor = '#ffffff';
880
881 /**
882 * The color of the outline of the text in CSS format.
883 *
884 * @property outlineColor
885 * @type String
886 */
887 this.outlineColor = 'rgba(0, 0, 0, 0.5)';
888
889 /**
890 * The width of the outline of the text.
891 *
892 * @property outlineWidth
893 * @type Number
894 */
895 this.outlineWidth = 4;
896};
897
898/**
899 * Loads a image file and returns a new bitmap object.
900 *
901 * @static
902 * @method load
903 * @param {String} url The image url of the texture
904 * @return Bitmap
905 */
906Bitmap.load = function(url) {
907 var bitmap = Object.create(Bitmap.prototype);
908 bitmap._defer = true;
909 bitmap.initialize();
910
911 bitmap._decodeAfterRequest = true;
912 bitmap._requestImage(url);
913
914 return bitmap;
915};
916
917/**
918 * Takes a snapshot of the game screen and returns a new bitmap object.
919 *
920 * @static
921 * @method snap
922 * @param {Stage} stage The stage object
923 * @return Bitmap
924 */
925Bitmap.snap = function(stage) {
926 var width = Graphics.width;
927 var height = Graphics.height;
928 var bitmap = new Bitmap(width, height);
929 var context = bitmap._context;
930 var renderTexture = PIXI.RenderTexture.create(width, height);
931 if (stage) {
932 Graphics._renderer.render(stage, renderTexture);
933 stage.worldTransform.identity();
934 var canvas = null;
935 if (Graphics.isWebGL()) {
936 canvas = Graphics._renderer.extract.canvas(renderTexture);
937 } else {
938 canvas = renderTexture.baseTexture._canvasRenderTarget.canvas;
939 }
940 context.drawImage(canvas, 0, 0);
941 } else {
942
943 }
944 renderTexture.destroy({ destroyBase: true });
945 bitmap._setDirty();
946 return bitmap;
947};
948
949/**
950 * Checks whether the bitmap is ready to render.
951 *
952 * @method isReady
953 * @return {Boolean} True if the bitmap is ready to render
954 */
955Bitmap.prototype.isReady = function() {
956 return this._loadingState === 'loaded' || this._loadingState === 'none';
957};
958
959/**
960 * Checks whether a loading error has occurred.
961 *
962 * @method isError
963 * @return {Boolean} True if a loading error has occurred
964 */
965Bitmap.prototype.isError = function() {
966 return this._loadingState === 'error';
967};
968
969/**
970 * touch the resource
971 * @method touch
972 */
973Bitmap.prototype.touch = function() {
974 if (this.cacheEntry) {
975 this.cacheEntry.touch();
976 }
977};
978
979/**
980 * [read-only] The url of the image file.
981 *
982 * @property url
983 * @type String
984 */
985Object.defineProperty(Bitmap.prototype, 'url', {
986 get: function() {
987 return this._url;
988 },
989 configurable: true
990});
991
992/**
993 * [read-only] The base texture that holds the image.
994 *
995 * @property baseTexture
996 * @type PIXI.BaseTexture
997 */
998Object.defineProperty(Bitmap.prototype, 'baseTexture', {
999 get: function() {
1000 return this._baseTexture;
1001 },
1002 configurable: true
1003});
1004
1005/**
1006 * [read-only] The bitmap canvas.
1007 *
1008 * @property canvas
1009 * @type HTMLCanvasElement
1010 */
1011Object.defineProperty(Bitmap.prototype, 'canvas', {
1012 get: function() {
1013 return this._canvas;
1014 },
1015 configurable: true
1016});
1017
1018/**
1019 * [read-only] The 2d context of the bitmap canvas.
1020 *
1021 * @property context
1022 * @type CanvasRenderingContext2D
1023 */
1024Object.defineProperty(Bitmap.prototype, 'context', {
1025 get: function() {
1026 return this._context;
1027 },
1028 configurable: true
1029});
1030
1031/**
1032 * [read-only] The width of the bitmap.
1033 *
1034 * @property width
1035 * @type Number
1036 */
1037Object.defineProperty(Bitmap.prototype, 'width', {
1038 get: function() {
1039 if(this.isReady()){
1040 return this._image? this._image.width: this._canvas.width;
1041 }
1042
1043 return 0;
1044 },
1045 configurable: true
1046});
1047
1048/**
1049 * [read-only] The height of the bitmap.
1050 *
1051 * @property height
1052 * @type Number
1053 */
1054Object.defineProperty(Bitmap.prototype, 'height', {
1055 get: function() {
1056 if(this.isReady()){
1057 return this._image? this._image.height: this._canvas.height;
1058 }
1059
1060 return 0;
1061 },
1062 configurable: true
1063});
1064
1065/**
1066 * [read-only] The rectangle of the bitmap.
1067 *
1068 * @property rect
1069 * @type Rectangle
1070 */
1071Object.defineProperty(Bitmap.prototype, 'rect', {
1072 get: function() {
1073 return new Rectangle(0, 0, this.width, this.height);
1074 },
1075 configurable: true
1076});
1077
1078/**
1079 * Whether the smooth scaling is applied.
1080 *
1081 * @property smooth
1082 * @type Boolean
1083 */
1084Object.defineProperty(Bitmap.prototype, 'smooth', {
1085 get: function() {
1086 return this._smooth;
1087 },
1088 set: function(value) {
1089 if (this._smooth !== value) {
1090 this._smooth = value;
1091 if(this.__baseTexture){
1092 if (this._smooth) {
1093 this._baseTexture.scaleMode = PIXI.SCALE_MODES.LINEAR;
1094 } else {
1095 this._baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST;
1096 }
1097 }
1098 }
1099 },
1100 configurable: true
1101});
1102
1103/**
1104 * The opacity of the drawing object in the range (0, 255).
1105 *
1106 * @property paintOpacity
1107 * @type Number
1108 */
1109Object.defineProperty(Bitmap.prototype, 'paintOpacity', {
1110 get: function() {
1111 return this._paintOpacity;
1112 },
1113 set: function(value) {
1114 if (this._paintOpacity !== value) {
1115 this._paintOpacity = value;
1116 this._context.globalAlpha = this._paintOpacity / 255;
1117 }
1118 },
1119 configurable: true
1120});
1121
1122/**
1123 * Resizes the bitmap.
1124 *
1125 * @method resize
1126 * @param {Number} width The new width of the bitmap
1127 * @param {Number} height The new height of the bitmap
1128 */
1129Bitmap.prototype.resize = function(width, height) {
1130 width = Math.max(width || 0, 1);
1131 height = Math.max(height || 0, 1);
1132 this._canvas.width = width;
1133 this._canvas.height = height;
1134 this._baseTexture.width = width;
1135 this._baseTexture.height = height;
1136};
1137
1138/**
1139 * Performs a block transfer.
1140 *
1141 * @method blt
1142 * @param {Bitmap} source The bitmap to draw
1143 * @param {Number} sx The x coordinate in the source
1144 * @param {Number} sy The y coordinate in the source
1145 * @param {Number} sw The width of the source image
1146 * @param {Number} sh The height of the source image
1147 * @param {Number} dx The x coordinate in the destination
1148 * @param {Number} dy The y coordinate in the destination
1149 * @param {Number} [dw=sw] The width to draw the image in the destination
1150 * @param {Number} [dh=sh] The height to draw the image in the destination
1151 */
1152Bitmap.prototype.blt = function(source, sx, sy, sw, sh, dx, dy, dw, dh) {
1153 dw = dw || sw;
1154 dh = dh || sh;
1155 if (sx >= 0 && sy >= 0 && sw > 0 && sh > 0 && dw > 0 && dh > 0 &&
1156 sx + sw <= source.width && sy + sh <= source.height) {
1157 this._context.globalCompositeOperation = 'source-over';
1158 this._context.drawImage(source._canvas, sx, sy, sw, sh, dx, dy, dw, dh);
1159 this._setDirty();
1160 }
1161};
1162
1163/**
1164 * Performs a block transfer, using assumption that original image was not modified (no hue)
1165 *
1166 * @method blt
1167 * @param {Bitmap} source The bitmap to draw
1168 * @param {Number} sx The x coordinate in the source
1169 * @param {Number} sy The y coordinate in the source
1170 * @param {Number} sw The width of the source image
1171 * @param {Number} sh The height of the source image
1172 * @param {Number} dx The x coordinate in the destination
1173 * @param {Number} dy The y coordinate in the destination
1174 * @param {Number} [dw=sw] The width to draw the image in the destination
1175 * @param {Number} [dh=sh] The height to draw the image in the destination
1176 */
1177Bitmap.prototype.bltImage = function(source, sx, sy, sw, sh, dx, dy, dw, dh) {
1178 dw = dw || sw;
1179 dh = dh || sh;
1180 if (sx >= 0 && sy >= 0 && sw > 0 && sh > 0 && dw > 0 && dh > 0 &&
1181 sx + sw <= source.width && sy + sh <= source.height) {
1182 this._context.globalCompositeOperation = 'source-over';
1183 this._context.drawImage(source._image, sx, sy, sw, sh, dx, dy, dw, dh);
1184 this._setDirty();
1185 }
1186};
1187
1188/**
1189 * Returns pixel color at the specified point.
1190 *
1191 * @method getPixel
1192 * @param {Number} x The x coordinate of the pixel in the bitmap
1193 * @param {Number} y The y coordinate of the pixel in the bitmap
1194 * @return {String} The pixel color (hex format)
1195 */
1196Bitmap.prototype.getPixel = function(x, y) {
1197 var data = this._context.getImageData(x, y, 1, 1).data;
1198 var result = '#';
1199 for (var i = 0; i < 3; i++) {
1200 result += data[i].toString(16).padZero(2);
1201 }
1202 return result;
1203};
1204
1205/**
1206 * Returns alpha pixel value at the specified point.
1207 *
1208 * @method getAlphaPixel
1209 * @param {Number} x The x coordinate of the pixel in the bitmap
1210 * @param {Number} y The y coordinate of the pixel in the bitmap
1211 * @return {String} The alpha value
1212 */
1213Bitmap.prototype.getAlphaPixel = function(x, y) {
1214 var data = this._context.getImageData(x, y, 1, 1).data;
1215 return data[3];
1216};
1217
1218/**
1219 * Clears the specified rectangle.
1220 *
1221 * @method clearRect
1222 * @param {Number} x The x coordinate for the upper-left corner
1223 * @param {Number} y The y coordinate for the upper-left corner
1224 * @param {Number} width The width of the rectangle to clear
1225 * @param {Number} height The height of the rectangle to clear
1226 */
1227Bitmap.prototype.clearRect = function(x, y, width, height) {
1228 this._context.clearRect(x, y, width, height);
1229 this._setDirty();
1230};
1231
1232/**
1233 * Clears the entire bitmap.
1234 *
1235 * @method clear
1236 */
1237Bitmap.prototype.clear = function() {
1238 this.clearRect(0, 0, this.width, this.height);
1239};
1240
1241/**
1242 * Fills the specified rectangle.
1243 *
1244 * @method fillRect
1245 * @param {Number} x The x coordinate for the upper-left corner
1246 * @param {Number} y The y coordinate for the upper-left corner
1247 * @param {Number} width The width of the rectangle to fill
1248 * @param {Number} height The height of the rectangle to fill
1249 * @param {String} color The color of the rectangle in CSS format
1250 */
1251Bitmap.prototype.fillRect = function(x, y, width, height, color) {
1252 var context = this._context;
1253 context.save();
1254 context.fillStyle = color;
1255 context.fillRect(x, y, width, height);
1256 context.restore();
1257 this._setDirty();
1258};
1259
1260/**
1261 * Fills the entire bitmap.
1262 *
1263 * @method fillAll
1264 * @param {String} color The color of the rectangle in CSS format
1265 */
1266Bitmap.prototype.fillAll = function(color) {
1267 this.fillRect(0, 0, this.width, this.height, color);
1268};
1269
1270/**
1271 * Draws the rectangle with a gradation.
1272 *
1273 * @method gradientFillRect
1274 * @param {Number} x The x coordinate for the upper-left corner
1275 * @param {Number} y The y coordinate for the upper-left corner
1276 * @param {Number} width The width of the rectangle to fill
1277 * @param {Number} height The height of the rectangle to fill
1278 * @param {String} color1 The gradient starting color
1279 * @param {String} color2 The gradient ending color
1280 * @param {Boolean} vertical Wether the gradient should be draw as vertical or not
1281 */
1282Bitmap.prototype.gradientFillRect = function(x, y, width, height, color1,
1283 color2, vertical) {
1284 var context = this._context;
1285 var grad;
1286 if (vertical) {
1287 grad = context.createLinearGradient(x, y, x, y + height);
1288 } else {
1289 grad = context.createLinearGradient(x, y, x + width, y);
1290 }
1291 grad.addColorStop(0, color1);
1292 grad.addColorStop(1, color2);
1293 context.save();
1294 context.fillStyle = grad;
1295 context.fillRect(x, y, width, height);
1296 context.restore();
1297 this._setDirty();
1298};
1299
1300/**
1301 * Draw a bitmap in the shape of a circle
1302 *
1303 * @method drawCircle
1304 * @param {Number} x The x coordinate based on the circle center
1305 * @param {Number} y The y coordinate based on the circle center
1306 * @param {Number} radius The radius of the circle
1307 * @param {String} color The color of the circle in CSS format
1308 */
1309Bitmap.prototype.drawCircle = function(x, y, radius, color) {
1310 var context = this._context;
1311 context.save();
1312 context.fillStyle = color;
1313 context.beginPath();
1314 context.arc(x, y, radius, 0, Math.PI * 2, false);
1315 context.fill();
1316 context.restore();
1317 this._setDirty();
1318};
1319
1320/**
1321 * Draws the outline text to the bitmap.
1322 *
1323 * @method drawText
1324 * @param {String} text The text that will be drawn
1325 * @param {Number} x The x coordinate for the left of the text
1326 * @param {Number} y The y coordinate for the top of the text
1327 * @param {Number} maxWidth The maximum allowed width of the text
1328 * @param {Number} lineHeight The height of the text line
1329 * @param {String} align The alignment of the text
1330 */
1331Bitmap.prototype.drawText = function(text, x, y, maxWidth, lineHeight, align) {
1332 // Note: Firefox has a bug with textBaseline: Bug 737852
1333 // So we use 'alphabetic' here.
1334 if (text !== undefined) {
1335 var tx = x;
1336 var ty = y + lineHeight - (lineHeight - this.fontSize * 0.7) / 2;
1337 var context = this._context;
1338 var alpha = context.globalAlpha;
1339 maxWidth = maxWidth || 0xffffffff;
1340 if (align === 'center') {
1341 tx += maxWidth / 2;
1342 }
1343 if (align === 'right') {
1344 tx += maxWidth;
1345 }
1346 context.save();
1347 context.font = this._makeFontNameText();
1348 context.textAlign = align;
1349 context.textBaseline = 'alphabetic';
1350 context.globalAlpha = 1;
1351 this._drawTextOutline(text, tx, ty, maxWidth);
1352 context.globalAlpha = alpha;
1353 this._drawTextBody(text, tx, ty, maxWidth);
1354 context.restore();
1355 this._setDirty();
1356 }
1357};
1358
1359/**
1360 * Returns the width of the specified text.
1361 *
1362 * @method measureTextWidth
1363 * @param {String} text The text to be measured
1364 * @return {Number} The width of the text in pixels
1365 */
1366Bitmap.prototype.measureTextWidth = function(text) {
1367 var context = this._context;
1368 context.save();
1369 context.font = this._makeFontNameText();
1370 var width = context.measureText(text).width;
1371 context.restore();
1372 return width;
1373};
1374
1375/**
1376 * Changes the color tone of the entire bitmap.
1377 *
1378 * @method adjustTone
1379 * @param {Number} r The red strength in the range (-255, 255)
1380 * @param {Number} g The green strength in the range (-255, 255)
1381 * @param {Number} b The blue strength in the range (-255, 255)
1382 */
1383Bitmap.prototype.adjustTone = function(r, g, b) {
1384 if ((r || g || b) && this.width > 0 && this.height > 0) {
1385 var context = this._context;
1386 var imageData = context.getImageData(0, 0, this.width, this.height);
1387 var pixels = imageData.data;
1388 for (var i = 0; i < pixels.length; i += 4) {
1389 pixels[i + 0] += r;
1390 pixels[i + 1] += g;
1391 pixels[i + 2] += b;
1392 }
1393 context.putImageData(imageData, 0, 0);
1394 this._setDirty();
1395 }
1396};
1397
1398/**
1399 * Rotates the hue of the entire bitmap.
1400 *
1401 * @method rotateHue
1402 * @param {Number} offset The hue offset in 360 degrees
1403 */
1404Bitmap.prototype.rotateHue = function(offset) {
1405 function rgbToHsl(r, g, b) {
1406 var cmin = Math.min(r, g, b);
1407 var cmax = Math.max(r, g, b);
1408 var h = 0;
1409 var s = 0;
1410 var l = (cmin + cmax) / 2;
1411 var delta = cmax - cmin;
1412
1413 if (delta > 0) {
1414 if (r === cmax) {
1415 h = 60 * (((g - b) / delta + 6) % 6);
1416 } else if (g === cmax) {
1417 h = 60 * ((b - r) / delta + 2);
1418 } else {
1419 h = 60 * ((r - g) / delta + 4);
1420 }
1421 s = delta / (255 - Math.abs(2 * l - 255));
1422 }
1423 return [h, s, l];
1424 }
1425
1426 function hslToRgb(h, s, l) {
1427 var c = (255 - Math.abs(2 * l - 255)) * s;
1428 var x = c * (1 - Math.abs((h / 60) % 2 - 1));
1429 var m = l - c / 2;
1430 var cm = c + m;
1431 var xm = x + m;
1432
1433 if (h < 60) {
1434 return [cm, xm, m];
1435 } else if (h < 120) {
1436 return [xm, cm, m];
1437 } else if (h < 180) {
1438 return [m, cm, xm];
1439 } else if (h < 240) {
1440 return [m, xm, cm];
1441 } else if (h < 300) {
1442 return [xm, m, cm];
1443 } else {
1444 return [cm, m, xm];
1445 }
1446 }
1447
1448 if (offset && this.width > 0 && this.height > 0) {
1449 offset = ((offset % 360) + 360) % 360;
1450 var context = this._context;
1451 var imageData = context.getImageData(0, 0, this.width, this.height);
1452 var pixels = imageData.data;
1453 for (var i = 0; i < pixels.length; i += 4) {
1454 var hsl = rgbToHsl(pixels[i + 0], pixels[i + 1], pixels[i + 2]);
1455 var h = (hsl[0] + offset) % 360;
1456 var s = hsl[1];
1457 var l = hsl[2];
1458 var rgb = hslToRgb(h, s, l);
1459 pixels[i + 0] = rgb[0];
1460 pixels[i + 1] = rgb[1];
1461 pixels[i + 2] = rgb[2];
1462 }
1463 context.putImageData(imageData, 0, 0);
1464 this._setDirty();
1465 }
1466};
1467
1468/**
1469 * Applies a blur effect to the bitmap.
1470 *
1471 * @method blur
1472 */
1473Bitmap.prototype.blur = function() {
1474 for (var i = 0; i < 2; i++) {
1475 var w = this.width;
1476 var h = this.height;
1477 var canvas = this._canvas;
1478 var context = this._context;
1479 var tempCanvas = document.createElement('canvas');
1480 var tempContext = tempCanvas.getContext('2d');
1481 tempCanvas.width = w + 2;
1482 tempCanvas.height = h + 2;
1483 tempContext.drawImage(canvas, 0, 0, w, h, 1, 1, w, h);
1484 tempContext.drawImage(canvas, 0, 0, w, 1, 1, 0, w, 1);
1485 tempContext.drawImage(canvas, 0, 0, 1, h, 0, 1, 1, h);
1486 tempContext.drawImage(canvas, 0, h - 1, w, 1, 1, h + 1, w, 1);
1487 tempContext.drawImage(canvas, w - 1, 0, 1, h, w + 1, 1, 1, h);
1488 context.save();
1489 context.fillStyle = 'black';
1490 context.fillRect(0, 0, w, h);
1491 context.globalCompositeOperation = 'lighter';
1492 context.globalAlpha = 1 / 9;
1493 for (var y = 0; y < 3; y++) {
1494 for (var x = 0; x < 3; x++) {
1495 context.drawImage(tempCanvas, x, y, w, h, 0, 0, w, h);
1496 }
1497 }
1498 context.restore();
1499 }
1500 this._setDirty();
1501};
1502
1503/**
1504 * Add a callback function that will be called when the bitmap is loaded.
1505 *
1506 * @method addLoadListener
1507 * @param {Function} listner The callback function
1508 */
1509Bitmap.prototype.addLoadListener = function(listner) {
1510 if (!this.isReady()) {
1511 this._loadListeners.push(listner);
1512 } else {
1513 listner(this);
1514 }
1515};
1516
1517/**
1518 * @method _makeFontNameText
1519 * @private
1520 */
1521Bitmap.prototype._makeFontNameText = function() {
1522 return (this.fontItalic ? 'Italic ' : '') +
1523 this.fontSize + 'px ' + this.fontFace;
1524};
1525
1526/**
1527 * @method _drawTextOutline
1528 * @param {String} text
1529 * @param {Number} tx
1530 * @param {Number} ty
1531 * @param {Number} maxWidth
1532 * @private
1533 */
1534Bitmap.prototype._drawTextOutline = function(text, tx, ty, maxWidth) {
1535 var context = this._context;
1536 context.strokeStyle = this.outlineColor;
1537 context.lineWidth = this.outlineWidth;
1538 context.lineJoin = 'round';
1539 context.strokeText(text, tx, ty, maxWidth);
1540};
1541
1542/**
1543 * @method _drawTextBody
1544 * @param {String} text
1545 * @param {Number} tx
1546 * @param {Number} ty
1547 * @param {Number} maxWidth
1548 * @private
1549 */
1550Bitmap.prototype._drawTextBody = function(text, tx, ty, maxWidth) {
1551 var context = this._context;
1552 context.fillStyle = this.textColor;
1553 context.fillText(text, tx, ty, maxWidth);
1554};
1555
1556/**
1557 * @method _onLoad
1558 * @private
1559 */
1560Bitmap.prototype._onLoad = function() {
1561 this._image.removeEventListener('load', this._loadListener);
1562 this._image.removeEventListener('error', this._errorListener);
1563
1564 this._renewCanvas();
1565
1566 switch(this._loadingState){
1567 case 'requesting':
1568 this._loadingState = 'requestCompleted';
1569 if(this._decodeAfterRequest){
1570 this.decode();
1571 }else{
1572 this._loadingState = 'purged';
1573 this._clearImgInstance();
1574 }
1575 break;
1576
1577 case 'decrypting':
1578 window.URL.revokeObjectURL(this._image.src);
1579 this._loadingState = 'decryptCompleted';
1580 if(this._decodeAfterRequest){
1581 this.decode();
1582 }else{
1583 this._loadingState = 'purged';
1584 this._clearImgInstance();
1585 }
1586 break;
1587 }
1588};
1589
1590Bitmap.prototype.decode = function(){
1591 switch(this._loadingState){
1592 case 'requestCompleted': case 'decryptCompleted':
1593 this._loadingState = 'loaded';
1594
1595 if(!this.__canvas) this._createBaseTexture(this._image);
1596 this._setDirty();
1597 this._callLoadListeners();
1598 break;
1599
1600 case 'requesting': case 'decrypting':
1601 this._decodeAfterRequest = true;
1602 if (!this._loader) {
1603 this._loader = ResourceHandler.createLoader(this._url, this._requestImage.bind(this, this._url), this._onError.bind(this));
1604 this._image.removeEventListener('error', this._errorListener);
1605 this._image.addEventListener('error', this._errorListener = this._loader);
1606 }
1607 break;
1608
1609 case 'pending': case 'purged': case 'error':
1610 this._decodeAfterRequest = true;
1611 this._requestImage(this._url);
1612 break;
1613 }
1614};
1615
1616/**
1617 * @method _callLoadListeners
1618 * @private
1619 */
1620Bitmap.prototype._callLoadListeners = function() {
1621 while (this._loadListeners.length > 0) {
1622 var listener = this._loadListeners.shift();
1623 listener(this);
1624 }
1625};
1626
1627/**
1628 * @method _onError
1629 * @private
1630 */
1631Bitmap.prototype._onError = function() {
1632 this._image.removeEventListener('load', this._loadListener);
1633 this._image.removeEventListener('error', this._errorListener);
1634 this._loadingState = 'error';
1635};
1636
1637/**
1638 * @method _setDirty
1639 * @private
1640 */
1641Bitmap.prototype._setDirty = function() {
1642 this._dirty = true;
1643};
1644
1645/**
1646 * updates texture is bitmap was dirty
1647 * @method checkDirty
1648 */
1649Bitmap.prototype.checkDirty = function() {
1650 if (this._dirty) {
1651 this._baseTexture.update();
1652 this._dirty = false;
1653 }
1654};
1655
1656Bitmap.request = function(url){
1657 var bitmap = Object.create(Bitmap.prototype);
1658 bitmap._defer = true;
1659 bitmap.initialize();
1660
1661 bitmap._url = url;
1662 bitmap._loadingState = 'pending';
1663
1664 return bitmap;
1665};
1666
1667Bitmap.prototype._requestImage = function(url){
1668 if(Bitmap._reuseImages.length !== 0){
1669 this._image = Bitmap._reuseImages.pop();
1670 }else{
1671 this._image = new Image();
1672 }
1673
1674 if (this._decodeAfterRequest && !this._loader) {
1675 this._loader = ResourceHandler.createLoader(url, this._requestImage.bind(this, url), this._onError.bind(this));
1676 }
1677
1678 this._image = new Image();
1679 this._url = url;
1680 this._loadingState = 'requesting';
1681
1682 if(!Decrypter.checkImgIgnore(url) && Decrypter.hasEncryptedImages) {
1683 this._loadingState = 'decrypting';
1684 Decrypter.decryptImg(url, this);
1685 } else {
1686 this._image.src = url;
1687
1688 this._image.addEventListener('load', this._loadListener = Bitmap.prototype._onLoad.bind(this));
1689 this._image.addEventListener('error', this._errorListener = this._loader || Bitmap.prototype._onError.bind(this));
1690 }
1691};
1692
1693Bitmap.prototype.isRequestOnly = function(){
1694 return !(this._decodeAfterRequest || this.isReady());
1695};
1696
1697Bitmap.prototype.isRequestReady = function(){
1698 return this._loadingState !== 'pending' &&
1699 this._loadingState !== 'requesting' &&
1700 this._loadingState !== 'decrypting';
1701};
1702
1703Bitmap.prototype.startRequest = function(){
1704 if(this._loadingState === 'pending'){
1705 this._decodeAfterRequest = false;
1706 this._requestImage(this._url);
1707 }
1708};
1709
1710//-----------------------------------------------------------------------------
1711/**
1712 * The static class that carries out graphics processing.
1713 *
1714 * @class Graphics
1715 */
1716function Graphics() {
1717 throw new Error('This is a static class');
1718}
1719
1720Graphics._cssFontLoading = document.fonts && document.fonts.ready;
1721Graphics._fontLoaded = null;
1722Graphics._videoVolume = 1;
1723
1724/**
1725 * Initializes the graphics system.
1726 *
1727 * @static
1728 * @method initialize
1729 * @param {Number} width The width of the game screen
1730 * @param {Number} height The height of the game screen
1731 * @param {String} type The type of the renderer.
1732 * 'canvas', 'webgl', or 'auto'.
1733 */
1734Graphics.initialize = function(width, height, type) {
1735 this._width = width || 800;
1736 this._height = height || 600;
1737 this._rendererType = type || 'auto';
1738 this._boxWidth = this._width;
1739 this._boxHeight = this._height;
1740
1741 this._scale = 1;
1742 this._realScale = 1;
1743
1744 this._errorShowed = false;
1745 this._errorPrinter = null;
1746 this._canvas = null;
1747 this._video = null;
1748 this._videoUnlocked = false;
1749 this._videoLoading = false;
1750 this._upperCanvas = null;
1751 this._renderer = null;
1752 this._fpsMeter = null;
1753 this._modeBox = null;
1754 this._skipCount = 0;
1755 this._maxSkip = 3;
1756 this._rendered = false;
1757 this._loadingImage = null;
1758 this._loadingCount = 0;
1759 this._fpsMeterToggled = false;
1760 this._stretchEnabled = this._defaultStretchMode();
1761
1762 this._canUseDifferenceBlend = false;
1763 this._canUseSaturationBlend = false;
1764 this._hiddenCanvas = null;
1765
1766 this._testCanvasBlendModes();
1767 this._modifyExistingElements();
1768 this._updateRealScale();
1769 this._createAllElements();
1770 this._disableTextSelection();
1771 this._disableContextMenu();
1772 this._setupEventHandlers();
1773 this._setupCssFontLoading();
1774};
1775
1776
1777Graphics._setupCssFontLoading = function(){
1778 if(Graphics._cssFontLoading){
1779 document.fonts.ready.then(function(fonts){
1780 Graphics._fontLoaded = fonts;
1781 }).catch(function(error){
1782 SceneManager.onError(error);
1783 });
1784 }
1785};
1786
1787Graphics.canUseCssFontLoading = function(){
1788 return !!this._cssFontLoading;
1789};
1790
1791/**
1792 * The total frame count of the game screen.
1793 *
1794 * @static
1795 * @property frameCount
1796 * @type Number
1797 */
1798Graphics.frameCount = 0;
1799
1800/**
1801 * The alias of PIXI.blendModes.NORMAL.
1802 *
1803 * @static
1804 * @property BLEND_NORMAL
1805 * @type Number
1806 * @final
1807 */
1808Graphics.BLEND_NORMAL = 0;
1809
1810/**
1811 * The alias of PIXI.blendModes.ADD.
1812 *
1813 * @static
1814 * @property BLEND_ADD
1815 * @type Number
1816 * @final
1817 */
1818Graphics.BLEND_ADD = 1;
1819
1820/**
1821 * The alias of PIXI.blendModes.MULTIPLY.
1822 *
1823 * @static
1824 * @property BLEND_MULTIPLY
1825 * @type Number
1826 * @final
1827 */
1828Graphics.BLEND_MULTIPLY = 2;
1829
1830/**
1831 * The alias of PIXI.blendModes.SCREEN.
1832 *
1833 * @static
1834 * @property BLEND_SCREEN
1835 * @type Number
1836 * @final
1837 */
1838Graphics.BLEND_SCREEN = 3;
1839
1840/**
1841 * Marks the beginning of each frame for FPSMeter.
1842 *
1843 * @static
1844 * @method tickStart
1845 */
1846Graphics.tickStart = function() {
1847 if (this._fpsMeter) {
1848 this._fpsMeter.tickStart();
1849 }
1850};
1851
1852/**
1853 * Marks the end of each frame for FPSMeter.
1854 *
1855 * @static
1856 * @method tickEnd
1857 */
1858Graphics.tickEnd = function() {
1859 if (this._fpsMeter && this._rendered) {
1860 this._fpsMeter.tick();
1861 }
1862};
1863
1864/**
1865 * Renders the stage to the game screen.
1866 *
1867 * @static
1868 * @method render
1869 * @param {Stage} stage The stage object to be rendered
1870 */
1871Graphics.render = function(stage) {
1872 if (this._skipCount === 0) {
1873 var startTime = Date.now();
1874 if (stage) {
1875 this._renderer.render(stage);
1876 if (this._renderer.gl && this._renderer.gl.flush) {
1877 this._renderer.gl.flush();
1878 }
1879 }
1880 var endTime = Date.now();
1881 var elapsed = endTime - startTime;
1882 this._skipCount = Math.min(Math.floor(elapsed / 15), this._maxSkip);
1883 this._rendered = true;
1884 } else {
1885 this._skipCount--;
1886 this._rendered = false;
1887 }
1888 this.frameCount++;
1889};
1890
1891/**
1892 * Checks whether the renderer type is WebGL.
1893 *
1894 * @static
1895 * @method isWebGL
1896 * @return {Boolean} True if the renderer type is WebGL
1897 */
1898Graphics.isWebGL = function() {
1899 return this._renderer && this._renderer.type === PIXI.RENDERER_TYPE.WEBGL;
1900};
1901
1902/**
1903 * Checks whether the current browser supports WebGL.
1904 *
1905 * @static
1906 * @method hasWebGL
1907 * @return {Boolean} True if the current browser supports WebGL.
1908 */
1909Graphics.hasWebGL = function() {
1910 try {
1911 var canvas = document.createElement('canvas');
1912 return !!(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
1913 } catch (e) {
1914 return false;
1915 }
1916};
1917
1918/**
1919 * Checks whether the canvas blend mode 'difference' is supported.
1920 *
1921 * @static
1922 * @method canUseDifferenceBlend
1923 * @return {Boolean} True if the canvas blend mode 'difference' is supported
1924 */
1925Graphics.canUseDifferenceBlend = function() {
1926 return this._canUseDifferenceBlend;
1927};
1928
1929/**
1930 * Checks whether the canvas blend mode 'saturation' is supported.
1931 *
1932 * @static
1933 * @method canUseSaturationBlend
1934 * @return {Boolean} True if the canvas blend mode 'saturation' is supported
1935 */
1936Graphics.canUseSaturationBlend = function() {
1937 return this._canUseSaturationBlend;
1938};
1939
1940/**
1941 * Sets the source of the "Now Loading" image.
1942 *
1943 * @static
1944 * @method setLoadingImage
1945 */
1946Graphics.setLoadingImage = function(src) {
1947 this._loadingImage = new Image();
1948 this._loadingImage.src = src;
1949};
1950
1951/**
1952 * Initializes the counter for displaying the "Now Loading" image.
1953 *
1954 * @static
1955 * @method startLoading
1956 */
1957Graphics.startLoading = function() {
1958 this._loadingCount = 0;
1959};
1960
1961/**
1962 * Increments the loading counter and displays the "Now Loading" image if necessary.
1963 *
1964 * @static
1965 * @method updateLoading
1966 */
1967Graphics.updateLoading = function() {
1968 this._loadingCount++;
1969 this._paintUpperCanvas();
1970 this._upperCanvas.style.opacity = 1;
1971};
1972
1973/**
1974 * Erases the "Now Loading" image.
1975 *
1976 * @static
1977 * @method endLoading
1978 */
1979Graphics.endLoading = function() {
1980 this._clearUpperCanvas();
1981 this._upperCanvas.style.opacity = 0;
1982};
1983
1984/**
1985 * Displays the loading error text to the screen.
1986 *
1987 * @static
1988 * @method printLoadingError
1989 * @param {String} url The url of the resource failed to load
1990 */
1991Graphics.printLoadingError = function(url) {
1992 if (this._errorPrinter && !this._errorShowed) {
1993 this._errorPrinter.innerHTML = this._makeErrorHtml('Loading Error', 'Failed to load: ' + url);
1994 var button = document.createElement('button');
1995 button.innerHTML = 'Retry';
1996 button.style.fontSize = '24px';
1997 button.style.color = '#ffffff';
1998 button.style.backgroundColor = '#000000';
1999 button.onmousedown = button.ontouchstart = function(event) {
2000 ResourceHandler.retry();
2001 event.stopPropagation();
2002 };
2003 this._errorPrinter.appendChild(button);
2004 this._loadingCount = -Infinity;
2005 }
2006};
2007
2008/**
2009 * Erases the loading error text.
2010 *
2011 * @static
2012 * @method eraseLoadingError
2013 */
2014Graphics.eraseLoadingError = function() {
2015 if (this._errorPrinter && !this._errorShowed) {
2016 this._errorPrinter.innerHTML = '';
2017 this.startLoading();
2018 }
2019};
2020
2021/**
2022 * Displays the error text to the screen.
2023 *
2024 * @static
2025 * @method printError
2026 * @param {String} name The name of the error
2027 * @param {String} message The message of the error
2028 */
2029Graphics.printError = function(name, message) {
2030 this._errorShowed = true;
2031 if (this._errorPrinter) {
2032 this._errorPrinter.innerHTML = this._makeErrorHtml(name, message);
2033 }
2034 this._applyCanvasFilter();
2035 this._clearUpperCanvas();
2036};
2037
2038/**
2039 * Shows the FPSMeter element.
2040 *
2041 * @static
2042 * @method showFps
2043 */
2044Graphics.showFps = function() {
2045 if (this._fpsMeter) {
2046 this._fpsMeter.show();
2047 this._modeBox.style.opacity = 1;
2048 }
2049};
2050
2051/**
2052 * Hides the FPSMeter element.
2053 *
2054 * @static
2055 * @method hideFps
2056 */
2057Graphics.hideFps = function() {
2058 if (this._fpsMeter) {
2059 this._fpsMeter.hide();
2060 this._modeBox.style.opacity = 0;
2061 }
2062};
2063
2064/**
2065 * Loads a font file.
2066 *
2067 * @static
2068 * @method loadFont
2069 * @param {String} name The face name of the font
2070 * @param {String} url The url of the font file
2071 */
2072Graphics.loadFont = function(name, url) {
2073 var style = document.createElement('style');
2074 var head = document.getElementsByTagName('head');
2075 var rule = '@font-face { font-family: "' + name + '"; src: url("' + url + '"); }';
2076 style.type = 'text/css';
2077 head.item(0).appendChild(style);
2078 style.sheet.insertRule(rule, 0);
2079 this._createFontLoader(name);
2080};
2081
2082/**
2083 * Checks whether the font file is loaded.
2084 *
2085 * @static
2086 * @method isFontLoaded
2087 * @param {String} name The face name of the font
2088 * @return {Boolean} True if the font file is loaded
2089 */
2090Graphics.isFontLoaded = function(name) {
2091 if (Graphics._cssFontLoading) {
2092 if(Graphics._fontLoaded){
2093 return Graphics._fontLoaded.check('10px "'+name+'"');
2094 }
2095
2096 return false;
2097 } else {
2098 if (!this._hiddenCanvas) {
2099 this._hiddenCanvas = document.createElement('canvas');
2100 }
2101 var context = this._hiddenCanvas.getContext('2d');
2102 var text = 'abcdefghijklmnopqrstuvwxyz';
2103 var width1, width2;
2104 context.font = '40px ' + name + ', sans-serif';
2105 width1 = context.measureText(text).width;
2106 context.font = '40px sans-serif';
2107 width2 = context.measureText(text).width;
2108 return width1 !== width2;
2109 }
2110};
2111
2112/**
2113 * Starts playback of a video.
2114 *
2115 * @static
2116 * @method playVideo
2117 * @param {String} src
2118 */
2119Graphics.playVideo = function(src) {
2120 this._videoLoader = ResourceHandler.createLoader(null, this._playVideo.bind(this, src), this._onVideoError.bind(this));
2121 this._playVideo(src);
2122};
2123
2124/**
2125 * @static
2126 * @method _playVideo
2127 * @param {String} src
2128 * @private
2129 */
2130Graphics._playVideo = function(src) {
2131 this._video.src = src;
2132 this._video.onloadeddata = this._onVideoLoad.bind(this);
2133 this._video.onerror = this._videoLoader;
2134 this._video.onended = this._onVideoEnd.bind(this);
2135 this._video.load();
2136 this._videoLoading = true;
2137};
2138
2139/**
2140 * Checks whether the video is playing.
2141 *
2142 * @static
2143 * @method isVideoPlaying
2144 * @return {Boolean} True if the video is playing
2145 */
2146Graphics.isVideoPlaying = function() {
2147 return this._videoLoading || this._isVideoVisible();
2148};
2149
2150/**
2151 * Checks whether the browser can play the specified video type.
2152 *
2153 * @static
2154 * @method canPlayVideoType
2155 * @param {String} type The video type to test support for
2156 * @return {Boolean} True if the browser can play the specified video type
2157 */
2158Graphics.canPlayVideoType = function(type) {
2159 return this._video && this._video.canPlayType(type);
2160};
2161
2162/**
2163 * Sets volume of a video.
2164 *
2165 * @static
2166 * @method setVideoVolume
2167 * @param {Number} value
2168 */
2169Graphics.setVideoVolume = function(value) {
2170 this._videoVolume = value;
2171 if (this._video) {
2172 this._video.volume = this._videoVolume;
2173 }
2174};
2175
2176/**
2177 * Converts an x coordinate on the page to the corresponding
2178 * x coordinate on the canvas area.
2179 *
2180 * @static
2181 * @method pageToCanvasX
2182 * @param {Number} x The x coordinate on the page to be converted
2183 * @return {Number} The x coordinate on the canvas area
2184 */
2185Graphics.pageToCanvasX = function(x) {
2186 if (this._canvas) {
2187 var left = this._canvas.offsetLeft;
2188 return Math.round((x - left) / this._realScale);
2189 } else {
2190 return 0;
2191 }
2192};
2193
2194/**
2195 * Converts a y coordinate on the page to the corresponding
2196 * y coordinate on the canvas area.
2197 *
2198 * @static
2199 * @method pageToCanvasY
2200 * @param {Number} y The y coordinate on the page to be converted
2201 * @return {Number} The y coordinate on the canvas area
2202 */
2203Graphics.pageToCanvasY = function(y) {
2204 if (this._canvas) {
2205 var top = this._canvas.offsetTop;
2206 return Math.round((y - top) / this._realScale);
2207 } else {
2208 return 0;
2209 }
2210};
2211
2212/**
2213 * Checks whether the specified point is inside the game canvas area.
2214 *
2215 * @static
2216 * @method isInsideCanvas
2217 * @param {Number} x The x coordinate on the canvas area
2218 * @param {Number} y The y coordinate on the canvas area
2219 * @return {Boolean} True if the specified point is inside the game canvas area
2220 */
2221Graphics.isInsideCanvas = function(x, y) {
2222 return (x >= 0 && x < this._width && y >= 0 && y < this._height);
2223};
2224
2225/**
2226 * Calls pixi.js garbage collector
2227 */
2228Graphics.callGC = function() {
2229 if (Graphics.isWebGL()) {
2230 Graphics._renderer.textureGC.run();
2231 }
2232};
2233
2234
2235/**
2236 * The width of the game screen.
2237 *
2238 * @static
2239 * @property width
2240 * @type Number
2241 */
2242Object.defineProperty(Graphics, 'width', {
2243 get: function() {
2244 return this._width;
2245 },
2246 set: function(value) {
2247 if (this._width !== value) {
2248 this._width = value;
2249 this._updateAllElements();
2250 }
2251 },
2252 configurable: true
2253});
2254
2255/**
2256 * The height of the game screen.
2257 *
2258 * @static
2259 * @property height
2260 * @type Number
2261 */
2262Object.defineProperty(Graphics, 'height', {
2263 get: function() {
2264 return this._height;
2265 },
2266 set: function(value) {
2267 if (this._height !== value) {
2268 this._height = value;
2269 this._updateAllElements();
2270 }
2271 },
2272 configurable: true
2273});
2274
2275/**
2276 * The width of the window display area.
2277 *
2278 * @static
2279 * @property boxWidth
2280 * @type Number
2281 */
2282Object.defineProperty(Graphics, 'boxWidth', {
2283 get: function() {
2284 return this._boxWidth;
2285 },
2286 set: function(value) {
2287 this._boxWidth = value;
2288 },
2289 configurable: true
2290});
2291
2292/**
2293 * The height of the window display area.
2294 *
2295 * @static
2296 * @property boxHeight
2297 * @type Number
2298 */
2299Object.defineProperty(Graphics, 'boxHeight', {
2300 get: function() {
2301 return this._boxHeight;
2302 },
2303 set: function(value) {
2304 this._boxHeight = value;
2305 },
2306 configurable: true
2307});
2308
2309/**
2310 * The zoom scale of the game screen.
2311 *
2312 * @static
2313 * @property scale
2314 * @type Number
2315 */
2316Object.defineProperty(Graphics, 'scale', {
2317 get: function() {
2318 return this._scale;
2319 },
2320 set: function(value) {
2321 if (this._scale !== value) {
2322 this._scale = value;
2323 this._updateAllElements();
2324 }
2325 },
2326 configurable: true
2327});
2328
2329/**
2330 * @static
2331 * @method _createAllElements
2332 * @private
2333 */
2334Graphics._createAllElements = function() {
2335 this._createErrorPrinter();
2336 this._createCanvas();
2337 this._createVideo();
2338 this._createUpperCanvas();
2339 this._createRenderer();
2340 this._createFPSMeter();
2341 this._createModeBox();
2342 this._createGameFontLoader();
2343};
2344
2345/**
2346 * @static
2347 * @method _updateAllElements
2348 * @private
2349 */
2350Graphics._updateAllElements = function() {
2351 this._updateRealScale();
2352 this._updateErrorPrinter();
2353 this._updateCanvas();
2354 this._updateVideo();
2355 this._updateUpperCanvas();
2356 this._updateRenderer();
2357 this._paintUpperCanvas();
2358};
2359
2360/**
2361 * @static
2362 * @method _updateRealScale
2363 * @private
2364 */
2365Graphics._updateRealScale = function() {
2366 if (this._stretchEnabled) {
2367 var h = window.innerWidth / this._width;
2368 var v = window.innerHeight / this._height;
2369 if (h >= 1 && h - 0.01 <= 1) h = 1;
2370 if (v >= 1 && v - 0.01 <= 1) v = 1;
2371 this._realScale = Math.min(h, v);
2372 } else {
2373 this._realScale = this._scale;
2374 }
2375};
2376
2377/**
2378 * @static
2379 * @method _makeErrorHtml
2380 * @param {String} name
2381 * @param {String} message
2382 * @return {String}
2383 * @private
2384 */
2385Graphics._makeErrorHtml = function(name, message) {
2386 return ('<font color="yellow"><b>' + name + '</b></font><br>' +
2387 '<font color="white">' + message + '</font><br>');
2388};
2389
2390/**
2391 * @static
2392 * @method _defaultStretchMode
2393 * @private
2394 */
2395Graphics._defaultStretchMode = function() {
2396 return Utils.isNwjs() || Utils.isMobileDevice();
2397};
2398
2399/**
2400 * @static
2401 * @method _testCanvasBlendModes
2402 * @private
2403 */
2404Graphics._testCanvasBlendModes = function() {
2405 var canvas, context, imageData1, imageData2;
2406 canvas = document.createElement('canvas');
2407 canvas.width = 1;
2408 canvas.height = 1;
2409 context = canvas.getContext('2d');
2410 context.globalCompositeOperation = 'source-over';
2411 context.fillStyle = 'white';
2412 context.fillRect(0, 0, 1, 1);
2413 context.globalCompositeOperation = 'difference';
2414 context.fillStyle = 'white';
2415 context.fillRect(0, 0, 1, 1);
2416 imageData1 = context.getImageData(0, 0, 1, 1);
2417 context.globalCompositeOperation = 'source-over';
2418 context.fillStyle = 'black';
2419 context.fillRect(0, 0, 1, 1);
2420 context.globalCompositeOperation = 'saturation';
2421 context.fillStyle = 'white';
2422 context.fillRect(0, 0, 1, 1);
2423 imageData2 = context.getImageData(0, 0, 1, 1);
2424 this._canUseDifferenceBlend = imageData1.data[0] === 0;
2425 this._canUseSaturationBlend = imageData2.data[0] === 0;
2426};
2427
2428/**
2429 * @static
2430 * @method _modifyExistingElements
2431 * @private
2432 */
2433Graphics._modifyExistingElements = function() {
2434 var elements = document.getElementsByTagName('*');
2435 for (var i = 0; i < elements.length; i++) {
2436 if (elements[i].style.zIndex > 0) {
2437 elements[i].style.zIndex = 0;
2438 }
2439 }
2440};
2441
2442/**
2443 * @static
2444 * @method _createErrorPrinter
2445 * @private
2446 */
2447Graphics._createErrorPrinter = function() {
2448 this._errorPrinter = document.createElement('p');
2449 this._errorPrinter.id = 'ErrorPrinter';
2450 this._updateErrorPrinter();
2451 document.body.appendChild(this._errorPrinter);
2452};
2453
2454/**
2455 * @static
2456 * @method _updateErrorPrinter
2457 * @private
2458 */
2459Graphics._updateErrorPrinter = function() {
2460 this._errorPrinter.width = this._width * 0.9;
2461 this._errorPrinter.height = 40;
2462 this._errorPrinter.style.textAlign = 'center';
2463 this._errorPrinter.style.textShadow = '1px 1px 3px #000';
2464 this._errorPrinter.style.fontSize = '20px';
2465 this._errorPrinter.style.zIndex = 99;
2466 this._centerElement(this._errorPrinter);
2467};
2468
2469/**
2470 * @static
2471 * @method _createCanvas
2472 * @private
2473 */
2474Graphics._createCanvas = function() {
2475 this._canvas = document.createElement('canvas');
2476 this._canvas.id = 'GameCanvas';
2477 this._updateCanvas();
2478 document.body.appendChild(this._canvas);
2479};
2480
2481/**
2482 * @static
2483 * @method _updateCanvas
2484 * @private
2485 */
2486Graphics._updateCanvas = function() {
2487 this._canvas.width = this._width;
2488 this._canvas.height = this._height;
2489 this._canvas.style.zIndex = 1;
2490 this._centerElement(this._canvas);
2491};
2492
2493/**
2494 * @static
2495 * @method _createVideo
2496 * @private
2497 */
2498Graphics._createVideo = function() {
2499 this._video = document.createElement('video');
2500 this._video.id = 'GameVideo';
2501 this._video.style.opacity = 0;
2502 this._video.setAttribute('playsinline', '');
2503 this._video.volume = this._videoVolume;
2504 this._updateVideo();
2505 makeVideoPlayableInline(this._video);
2506 document.body.appendChild(this._video);
2507};
2508
2509/**
2510 * @static
2511 * @method _updateVideo
2512 * @private
2513 */
2514Graphics._updateVideo = function() {
2515 this._video.width = this._width;
2516 this._video.height = this._height;
2517 this._video.style.zIndex = 2;
2518 this._centerElement(this._video);
2519};
2520
2521/**
2522 * @static
2523 * @method _createUpperCanvas
2524 * @private
2525 */
2526Graphics._createUpperCanvas = function() {
2527 this._upperCanvas = document.createElement('canvas');
2528 this._upperCanvas.id = 'UpperCanvas';
2529 this._updateUpperCanvas();
2530 document.body.appendChild(this._upperCanvas);
2531};
2532
2533/**
2534 * @static
2535 * @method _updateUpperCanvas
2536 * @private
2537 */
2538Graphics._updateUpperCanvas = function() {
2539 this._upperCanvas.width = this._width;
2540 this._upperCanvas.height = this._height;
2541 this._upperCanvas.style.zIndex = 3;
2542 this._centerElement(this._upperCanvas);
2543};
2544
2545/**
2546 * @static
2547 * @method _clearUpperCanvas
2548 * @private
2549 */
2550Graphics._clearUpperCanvas = function() {
2551 var context = this._upperCanvas.getContext('2d');
2552 context.clearRect(0, 0, this._width, this._height);
2553};
2554
2555/**
2556 * @static
2557 * @method _paintUpperCanvas
2558 * @private
2559 */
2560Graphics._paintUpperCanvas = function() {
2561 this._clearUpperCanvas();
2562 if (this._loadingImage && this._loadingCount >= 20) {
2563 var context = this._upperCanvas.getContext('2d');
2564 var dx = (this._width - this._loadingImage.width) / 2;
2565 var dy = (this._height - this._loadingImage.height) / 2;
2566 var alpha = ((this._loadingCount - 20) / 30).clamp(0, 1);
2567 context.save();
2568 context.globalAlpha = alpha;
2569 context.drawImage(this._loadingImage, dx, dy);
2570 context.restore();
2571 }
2572};
2573
2574/**
2575 * @static
2576 * @method _createRenderer
2577 * @private
2578 */
2579Graphics._createRenderer = function() {
2580 PIXI.dontSayHello = true;
2581 var width = this._width;
2582 var height = this._height;
2583 var options = { view: this._canvas };
2584 try {
2585 switch (this._rendererType) {
2586 case 'canvas':
2587 this._renderer = new PIXI.CanvasRenderer(width, height, options);
2588 break;
2589 case 'webgl':
2590 this._renderer = new PIXI.WebGLRenderer(width, height, options);
2591 break;
2592 default:
2593 this._renderer = PIXI.autoDetectRenderer(width, height, options);
2594 break;
2595 }
2596
2597 if(this._renderer && this._renderer.textureGC)
2598 this._renderer.textureGC.maxIdle = 1;
2599
2600 } catch (e) {
2601 this._renderer = null;
2602 }
2603};
2604
2605/**
2606 * @static
2607 * @method _updateRenderer
2608 * @private
2609 */
2610Graphics._updateRenderer = function() {
2611 if (this._renderer) {
2612 this._renderer.resize(this._width, this._height);
2613 }
2614};
2615
2616/**
2617 * @static
2618 * @method _createFPSMeter
2619 * @private
2620 */
2621Graphics._createFPSMeter = function() {
2622 var options = { graph: 1, decimals: 0, theme: 'transparent', toggleOn: null };
2623 this._fpsMeter = new FPSMeter(options);
2624 this._fpsMeter.hide();
2625};
2626
2627/**
2628 * @static
2629 * @method _createModeBox
2630 * @private
2631 */
2632Graphics._createModeBox = function() {
2633 var box = document.createElement('div');
2634 box.id = 'modeTextBack';
2635 box.style.position = 'absolute';
2636 box.style.left = '5px';
2637 box.style.top = '5px';
2638 box.style.width = '119px';
2639 box.style.height = '58px';
2640 box.style.background = 'rgba(0,0,0,0.2)';
2641 box.style.zIndex = 9;
2642 box.style.opacity = 0;
2643
2644 var text = document.createElement('div');
2645 text.id = 'modeText';
2646 text.style.position = 'absolute';
2647 text.style.left = '0px';
2648 text.style.top = '41px';
2649 text.style.width = '119px';
2650 text.style.fontSize = '12px';
2651 text.style.fontFamily = 'monospace';
2652 text.style.color = 'white';
2653 text.style.textAlign = 'center';
2654 text.style.textShadow = '1px 1px 0 rgba(0,0,0,0.5)';
2655 text.innerHTML = this.isWebGL() ? 'WebGL mode' : 'Canvas mode';
2656
2657 document.body.appendChild(box);
2658 box.appendChild(text);
2659
2660 this._modeBox = box;
2661};
2662
2663/**
2664 * @static
2665 * @method _createGameFontLoader
2666 * @private
2667 */
2668Graphics._createGameFontLoader = function() {
2669 this._createFontLoader('GameFont');
2670};
2671
2672/**
2673 * @static
2674 * @method _createFontLoader
2675 * @param {String} name
2676 * @private
2677 */
2678Graphics._createFontLoader = function(name) {
2679 var div = document.createElement('div');
2680 var text = document.createTextNode('.');
2681 div.style.fontFamily = name;
2682 div.style.fontSize = '0px';
2683 div.style.color = 'transparent';
2684 div.style.position = 'absolute';
2685 div.style.margin = 'auto';
2686 div.style.top = '0px';
2687 div.style.left = '0px';
2688 div.style.width = '1px';
2689 div.style.height = '1px';
2690 div.appendChild(text);
2691 document.body.appendChild(div);
2692};
2693
2694/**
2695 * @static
2696 * @method _centerElement
2697 * @param {HTMLElement} element
2698 * @private
2699 */
2700Graphics._centerElement = function(element) {
2701 var width = element.width * this._realScale;
2702 var height = element.height * this._realScale;
2703 element.style.position = 'absolute';
2704 element.style.margin = 'auto';
2705 element.style.top = 0;
2706 element.style.left = 0;
2707 element.style.right = 0;
2708 element.style.bottom = 0;
2709 element.style.width = width + 'px';
2710 element.style.height = height + 'px';
2711};
2712
2713/**
2714 * @static
2715 * @method _disableTextSelection
2716 * @private
2717 */
2718Graphics._disableTextSelection = function() {
2719 var body = document.body;
2720 body.style.userSelect = 'none';
2721 body.style.webkitUserSelect = 'none';
2722 body.style.msUserSelect = 'none';
2723 body.style.mozUserSelect = 'none';
2724};
2725
2726/**
2727 * @static
2728 * @method _disableContextMenu
2729 * @private
2730 */
2731Graphics._disableContextMenu = function() {
2732 var elements = document.body.getElementsByTagName('*');
2733 var oncontextmenu = function() { return false; };
2734 for (var i = 0; i < elements.length; i++) {
2735 elements[i].oncontextmenu = oncontextmenu;
2736 }
2737};
2738
2739/**
2740 * @static
2741 * @method _applyCanvasFilter
2742 * @private
2743 */
2744Graphics._applyCanvasFilter = function() {
2745 if (this._canvas) {
2746 this._canvas.style.opacity = 0.5;
2747 this._canvas.style.filter = 'blur(8px)';
2748 this._canvas.style.webkitFilter = 'blur(8px)';
2749 }
2750};
2751
2752/**
2753 * @static
2754 * @method _onVideoLoad
2755 * @private
2756 */
2757Graphics._onVideoLoad = function() {
2758 this._video.play();
2759 this._updateVisibility(true);
2760 this._videoLoading = false;
2761};
2762
2763/**
2764 * @static
2765 * @method _onVideoError
2766 * @private
2767 */
2768Graphics._onVideoError = function() {
2769 this._updateVisibility(false);
2770 this._videoLoading = false;
2771};
2772
2773/**
2774 * @static
2775 * @method _onVideoEnd
2776 * @private
2777 */
2778Graphics._onVideoEnd = function() {
2779 this._updateVisibility(false);
2780};
2781
2782/**
2783 * @static
2784 * @method _updateVisibility
2785 * @param {Boolean} videoVisible
2786 * @private
2787 */
2788Graphics._updateVisibility = function(videoVisible) {
2789 this._video.style.opacity = videoVisible ? 1 : 0;
2790 this._canvas.style.opacity = videoVisible ? 0 : 1;
2791};
2792
2793/**
2794 * @static
2795 * @method _isVideoVisible
2796 * @return {Boolean}
2797 * @private
2798 */
2799Graphics._isVideoVisible = function() {
2800 return this._video.style.opacity > 0;
2801};
2802
2803/**
2804 * @static
2805 * @method _setupEventHandlers
2806 * @private
2807 */
2808Graphics._setupEventHandlers = function() {
2809 window.addEventListener('resize', this._onWindowResize.bind(this));
2810 document.addEventListener('keydown', this._onKeyDown.bind(this));
2811 document.addEventListener('keydown', this._onTouchEnd.bind(this));
2812 document.addEventListener('mousedown', this._onTouchEnd.bind(this));
2813 document.addEventListener('touchend', this._onTouchEnd.bind(this));
2814};
2815
2816/**
2817 * @static
2818 * @method _onWindowResize
2819 * @private
2820 */
2821Graphics._onWindowResize = function() {
2822 this._updateAllElements();
2823};
2824
2825/**
2826 * @static
2827 * @method _onKeyDown
2828 * @param {KeyboardEvent} event
2829 * @private
2830 */
2831Graphics._onKeyDown = function(event) {
2832 if (!event.ctrlKey && !event.altKey) {
2833 switch (event.keyCode) {
2834 case 113: // F2
2835 event.preventDefault();
2836 this._switchFPSMeter();
2837 break;
2838 case 114: // F3
2839 event.preventDefault();
2840 this._switchStretchMode();
2841 break;
2842 case 115: // F4
2843 event.preventDefault();
2844 this._switchFullScreen();
2845 break;
2846 }
2847 }
2848};
2849
2850/**
2851 * @static
2852 * @method _onTouchEnd
2853 * @param {TouchEvent} event
2854 * @private
2855 */
2856Graphics._onTouchEnd = function(event) {
2857 if (!this._videoUnlocked) {
2858 this._video.play();
2859 this._videoUnlocked = true;
2860 }
2861 if (this._isVideoVisible() && this._video.paused) {
2862 this._video.play();
2863 }
2864};
2865
2866/**
2867 * @static
2868 * @method _switchFPSMeter
2869 * @private
2870 */
2871Graphics._switchFPSMeter = function() {
2872 if (this._fpsMeter.isPaused) {
2873 this.showFps();
2874 this._fpsMeter.showFps();
2875 this._fpsMeterToggled = false;
2876 } else if (!this._fpsMeterToggled) {
2877 this._fpsMeter.showDuration();
2878 this._fpsMeterToggled = true;
2879 } else {
2880 this.hideFps();
2881 }
2882};
2883
2884/**
2885 * @static
2886 * @method _switchStretchMode
2887 * @return {Boolean}
2888 * @private
2889 */
2890Graphics._switchStretchMode = function() {
2891 this._stretchEnabled = !this._stretchEnabled;
2892 this._updateAllElements();
2893};
2894
2895/**
2896 * @static
2897 * @method _switchFullScreen
2898 * @private
2899 */
2900Graphics._switchFullScreen = function() {
2901 if (this._isFullScreen()) {
2902 this._requestFullScreen();
2903 } else {
2904 this._cancelFullScreen();
2905 }
2906};
2907
2908/**
2909 * @static
2910 * @method _isFullScreen
2911 * @return {Boolean}
2912 * @private
2913 */
2914Graphics._isFullScreen = function() {
2915 return ((document.fullScreenElement && document.fullScreenElement !== null) ||
2916 (!document.mozFullScreen && !document.webkitFullscreenElement &&
2917 !document.msFullscreenElement));
2918};
2919
2920/**
2921 * @static
2922 * @method _requestFullScreen
2923 * @private
2924 */
2925Graphics._requestFullScreen = function() {
2926 var element = document.body;
2927 if (element.requestFullScreen) {
2928 element.requestFullScreen();
2929 } else if (element.mozRequestFullScreen) {
2930 element.mozRequestFullScreen();
2931 } else if (element.webkitRequestFullScreen) {
2932 element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
2933 } else if (element.msRequestFullscreen) {
2934 element.msRequestFullscreen();
2935 }
2936};
2937
2938/**
2939 * @static
2940 * @method _cancelFullScreen
2941 * @private
2942 */
2943Graphics._cancelFullScreen = function() {
2944 if (document.cancelFullScreen) {
2945 document.cancelFullScreen();
2946 } else if (document.mozCancelFullScreen) {
2947 document.mozCancelFullScreen();
2948 } else if (document.webkitCancelFullScreen) {
2949 document.webkitCancelFullScreen();
2950 } else if (document.msExitFullscreen) {
2951 document.msExitFullscreen();
2952 }
2953};
2954
2955//-----------------------------------------------------------------------------
2956/**
2957 * The static class that handles input data from the keyboard and gamepads.
2958 *
2959 * @class Input
2960 */
2961function Input() {
2962 throw new Error('This is a static class');
2963}
2964
2965/**
2966 * Initializes the input system.
2967 *
2968 * @static
2969 * @method initialize
2970 */
2971Input.initialize = function() {
2972 this.clear();
2973 this._wrapNwjsAlert();
2974 this._setupEventHandlers();
2975};
2976
2977/**
2978 * The wait time of the key repeat in frames.
2979 *
2980 * @static
2981 * @property keyRepeatWait
2982 * @type Number
2983 */
2984Input.keyRepeatWait = 24;
2985
2986/**
2987 * The interval of the key repeat in frames.
2988 *
2989 * @static
2990 * @property keyRepeatInterval
2991 * @type Number
2992 */
2993Input.keyRepeatInterval = 6;
2994
2995/**
2996 * A hash table to convert from a virtual key code to a mapped key name.
2997 *
2998 * @static
2999 * @property keyMapper
3000 * @type Object
3001 */
3002Input.keyMapper = {
3003 9: 'tab', // tab
3004 13: 'ok', // enter
3005 16: 'shift', // shift
3006 17: 'control', // control
3007 18: 'control', // alt
3008 27: 'escape', // escape
3009 32: 'ok', // space
3010 33: 'pageup', // pageup
3011 34: 'pagedown', // pagedown
3012 37: 'left', // left arrow
3013 38: 'up', // up arrow
3014 39: 'right', // right arrow
3015 40: 'down', // down arrow
3016 45: 'escape', // insert
3017 81: 'pageup', // Q
3018 87: 'pagedown', // W
3019 88: 'escape', // X
3020 90: 'ok', // Z
3021 96: 'escape', // numpad 0
3022 98: 'down', // numpad 2
3023 100: 'left', // numpad 4
3024 102: 'right', // numpad 6
3025 104: 'up', // numpad 8
3026 120: 'debug' // F9
3027};
3028
3029/**
3030 * A hash table to convert from a gamepad button to a mapped key name.
3031 *
3032 * @static
3033 * @property gamepadMapper
3034 * @type Object
3035 */
3036Input.gamepadMapper = {
3037 0: 'ok', // A
3038 1: 'cancel', // B
3039 2: 'shift', // X
3040 3: 'menu', // Y
3041 4: 'pageup', // LB
3042 5: 'pagedown', // RB
3043 12: 'up', // D-pad up
3044 13: 'down', // D-pad down
3045 14: 'left', // D-pad left
3046 15: 'right', // D-pad right
3047};
3048
3049/**
3050 * Clears all the input data.
3051 *
3052 * @static
3053 * @method clear
3054 */
3055Input.clear = function() {
3056 this._currentState = {};
3057 this._previousState = {};
3058 this._gamepadStates = [];
3059 this._latestButton = null;
3060 this._pressedTime = 0;
3061 this._dir4 = 0;
3062 this._dir8 = 0;
3063 this._preferredAxis = '';
3064 this._date = 0;
3065};
3066
3067/**
3068 * Updates the input data.
3069 *
3070 * @static
3071 * @method update
3072 */
3073Input.update = function() {
3074 this._pollGamepads();
3075 if (this._currentState[this._latestButton]) {
3076 this._pressedTime++;
3077 } else {
3078 this._latestButton = null;
3079 }
3080 for (var name in this._currentState) {
3081 if (this._currentState[name] && !this._previousState[name]) {
3082 this._latestButton = name;
3083 this._pressedTime = 0;
3084 this._date = Date.now();
3085 }
3086 this._previousState[name] = this._currentState[name];
3087 }
3088 this._updateDirection();
3089};
3090
3091/**
3092 * Checks whether a key is currently pressed down.
3093 *
3094 * @static
3095 * @method isPressed
3096 * @param {String} keyName The mapped name of the key
3097 * @return {Boolean} True if the key is pressed
3098 */
3099Input.isPressed = function(keyName) {
3100 if (this._isEscapeCompatible(keyName) && this.isPressed('escape')) {
3101 return true;
3102 } else {
3103 return !!this._currentState[keyName];
3104 }
3105};
3106
3107/**
3108 * Checks whether a key is just pressed.
3109 *
3110 * @static
3111 * @method isTriggered
3112 * @param {String} keyName The mapped name of the key
3113 * @return {Boolean} True if the key is triggered
3114 */
3115Input.isTriggered = function(keyName) {
3116 if (this._isEscapeCompatible(keyName) && this.isTriggered('escape')) {
3117 return true;
3118 } else {
3119 return this._latestButton === keyName && this._pressedTime === 0;
3120 }
3121};
3122
3123/**
3124 * Checks whether a key is just pressed or a key repeat occurred.
3125 *
3126 * @static
3127 * @method isRepeated
3128 * @param {String} keyName The mapped name of the key
3129 * @return {Boolean} True if the key is repeated
3130 */
3131Input.isRepeated = function(keyName) {
3132 if (this._isEscapeCompatible(keyName) && this.isRepeated('escape')) {
3133 return true;
3134 } else {
3135 return (this._latestButton === keyName &&
3136 (this._pressedTime === 0 ||
3137 (this._pressedTime >= this.keyRepeatWait &&
3138 this._pressedTime % this.keyRepeatInterval === 0)));
3139 }
3140};
3141
3142/**
3143 * Checks whether a key is kept depressed.
3144 *
3145 * @static
3146 * @method isLongPressed
3147 * @param {String} keyName The mapped name of the key
3148 * @return {Boolean} True if the key is long-pressed
3149 */
3150Input.isLongPressed = function(keyName) {
3151 if (this._isEscapeCompatible(keyName) && this.isLongPressed('escape')) {
3152 return true;
3153 } else {
3154 return (this._latestButton === keyName &&
3155 this._pressedTime >= this.keyRepeatWait);
3156 }
3157};
3158
3159/**
3160 * [read-only] The four direction value as a number of the numpad, or 0 for neutral.
3161 *
3162 * @static
3163 * @property dir4
3164 * @type Number
3165 */
3166Object.defineProperty(Input, 'dir4', {
3167 get: function() {
3168 return this._dir4;
3169 },
3170 configurable: true
3171});
3172
3173/**
3174 * [read-only] The eight direction value as a number of the numpad, or 0 for neutral.
3175 *
3176 * @static
3177 * @property dir8
3178 * @type Number
3179 */
3180Object.defineProperty(Input, 'dir8', {
3181 get: function() {
3182 return this._dir8;
3183 },
3184 configurable: true
3185});
3186
3187/**
3188 * [read-only] The time of the last input in milliseconds.
3189 *
3190 * @static
3191 * @property date
3192 * @type Number
3193 */
3194Object.defineProperty(Input, 'date', {
3195 get: function() {
3196 return this._date;
3197 },
3198 configurable: true
3199});
3200
3201/**
3202 * @static
3203 * @method _wrapNwjsAlert
3204 * @private
3205 */
3206Input._wrapNwjsAlert = function() {
3207 if (Utils.isNwjs()) {
3208 var _alert = window.alert;
3209 window.alert = function() {
3210 var gui = require('nw.gui');
3211 var win = gui.Window.get();
3212 _alert.apply(this, arguments);
3213 win.focus();
3214 Input.clear();
3215 };
3216 }
3217};
3218
3219/**
3220 * @static
3221 * @method _setupEventHandlers
3222 * @private
3223 */
3224Input._setupEventHandlers = function() {
3225 document.addEventListener('keydown', this._onKeyDown.bind(this));
3226 document.addEventListener('keyup', this._onKeyUp.bind(this));
3227 window.addEventListener('blur', this._onLostFocus.bind(this));
3228};
3229
3230/**
3231 * @static
3232 * @method _onKeyDown
3233 * @param {KeyboardEvent} event
3234 * @private
3235 */
3236Input._onKeyDown = function(event) {
3237 if (this._shouldPreventDefault(event.keyCode)) {
3238 event.preventDefault();
3239 }
3240 if (event.keyCode === 144) { // Numlock
3241 this.clear();
3242 }
3243 var buttonName = this.keyMapper[event.keyCode];
3244 if (ResourceHandler.exists() && buttonName === 'ok') {
3245 ResourceHandler.retry();
3246 } else if (buttonName) {
3247 this._currentState[buttonName] = true;
3248 }
3249};
3250
3251/**
3252 * @static
3253 * @method _shouldPreventDefault
3254 * @param {Number} keyCode
3255 * @private
3256 */
3257Input._shouldPreventDefault = function(keyCode) {
3258 switch (keyCode) {
3259 case 8: // backspace
3260 case 33: // pageup
3261 case 34: // pagedown
3262 case 37: // left arrow
3263 case 38: // up arrow
3264 case 39: // right arrow
3265 case 40: // down arrow
3266 return true;
3267 }
3268 return false;
3269};
3270
3271/**
3272 * @static
3273 * @method _onKeyUp
3274 * @param {KeyboardEvent} event
3275 * @private
3276 */
3277Input._onKeyUp = function(event) {
3278 var buttonName = this.keyMapper[event.keyCode];
3279 if (buttonName) {
3280 this._currentState[buttonName] = false;
3281 }
3282 if (event.keyCode === 0) { // For QtWebEngine on OS X
3283 this.clear();
3284 }
3285};
3286
3287/**
3288 * @static
3289 * @method _onLostFocus
3290 * @private
3291 */
3292Input._onLostFocus = function() {
3293 this.clear();
3294};
3295
3296/**
3297 * @static
3298 * @method _pollGamepads
3299 * @private
3300 */
3301Input._pollGamepads = function() {
3302 if (navigator.getGamepads) {
3303 var gamepads = navigator.getGamepads();
3304 if (gamepads) {
3305 for (var i = 0; i < gamepads.length; i++) {
3306 var gamepad = gamepads[i];
3307 if (gamepad && gamepad.connected) {
3308 this._updateGamepadState(gamepad);
3309 }
3310 }
3311 }
3312 }
3313};
3314
3315/**
3316 * @static
3317 * @method _updateGamepadState
3318 * @param {Gamepad} gamepad
3319 * @param {Number} index
3320 * @private
3321 */
3322Input._updateGamepadState = function(gamepad) {
3323 var lastState = this._gamepadStates[gamepad.index] || [];
3324 var newState = [];
3325 var buttons = gamepad.buttons;
3326 var axes = gamepad.axes;
3327 var threshold = 0.5;
3328 newState[12] = false;
3329 newState[13] = false;
3330 newState[14] = false;
3331 newState[15] = false;
3332 for (var i = 0; i < buttons.length; i++) {
3333 newState[i] = buttons[i].pressed;
3334 }
3335 if (axes[1] < -threshold) {
3336 newState[12] = true; // up
3337 } else if (axes[1] > threshold) {
3338 newState[13] = true; // down
3339 }
3340 if (axes[0] < -threshold) {
3341 newState[14] = true; // left
3342 } else if (axes[0] > threshold) {
3343 newState[15] = true; // right
3344 }
3345 for (var j = 0; j < newState.length; j++) {
3346 if (newState[j] !== lastState[j]) {
3347 var buttonName = this.gamepadMapper[j];
3348 if (buttonName) {
3349 this._currentState[buttonName] = newState[j];
3350 }
3351 }
3352 }
3353 this._gamepadStates[gamepad.index] = newState;
3354};
3355
3356/**
3357 * @static
3358 * @method _updateDirection
3359 * @private
3360 */
3361Input._updateDirection = function() {
3362 var x = this._signX();
3363 var y = this._signY();
3364
3365 this._dir8 = this._makeNumpadDirection(x, y);
3366
3367 if (x !== 0 && y !== 0) {
3368 if (this._preferredAxis === 'x') {
3369 y = 0;
3370 } else {
3371 x = 0;
3372 }
3373 } else if (x !== 0) {
3374 this._preferredAxis = 'y';
3375 } else if (y !== 0) {
3376 this._preferredAxis = 'x';
3377 }
3378
3379 this._dir4 = this._makeNumpadDirection(x, y);
3380};
3381
3382/**
3383 * @static
3384 * @method _signX
3385 * @private
3386 */
3387Input._signX = function() {
3388 var x = 0;
3389
3390 if (this.isPressed('left')) {
3391 x--;
3392 }
3393 if (this.isPressed('right')) {
3394 x++;
3395 }
3396 return x;
3397};
3398
3399/**
3400 * @static
3401 * @method _signY
3402 * @private
3403 */
3404Input._signY = function() {
3405 var y = 0;
3406
3407 if (this.isPressed('up')) {
3408 y--;
3409 }
3410 if (this.isPressed('down')) {
3411 y++;
3412 }
3413 return y;
3414};
3415
3416/**
3417 * @static
3418 * @method _makeNumpadDirection
3419 * @param {Number} x
3420 * @param {Number} y
3421 * @return {Number}
3422 * @private
3423 */
3424Input._makeNumpadDirection = function(x, y) {
3425 if (x !== 0 || y !== 0) {
3426 return 5 - y * 3 + x;
3427 }
3428 return 0;
3429};
3430
3431/**
3432 * @static
3433 * @method _isEscapeCompatible
3434 * @param {String} keyName
3435 * @return {Boolean}
3436 * @private
3437 */
3438Input._isEscapeCompatible = function(keyName) {
3439 return keyName === 'cancel' || keyName === 'menu';
3440};
3441
3442//-----------------------------------------------------------------------------
3443/**
3444 * The static class that handles input data from the mouse and touchscreen.
3445 *
3446 * @class TouchInput
3447 */
3448function TouchInput() {
3449 throw new Error('This is a static class');
3450}
3451
3452/**
3453 * Initializes the touch system.
3454 *
3455 * @static
3456 * @method initialize
3457 */
3458TouchInput.initialize = function() {
3459 this.clear();
3460 this._setupEventHandlers();
3461};
3462
3463/**
3464 * The wait time of the pseudo key repeat in frames.
3465 *
3466 * @static
3467 * @property keyRepeatWait
3468 * @type Number
3469 */
3470TouchInput.keyRepeatWait = 24;
3471
3472/**
3473 * The interval of the pseudo key repeat in frames.
3474 *
3475 * @static
3476 * @property keyRepeatInterval
3477 * @type Number
3478 */
3479TouchInput.keyRepeatInterval = 6;
3480
3481/**
3482 * Clears all the touch data.
3483 *
3484 * @static
3485 * @method clear
3486 */
3487TouchInput.clear = function() {
3488 this._mousePressed = false;
3489 this._screenPressed = false;
3490 this._pressedTime = 0;
3491 this._events = {};
3492 this._events.triggered = false;
3493 this._events.cancelled = false;
3494 this._events.moved = false;
3495 this._events.released = false;
3496 this._events.wheelX = 0;
3497 this._events.wheelY = 0;
3498 this._triggered = false;
3499 this._cancelled = false;
3500 this._moved = false;
3501 this._released = false;
3502 this._wheelX = 0;
3503 this._wheelY = 0;
3504 this._x = 0;
3505 this._y = 0;
3506 this._date = 0;
3507};
3508
3509/**
3510 * Updates the touch data.
3511 *
3512 * @static
3513 * @method update
3514 */
3515TouchInput.update = function() {
3516 this._triggered = this._events.triggered;
3517 this._cancelled = this._events.cancelled;
3518 this._moved = this._events.moved;
3519 this._released = this._events.released;
3520 this._wheelX = this._events.wheelX;
3521 this._wheelY = this._events.wheelY;
3522 this._events.triggered = false;
3523 this._events.cancelled = false;
3524 this._events.moved = false;
3525 this._events.released = false;
3526 this._events.wheelX = 0;
3527 this._events.wheelY = 0;
3528 if (this.isPressed()) {
3529 this._pressedTime++;
3530 }
3531};
3532
3533/**
3534 * Checks whether the mouse button or touchscreen is currently pressed down.
3535 *
3536 * @static
3537 * @method isPressed
3538 * @return {Boolean} True if the mouse button or touchscreen is pressed
3539 */
3540TouchInput.isPressed = function() {
3541 return this._mousePressed || this._screenPressed;
3542};
3543
3544/**
3545 * Checks whether the left mouse button or touchscreen is just pressed.
3546 *
3547 * @static
3548 * @method isTriggered
3549 * @return {Boolean} True if the mouse button or touchscreen is triggered
3550 */
3551TouchInput.isTriggered = function() {
3552 return this._triggered;
3553};
3554
3555/**
3556 * Checks whether the left mouse button or touchscreen is just pressed
3557 * or a pseudo key repeat occurred.
3558 *
3559 * @static
3560 * @method isRepeated
3561 * @return {Boolean} True if the mouse button or touchscreen is repeated
3562 */
3563TouchInput.isRepeated = function() {
3564 return (this.isPressed() &&
3565 (this._triggered ||
3566 (this._pressedTime >= this.keyRepeatWait &&
3567 this._pressedTime % this.keyRepeatInterval === 0)));
3568};
3569
3570/**
3571 * Checks whether the left mouse button or touchscreen is kept depressed.
3572 *
3573 * @static
3574 * @method isLongPressed
3575 * @return {Boolean} True if the left mouse button or touchscreen is long-pressed
3576 */
3577TouchInput.isLongPressed = function() {
3578 return this.isPressed() && this._pressedTime >= this.keyRepeatWait;
3579};
3580
3581/**
3582 * Checks whether the right mouse button is just pressed.
3583 *
3584 * @static
3585 * @method isCancelled
3586 * @return {Boolean} True if the right mouse button is just pressed
3587 */
3588TouchInput.isCancelled = function() {
3589 return this._cancelled;
3590};
3591
3592/**
3593 * Checks whether the mouse or a finger on the touchscreen is moved.
3594 *
3595 * @static
3596 * @method isMoved
3597 * @return {Boolean} True if the mouse or a finger on the touchscreen is moved
3598 */
3599TouchInput.isMoved = function() {
3600 return this._moved;
3601};
3602
3603/**
3604 * Checks whether the left mouse button or touchscreen is released.
3605 *
3606 * @static
3607 * @method isReleased
3608 * @return {Boolean} True if the mouse button or touchscreen is released
3609 */
3610TouchInput.isReleased = function() {
3611 return this._released;
3612};
3613
3614/**
3615 * [read-only] The horizontal scroll amount.
3616 *
3617 * @static
3618 * @property wheelX
3619 * @type Number
3620 */
3621Object.defineProperty(TouchInput, 'wheelX', {
3622 get: function() {
3623 return this._wheelX;
3624 },
3625 configurable: true
3626});
3627
3628/**
3629 * [read-only] The vertical scroll amount.
3630 *
3631 * @static
3632 * @property wheelY
3633 * @type Number
3634 */
3635Object.defineProperty(TouchInput, 'wheelY', {
3636 get: function() {
3637 return this._wheelY;
3638 },
3639 configurable: true
3640});
3641
3642/**
3643 * [read-only] The x coordinate on the canvas area of the latest touch event.
3644 *
3645 * @static
3646 * @property x
3647 * @type Number
3648 */
3649Object.defineProperty(TouchInput, 'x', {
3650 get: function() {
3651 return this._x;
3652 },
3653 configurable: true
3654});
3655
3656/**
3657 * [read-only] The y coordinate on the canvas area of the latest touch event.
3658 *
3659 * @static
3660 * @property y
3661 * @type Number
3662 */
3663Object.defineProperty(TouchInput, 'y', {
3664 get: function() {
3665 return this._y;
3666 },
3667 configurable: true
3668});
3669
3670/**
3671 * [read-only] The time of the last input in milliseconds.
3672 *
3673 * @static
3674 * @property date
3675 * @type Number
3676 */
3677Object.defineProperty(TouchInput, 'date', {
3678 get: function() {
3679 return this._date;
3680 },
3681 configurable: true
3682});
3683
3684/**
3685 * @static
3686 * @method _setupEventHandlers
3687 * @private
3688 */
3689TouchInput._setupEventHandlers = function() {
3690 var isSupportPassive = Utils.isSupportPassiveEvent();
3691 document.addEventListener('mousedown', this._onMouseDown.bind(this));
3692 document.addEventListener('mousemove', this._onMouseMove.bind(this));
3693 document.addEventListener('mouseup', this._onMouseUp.bind(this));
3694 document.addEventListener('wheel', this._onWheel.bind(this));
3695 document.addEventListener('touchstart', this._onTouchStart.bind(this), isSupportPassive ? {passive: false} : false);
3696 document.addEventListener('touchmove', this._onTouchMove.bind(this), isSupportPassive ? {passive: false} : false);
3697 document.addEventListener('touchend', this._onTouchEnd.bind(this));
3698 document.addEventListener('touchcancel', this._onTouchCancel.bind(this));
3699 document.addEventListener('pointerdown', this._onPointerDown.bind(this));
3700};
3701
3702/**
3703 * @static
3704 * @method _onMouseDown
3705 * @param {MouseEvent} event
3706 * @private
3707 */
3708TouchInput._onMouseDown = function(event) {
3709 if (event.button === 0) {
3710 this._onLeftButtonDown(event);
3711 } else if (event.button === 1) {
3712 this._onMiddleButtonDown(event);
3713 } else if (event.button === 2) {
3714 this._onRightButtonDown(event);
3715 }
3716};
3717
3718/**
3719 * @static
3720 * @method _onLeftButtonDown
3721 * @param {MouseEvent} event
3722 * @private
3723 */
3724TouchInput._onLeftButtonDown = function(event) {
3725 var x = Graphics.pageToCanvasX(event.pageX);
3726 var y = Graphics.pageToCanvasY(event.pageY);
3727 if (Graphics.isInsideCanvas(x, y)) {
3728 this._mousePressed = true;
3729 this._pressedTime = 0;
3730 this._onTrigger(x, y);
3731 }
3732};
3733
3734/**
3735 * @static
3736 * @method _onMiddleButtonDown
3737 * @param {MouseEvent} event
3738 * @private
3739 */
3740TouchInput._onMiddleButtonDown = function(event) {
3741};
3742
3743/**
3744 * @static
3745 * @method _onRightButtonDown
3746 * @param {MouseEvent} event
3747 * @private
3748 */
3749TouchInput._onRightButtonDown = function(event) {
3750 var x = Graphics.pageToCanvasX(event.pageX);
3751 var y = Graphics.pageToCanvasY(event.pageY);
3752 if (Graphics.isInsideCanvas(x, y)) {
3753 this._onCancel(x, y);
3754 }
3755};
3756
3757/**
3758 * @static
3759 * @method _onMouseMove
3760 * @param {MouseEvent} event
3761 * @private
3762 */
3763TouchInput._onMouseMove = function(event) {
3764 if (this._mousePressed) {
3765 var x = Graphics.pageToCanvasX(event.pageX);
3766 var y = Graphics.pageToCanvasY(event.pageY);
3767 this._onMove(x, y);
3768 }
3769};
3770
3771/**
3772 * @static
3773 * @method _onMouseUp
3774 * @param {MouseEvent} event
3775 * @private
3776 */
3777TouchInput._onMouseUp = function(event) {
3778 if (event.button === 0) {
3779 var x = Graphics.pageToCanvasX(event.pageX);
3780 var y = Graphics.pageToCanvasY(event.pageY);
3781 this._mousePressed = false;
3782 this._onRelease(x, y);
3783 }
3784};
3785
3786/**
3787 * @static
3788 * @method _onWheel
3789 * @param {WheelEvent} event
3790 * @private
3791 */
3792TouchInput._onWheel = function(event) {
3793 this._events.wheelX += event.deltaX;
3794 this._events.wheelY += event.deltaY;
3795 event.preventDefault();
3796};
3797
3798/**
3799 * @static
3800 * @method _onTouchStart
3801 * @param {TouchEvent} event
3802 * @private
3803 */
3804TouchInput._onTouchStart = function(event) {
3805 for (var i = 0; i < event.changedTouches.length; i++) {
3806 var touch = event.changedTouches[i];
3807 var x = Graphics.pageToCanvasX(touch.pageX);
3808 var y = Graphics.pageToCanvasY(touch.pageY);
3809 if (Graphics.isInsideCanvas(x, y)) {
3810 this._screenPressed = true;
3811 this._pressedTime = 0;
3812 if (event.touches.length >= 2) {
3813 this._onCancel(x, y);
3814 } else {
3815 this._onTrigger(x, y);
3816 }
3817 event.preventDefault();
3818 }
3819 }
3820 if (window.cordova || window.navigator.standalone) {
3821 event.preventDefault();
3822 }
3823};
3824
3825/**
3826 * @static
3827 * @method _onTouchMove
3828 * @param {TouchEvent} event
3829 * @private
3830 */
3831TouchInput._onTouchMove = function(event) {
3832 for (var i = 0; i < event.changedTouches.length; i++) {
3833 var touch = event.changedTouches[i];
3834 var x = Graphics.pageToCanvasX(touch.pageX);
3835 var y = Graphics.pageToCanvasY(touch.pageY);
3836 this._onMove(x, y);
3837 }
3838};
3839
3840/**
3841 * @static
3842 * @method _onTouchEnd
3843 * @param {TouchEvent} event
3844 * @private
3845 */
3846TouchInput._onTouchEnd = function(event) {
3847 for (var i = 0; i < event.changedTouches.length; i++) {
3848 var touch = event.changedTouches[i];
3849 var x = Graphics.pageToCanvasX(touch.pageX);
3850 var y = Graphics.pageToCanvasY(touch.pageY);
3851 this._screenPressed = false;
3852 this._onRelease(x, y);
3853 }
3854};
3855
3856/**
3857 * @static
3858 * @method _onTouchCancel
3859 * @param {TouchEvent} event
3860 * @private
3861 */
3862TouchInput._onTouchCancel = function(event) {
3863 this._screenPressed = false;
3864};
3865
3866/**
3867 * @static
3868 * @method _onPointerDown
3869 * @param {PointerEvent} event
3870 * @private
3871 */
3872TouchInput._onPointerDown = function(event) {
3873 if (event.pointerType === 'touch' && !event.isPrimary) {
3874 var x = Graphics.pageToCanvasX(event.pageX);
3875 var y = Graphics.pageToCanvasY(event.pageY);
3876 if (Graphics.isInsideCanvas(x, y)) {
3877 // For Microsoft Edge
3878 this._onCancel(x, y);
3879 event.preventDefault();
3880 }
3881 }
3882};
3883
3884/**
3885 * @static
3886 * @method _onTrigger
3887 * @param {Number} x
3888 * @param {Number} y
3889 * @private
3890 */
3891TouchInput._onTrigger = function(x, y) {
3892 this._events.triggered = true;
3893 this._x = x;
3894 this._y = y;
3895 this._date = Date.now();
3896};
3897
3898/**
3899 * @static
3900 * @method _onCancel
3901 * @param {Number} x
3902 * @param {Number} y
3903 * @private
3904 */
3905TouchInput._onCancel = function(x, y) {
3906 this._events.cancelled = true;
3907 this._x = x;
3908 this._y = y;
3909};
3910
3911/**
3912 * @static
3913 * @method _onMove
3914 * @param {Number} x
3915 * @param {Number} y
3916 * @private
3917 */
3918TouchInput._onMove = function(x, y) {
3919 this._events.moved = true;
3920 this._x = x;
3921 this._y = y;
3922};
3923
3924/**
3925 * @static
3926 * @method _onRelease
3927 * @param {Number} x
3928 * @param {Number} y
3929 * @private
3930 */
3931TouchInput._onRelease = function(x, y) {
3932 this._events.released = true;
3933 this._x = x;
3934 this._y = y;
3935};
3936
3937//-----------------------------------------------------------------------------
3938/**
3939 * The basic object that is rendered to the game screen.
3940 *
3941 * @class Sprite
3942 * @constructor
3943 * @param {Bitmap} bitmap The image for the sprite
3944 */
3945function Sprite() {
3946 this.initialize.apply(this, arguments);
3947}
3948
3949Sprite.prototype = Object.create(PIXI.Sprite.prototype);
3950Sprite.prototype.constructor = Sprite;
3951
3952Sprite.voidFilter = new PIXI.filters.VoidFilter();
3953
3954Sprite.prototype.initialize = function(bitmap) {
3955 var texture = new PIXI.Texture(new PIXI.BaseTexture());
3956
3957 PIXI.Sprite.call(this, texture);
3958
3959 this._bitmap = null;
3960 this._frame = new Rectangle();
3961 this._realFrame = new Rectangle();
3962 this._blendColor = [0, 0, 0, 0];
3963 this._colorTone = [0, 0, 0, 0];
3964 this._canvas = null;
3965 this._context = null;
3966 this._tintTexture = null;
3967
3968 /**
3969 * use heavy renderer that will reduce border artifacts and apply advanced blendModes
3970 * @type {boolean}
3971 * @private
3972 */
3973 this._isPicture = false;
3974
3975 this.spriteId = Sprite._counter++;
3976 this.opaque = false;
3977
3978 this.bitmap = bitmap;
3979};
3980
3981// Number of the created objects.
3982Sprite._counter = 0;
3983
3984/**
3985 * The image for the sprite.
3986 *
3987 * @property bitmap
3988 * @type Bitmap
3989 */
3990Object.defineProperty(Sprite.prototype, 'bitmap', {
3991 get: function() {
3992 return this._bitmap;
3993 },
3994 set: function(value) {
3995 if (this._bitmap !== value) {
3996 this._bitmap = value;
3997
3998 if(value){
3999 this._refreshFrame = true;
4000 value.addLoadListener(this._onBitmapLoad.bind(this));
4001 }else{
4002 this._refreshFrame = false;
4003 this.texture.frame = Rectangle.emptyRectangle;
4004 }
4005 }
4006 },
4007 configurable: true
4008});
4009
4010/**
4011 * The width of the sprite without the scale.
4012 *
4013 * @property width
4014 * @type Number
4015 */
4016Object.defineProperty(Sprite.prototype, 'width', {
4017 get: function() {
4018 return this._frame.width;
4019 },
4020 set: function(value) {
4021 this._frame.width = value;
4022 this._refresh();
4023 },
4024 configurable: true
4025});
4026
4027/**
4028 * The height of the sprite without the scale.
4029 *
4030 * @property height
4031 * @type Number
4032 */
4033Object.defineProperty(Sprite.prototype, 'height', {
4034 get: function() {
4035 return this._frame.height;
4036 },
4037 set: function(value) {
4038 this._frame.height = value;
4039 this._refresh();
4040 },
4041 configurable: true
4042});
4043
4044/**
4045 * The opacity of the sprite (0 to 255).
4046 *
4047 * @property opacity
4048 * @type Number
4049 */
4050Object.defineProperty(Sprite.prototype, 'opacity', {
4051 get: function() {
4052 return this.alpha * 255;
4053 },
4054 set: function(value) {
4055 this.alpha = value.clamp(0, 255) / 255;
4056 },
4057 configurable: true
4058});
4059
4060/**
4061 * Updates the sprite for each frame.
4062 *
4063 * @method update
4064 */
4065Sprite.prototype.update = function() {
4066 this.children.forEach(function(child) {
4067 if (child.update) {
4068 child.update();
4069 }
4070 });
4071};
4072
4073/**
4074 * Sets the x and y at once.
4075 *
4076 * @method move
4077 * @param {Number} x The x coordinate of the sprite
4078 * @param {Number} y The y coordinate of the sprite
4079 */
4080Sprite.prototype.move = function(x, y) {
4081 this.x = x;
4082 this.y = y;
4083};
4084
4085/**
4086 * Sets the rectagle of the bitmap that the sprite displays.
4087 *
4088 * @method setFrame
4089 * @param {Number} x The x coordinate of the frame
4090 * @param {Number} y The y coordinate of the frame
4091 * @param {Number} width The width of the frame
4092 * @param {Number} height The height of the frame
4093 */
4094Sprite.prototype.setFrame = function(x, y, width, height) {
4095 this._refreshFrame = false;
4096 var frame = this._frame;
4097 if (x !== frame.x || y !== frame.y ||
4098 width !== frame.width || height !== frame.height) {
4099 frame.x = x;
4100 frame.y = y;
4101 frame.width = width;
4102 frame.height = height;
4103 this._refresh();
4104 }
4105};
4106
4107/**
4108 * Gets the blend color for the sprite.
4109 *
4110 * @method getBlendColor
4111 * @return {Array} The blend color [r, g, b, a]
4112 */
4113Sprite.prototype.getBlendColor = function() {
4114 return this._blendColor.clone();
4115};
4116
4117/**
4118 * Sets the blend color for the sprite.
4119 *
4120 * @method setBlendColor
4121 * @param {Array} color The blend color [r, g, b, a]
4122 */
4123Sprite.prototype.setBlendColor = function(color) {
4124 if (!(color instanceof Array)) {
4125 throw new Error('Argument must be an array');
4126 }
4127 if (!this._blendColor.equals(color)) {
4128 this._blendColor = color.clone();
4129 this._refresh();
4130 }
4131};
4132
4133/**
4134 * Gets the color tone for the sprite.
4135 *
4136 * @method getColorTone
4137 * @return {Array} The color tone [r, g, b, gray]
4138 */
4139Sprite.prototype.getColorTone = function() {
4140 return this._colorTone.clone();
4141};
4142
4143/**
4144 * Sets the color tone for the sprite.
4145 *
4146 * @method setColorTone
4147 * @param {Array} tone The color tone [r, g, b, gray]
4148 */
4149Sprite.prototype.setColorTone = function(tone) {
4150 if (!(tone instanceof Array)) {
4151 throw new Error('Argument must be an array');
4152 }
4153 if (!this._colorTone.equals(tone)) {
4154 this._colorTone = tone.clone();
4155 this._refresh();
4156 }
4157};
4158
4159/**
4160 * @method _onBitmapLoad
4161 * @private
4162 */
4163Sprite.prototype._onBitmapLoad = function(bitmapLoaded) {
4164 if(bitmapLoaded === this._bitmap){
4165 if (this._refreshFrame && this._bitmap) {
4166 this._refreshFrame = false;
4167 this._frame.width = this._bitmap.width;
4168 this._frame.height = this._bitmap.height;
4169 }
4170 }
4171
4172 this._refresh();
4173};
4174
4175/**
4176 * @method _refresh
4177 * @private
4178 */
4179Sprite.prototype._refresh = function() {
4180 var frameX = Math.floor(this._frame.x);
4181 var frameY = Math.floor(this._frame.y);
4182 var frameW = Math.floor(this._frame.width);
4183 var frameH = Math.floor(this._frame.height);
4184 var bitmapW = this._bitmap ? this._bitmap.width : 0;
4185 var bitmapH = this._bitmap ? this._bitmap.height : 0;
4186 var realX = frameX.clamp(0, bitmapW);
4187 var realY = frameY.clamp(0, bitmapH);
4188 var realW = (frameW - realX + frameX).clamp(0, bitmapW - realX);
4189 var realH = (frameH - realY + frameY).clamp(0, bitmapH - realY);
4190
4191 this._realFrame.x = realX;
4192 this._realFrame.y = realY;
4193 this._realFrame.width = realW;
4194 this._realFrame.height = realH;
4195 this.pivot.x = frameX - realX;
4196 this.pivot.y = frameY - realY;
4197
4198 if (realW > 0 && realH > 0) {
4199 if (this._needsTint()) {
4200 this._createTinter(realW, realH);
4201 this._executeTint(realX, realY, realW, realH);
4202 this._tintTexture.update();
4203 this.texture.baseTexture = this._tintTexture;
4204 this.texture.frame = new Rectangle(0, 0, realW, realH);
4205 } else {
4206 if (this._bitmap) {
4207 this.texture.baseTexture = this._bitmap.baseTexture;
4208 }
4209 this.texture.frame = this._realFrame;
4210 }
4211 } else if (this._bitmap) {
4212 this.texture.frame = Rectangle.emptyRectangle;
4213 } else {
4214 this.texture.baseTexture.width = Math.max(this.texture.baseTexture.width, this._frame.x + this._frame.width);
4215 this.texture.baseTexture.height = Math.max(this.texture.baseTexture.height, this._frame.y + this._frame.height);
4216 this.texture.frame = this._frame;
4217 }
4218 this.texture._updateID++;
4219};
4220
4221/**
4222 * @method _isInBitmapRect
4223 * @param {Number} x
4224 * @param {Number} y
4225 * @param {Number} w
4226 * @param {Number} h
4227 * @return {Boolean}
4228 * @private
4229 */
4230Sprite.prototype._isInBitmapRect = function(x, y, w, h) {
4231 return (this._bitmap && x + w > 0 && y + h > 0 &&
4232 x < this._bitmap.width && y < this._bitmap.height);
4233};
4234
4235/**
4236 * @method _needsTint
4237 * @return {Boolean}
4238 * @private
4239 */
4240Sprite.prototype._needsTint = function() {
4241 var tone = this._colorTone;
4242 return tone[0] || tone[1] || tone[2] || tone[3] || this._blendColor[3] > 0;
4243};
4244
4245/**
4246 * @method _createTinter
4247 * @param {Number} w
4248 * @param {Number} h
4249 * @private
4250 */
4251Sprite.prototype._createTinter = function(w, h) {
4252 if (!this._canvas) {
4253 this._canvas = document.createElement('canvas');
4254 this._context = this._canvas.getContext('2d');
4255 }
4256
4257 this._canvas.width = w;
4258 this._canvas.height = h;
4259
4260 if (!this._tintTexture) {
4261 this._tintTexture = new PIXI.BaseTexture(this._canvas);
4262 }
4263
4264 this._tintTexture.width = w;
4265 this._tintTexture.height = h;
4266 this._tintTexture.scaleMode = this._bitmap.baseTexture.scaleMode;
4267};
4268
4269/**
4270 * @method _executeTint
4271 * @param {Number} x
4272 * @param {Number} y
4273 * @param {Number} w
4274 * @param {Number} h
4275 * @private
4276 */
4277Sprite.prototype._executeTint = function(x, y, w, h) {
4278 var context = this._context;
4279 var tone = this._colorTone;
4280 var color = this._blendColor;
4281
4282 context.globalCompositeOperation = 'copy';
4283 context.drawImage(this._bitmap.canvas, x, y, w, h, 0, 0, w, h);
4284
4285 if (Graphics.canUseSaturationBlend()) {
4286 var gray = Math.max(0, tone[3]);
4287 context.globalCompositeOperation = 'saturation';
4288 context.fillStyle = 'rgba(255,255,255,' + gray / 255 + ')';
4289 context.fillRect(0, 0, w, h);
4290 }
4291
4292 var r1 = Math.max(0, tone[0]);
4293 var g1 = Math.max(0, tone[1]);
4294 var b1 = Math.max(0, tone[2]);
4295 context.globalCompositeOperation = 'lighter';
4296 context.fillStyle = Utils.rgbToCssColor(r1, g1, b1);
4297 context.fillRect(0, 0, w, h);
4298
4299 if (Graphics.canUseDifferenceBlend()) {
4300 context.globalCompositeOperation = 'difference';
4301 context.fillStyle = 'white';
4302 context.fillRect(0, 0, w, h);
4303
4304 var r2 = Math.max(0, -tone[0]);
4305 var g2 = Math.max(0, -tone[1]);
4306 var b2 = Math.max(0, -tone[2]);
4307 context.globalCompositeOperation = 'lighter';
4308 context.fillStyle = Utils.rgbToCssColor(r2, g2, b2);
4309 context.fillRect(0, 0, w, h);
4310
4311 context.globalCompositeOperation = 'difference';
4312 context.fillStyle = 'white';
4313 context.fillRect(0, 0, w, h);
4314 }
4315
4316 var r3 = Math.max(0, color[0]);
4317 var g3 = Math.max(0, color[1]);
4318 var b3 = Math.max(0, color[2]);
4319 var a3 = Math.max(0, color[3]);
4320 context.globalCompositeOperation = 'source-atop';
4321 context.fillStyle = Utils.rgbToCssColor(r3, g3, b3);
4322 context.globalAlpha = a3 / 255;
4323 context.fillRect(0, 0, w, h);
4324
4325 context.globalCompositeOperation = 'destination-in';
4326 context.globalAlpha = 1;
4327 context.drawImage(this._bitmap.canvas, x, y, w, h, 0, 0, w, h);
4328};
4329
4330Sprite.prototype._renderCanvas_PIXI = PIXI.Sprite.prototype._renderCanvas;
4331Sprite.prototype._renderWebGL_PIXI = PIXI.Sprite.prototype._renderWebGL;
4332
4333/**
4334 * @method _renderCanvas
4335 * @param {Object} renderer
4336 * @private
4337 */
4338Sprite.prototype._renderCanvas = function(renderer) {
4339 if (this.bitmap) {
4340 this.bitmap.touch();
4341 }
4342 if(this.bitmap && !this.bitmap.isReady()){
4343 return;
4344 }
4345
4346 if (this.texture.frame.width > 0 && this.texture.frame.height > 0) {
4347 this._renderCanvas_PIXI(renderer);
4348 }
4349};
4350
4351/**
4352 * checks if we need to speed up custom blendmodes
4353 * @param renderer
4354 * @private
4355 */
4356Sprite.prototype._speedUpCustomBlendModes = function(renderer) {
4357 var picture = renderer.plugins.picture;
4358 var blend = this.blendMode;
4359 if (renderer.renderingToScreen && renderer._activeRenderTarget.root) {
4360 if (picture.drawModes[blend]) {
4361 var stage = renderer._lastObjectRendered;
4362 var f = stage._filters;
4363 if (!f || !f[0]) {
4364 setTimeout(function () {
4365 var f = stage._filters;
4366 if (!f || !f[0]) {
4367 stage.filters = [Sprite.voidFilter];
4368 stage.filterArea = new PIXI.Rectangle(0, 0, Graphics.width, Graphics.height);
4369 }
4370 }, 0);
4371 }
4372 }
4373 }
4374};
4375
4376/**
4377 * @method _renderWebGL
4378 * @param {Object} renderer
4379 * @private
4380 */
4381Sprite.prototype._renderWebGL = function(renderer) {
4382 if (this.bitmap) {
4383 this.bitmap.touch();
4384 }
4385 if(this.bitmap && !this.bitmap.isReady()){
4386 return;
4387 }
4388 if (this.texture.frame.width > 0 && this.texture.frame.height > 0) {
4389 if (this._bitmap) {
4390 this._bitmap.checkDirty();
4391 }
4392
4393 //copy of pixi-v4 internal code
4394 this.calculateVertices();
4395
4396 if (this.pluginName === 'sprite' && this._isPicture) {
4397 // use heavy renderer, which reduces artifacts and applies corrent blendMode,
4398 // but does not use multitexture optimization
4399 this._speedUpCustomBlendModes(renderer);
4400 renderer.setObjectRenderer(renderer.plugins.picture);
4401 renderer.plugins.picture.render(this);
4402 } else {
4403 // use pixi super-speed renderer
4404 renderer.setObjectRenderer(renderer.plugins[this.pluginName]);
4405 renderer.plugins[this.pluginName].render(this);
4406 }
4407 }
4408};
4409
4410// The important members from Pixi.js
4411
4412/**
4413 * The visibility of the sprite.
4414 *
4415 * @property visible
4416 * @type Boolean
4417 */
4418
4419/**
4420 * The x coordinate of the sprite.
4421 *
4422 * @property x
4423 * @type Number
4424 */
4425
4426/**
4427 * The y coordinate of the sprite.
4428 *
4429 * @property y
4430 * @type Number
4431 */
4432
4433/**
4434 * The origin point of the sprite. (0,0) to (1,1).
4435 *
4436 * @property anchor
4437 * @type Point
4438 */
4439
4440/**
4441 * The scale factor of the sprite.
4442 *
4443 * @property scale
4444 * @type Point
4445 */
4446
4447/**
4448 * The rotation of the sprite in radians.
4449 *
4450 * @property rotation
4451 * @type Number
4452 */
4453
4454/**
4455 * The blend mode to be applied to the sprite.
4456 *
4457 * @property blendMode
4458 * @type Number
4459 */
4460
4461/**
4462 * Sets the filters for the sprite.
4463 *
4464 * @property filters
4465 * @type Array
4466 */
4467
4468/**
4469 * [read-only] The array of children of the sprite.
4470 *
4471 * @property children
4472 * @type Array
4473 */
4474
4475/**
4476 * [read-only] The object that contains the sprite.
4477 *
4478 * @property parent
4479 * @type Object
4480 */
4481
4482/**
4483 * Adds a child to the container.
4484 *
4485 * @method addChild
4486 * @param {Object} child The child to add
4487 * @return {Object} The child that was added
4488 */
4489
4490/**
4491 * Adds a child to the container at a specified index.
4492 *
4493 * @method addChildAt
4494 * @param {Object} child The child to add
4495 * @param {Number} index The index to place the child in
4496 * @return {Object} The child that was added
4497 */
4498
4499/**
4500 * Removes a child from the container.
4501 *
4502 * @method removeChild
4503 * @param {Object} child The child to remove
4504 * @return {Object} The child that was removed
4505 */
4506
4507/**
4508 * Removes a child from the specified index position.
4509 *
4510 * @method removeChildAt
4511 * @param {Number} index The index to get the child from
4512 * @return {Object} The child that was removed
4513 */
4514
4515//-----------------------------------------------------------------------------
4516/**
4517 * The tilemap which displays 2D tile-based game map.
4518 *
4519 * @class Tilemap
4520 * @constructor
4521 */
4522function Tilemap() {
4523 this.initialize.apply(this, arguments);
4524}
4525
4526Tilemap.prototype = Object.create(PIXI.Container.prototype);
4527Tilemap.prototype.constructor = Tilemap;
4528
4529Tilemap.prototype.initialize = function() {
4530 PIXI.Container.call(this);
4531
4532 this._margin = 20;
4533 this._width = Graphics.width + this._margin * 2;
4534 this._height = Graphics.height + this._margin * 2;
4535 this._tileWidth = 48;
4536 this._tileHeight = 48;
4537 this._mapWidth = 0;
4538 this._mapHeight = 0;
4539 this._mapData = null;
4540 this._layerWidth = 0;
4541 this._layerHeight = 0;
4542 this._lastTiles = [];
4543
4544 /**
4545 * The bitmaps used as a tileset.
4546 *
4547 * @property bitmaps
4548 * @type Array
4549 */
4550 this.bitmaps = [];
4551
4552 /**
4553 * The origin point of the tilemap for scrolling.
4554 *
4555 * @property origin
4556 * @type Point
4557 */
4558 this.origin = new Point();
4559
4560 /**
4561 * The tileset flags.
4562 *
4563 * @property flags
4564 * @type Array
4565 */
4566 this.flags = [];
4567
4568 /**
4569 * The animation count for autotiles.
4570 *
4571 * @property animationCount
4572 * @type Number
4573 */
4574 this.animationCount = 0;
4575
4576 /**
4577 * Whether the tilemap loops horizontal.
4578 *
4579 * @property horizontalWrap
4580 * @type Boolean
4581 */
4582 this.horizontalWrap = false;
4583
4584 /**
4585 * Whether the tilemap loops vertical.
4586 *
4587 * @property verticalWrap
4588 * @type Boolean
4589 */
4590 this.verticalWrap = false;
4591
4592 this._createLayers();
4593 this.refresh();
4594};
4595
4596/**
4597 * The width of the screen in pixels.
4598 *
4599 * @property width
4600 * @type Number
4601 */
4602Object.defineProperty(Tilemap.prototype, 'width', {
4603 get: function() {
4604 return this._width;
4605 },
4606 set: function(value) {
4607 if (this._width !== value) {
4608 this._width = value;
4609 this._createLayers();
4610 }
4611 }
4612});
4613
4614/**
4615 * The height of the screen in pixels.
4616 *
4617 * @property height
4618 * @type Number
4619 */
4620Object.defineProperty(Tilemap.prototype, 'height', {
4621 get: function() {
4622 return this._height;
4623 },
4624 set: function(value) {
4625 if (this._height !== value) {
4626 this._height = value;
4627 this._createLayers();
4628 }
4629 }
4630});
4631
4632/**
4633 * The width of a tile in pixels.
4634 *
4635 * @property tileWidth
4636 * @type Number
4637 */
4638Object.defineProperty(Tilemap.prototype, 'tileWidth', {
4639 get: function() {
4640 return this._tileWidth;
4641 },
4642 set: function(value) {
4643 if (this._tileWidth !== value) {
4644 this._tileWidth = value;
4645 this._createLayers();
4646 }
4647 }
4648});
4649
4650/**
4651 * The height of a tile in pixels.
4652 *
4653 * @property tileHeight
4654 * @type Number
4655 */
4656Object.defineProperty(Tilemap.prototype, 'tileHeight', {
4657 get: function() {
4658 return this._tileHeight;
4659 },
4660 set: function(value) {
4661 if (this._tileHeight !== value) {
4662 this._tileHeight = value;
4663 this._createLayers();
4664 }
4665 }
4666});
4667
4668/**
4669 * Sets the tilemap data.
4670 *
4671 * @method setData
4672 * @param {Number} width The width of the map in number of tiles
4673 * @param {Number} height The height of the map in number of tiles
4674 * @param {Array} data The one dimensional array for the map data
4675 */
4676Tilemap.prototype.setData = function(width, height, data) {
4677 this._mapWidth = width;
4678 this._mapHeight = height;
4679 this._mapData = data;
4680};
4681
4682/**
4683 * Checks whether the tileset is ready to render.
4684 *
4685 * @method isReady
4686 * @type Boolean
4687 * @return {Boolean} True if the tilemap is ready
4688 */
4689Tilemap.prototype.isReady = function() {
4690 for (var i = 0; i < this.bitmaps.length; i++) {
4691 if (this.bitmaps[i] && !this.bitmaps[i].isReady()) {
4692 return false;
4693 }
4694 }
4695 return true;
4696};
4697
4698/**
4699 * Updates the tilemap for each frame.
4700 *
4701 * @method update
4702 */
4703Tilemap.prototype.update = function() {
4704 this.animationCount++;
4705 this.animationFrame = Math.floor(this.animationCount / 30);
4706 this.children.forEach(function(child) {
4707 if (child.update) {
4708 child.update();
4709 }
4710 });
4711 for (var i=0; i<this.bitmaps.length;i++) {
4712 if (this.bitmaps[i]) {
4713 this.bitmaps[i].touch();
4714 }
4715 }
4716};
4717
4718/**
4719 * Forces to repaint the entire tilemap.
4720 *
4721 * @method refresh
4722 */
4723Tilemap.prototype.refresh = function() {
4724 this._lastTiles.length = 0;
4725};
4726
4727/**
4728 * Forces to refresh the tileset
4729 *
4730 * @method refresh
4731 */
4732Tilemap.prototype.refreshTileset = function() {
4733
4734};
4735
4736/**
4737 * @method updateTransform
4738 * @private
4739 */
4740Tilemap.prototype.updateTransform = function() {
4741 var ox = Math.floor(this.origin.x);
4742 var oy = Math.floor(this.origin.y);
4743 var startX = Math.floor((ox - this._margin) / this._tileWidth);
4744 var startY = Math.floor((oy - this._margin) / this._tileHeight);
4745 this._updateLayerPositions(startX, startY);
4746 if (this._needsRepaint || this._lastAnimationFrame !== this.animationFrame ||
4747 this._lastStartX !== startX || this._lastStartY !== startY) {
4748 this._frameUpdated = this._lastAnimationFrame !== this.animationFrame;
4749 this._lastAnimationFrame = this.animationFrame;
4750 this._lastStartX = startX;
4751 this._lastStartY = startY;
4752 this._paintAllTiles(startX, startY);
4753 this._needsRepaint = false;
4754 }
4755 this._sortChildren();
4756 PIXI.Container.prototype.updateTransform.call(this);
4757};
4758
4759/**
4760 * @method _createLayers
4761 * @private
4762 */
4763Tilemap.prototype._createLayers = function() {
4764 var width = this._width;
4765 var height = this._height;
4766 var margin = this._margin;
4767 var tileCols = Math.ceil(width / this._tileWidth) + 1;
4768 var tileRows = Math.ceil(height / this._tileHeight) + 1;
4769 var layerWidth = tileCols * this._tileWidth;
4770 var layerHeight = tileRows * this._tileHeight;
4771 this._lowerBitmap = new Bitmap(layerWidth, layerHeight);
4772 this._upperBitmap = new Bitmap(layerWidth, layerHeight);
4773 this._layerWidth = layerWidth;
4774 this._layerHeight = layerHeight;
4775
4776 /*
4777 * Z coordinate:
4778 *
4779 * 0 : Lower tiles
4780 * 1 : Lower characters
4781 * 3 : Normal characters
4782 * 4 : Upper tiles
4783 * 5 : Upper characters
4784 * 6 : Airship shadow
4785 * 7 : Balloon
4786 * 8 : Animation
4787 * 9 : Destination
4788 */
4789
4790 this._lowerLayer = new Sprite();
4791 this._lowerLayer.move(-margin, -margin, width, height);
4792 this._lowerLayer.z = 0;
4793
4794 this._upperLayer = new Sprite();
4795 this._upperLayer.move(-margin, -margin, width, height);
4796 this._upperLayer.z = 4;
4797
4798 for (var i = 0; i < 4; i++) {
4799 this._lowerLayer.addChild(new Sprite(this._lowerBitmap));
4800 this._upperLayer.addChild(new Sprite(this._upperBitmap));
4801 }
4802
4803 this.addChild(this._lowerLayer);
4804 this.addChild(this._upperLayer);
4805};
4806
4807/**
4808 * @method _updateLayerPositions
4809 * @param {Number} startX
4810 * @param {Number} startY
4811 * @private
4812 */
4813Tilemap.prototype._updateLayerPositions = function(startX, startY) {
4814 var m = this._margin;
4815 var ox = Math.floor(this.origin.x);
4816 var oy = Math.floor(this.origin.y);
4817 var x2 = (ox - m).mod(this._layerWidth);
4818 var y2 = (oy - m).mod(this._layerHeight);
4819 var w1 = this._layerWidth - x2;
4820 var h1 = this._layerHeight - y2;
4821 var w2 = this._width - w1;
4822 var h2 = this._height - h1;
4823
4824 for (var i = 0; i < 2; i++) {
4825 var children;
4826 if (i === 0) {
4827 children = this._lowerLayer.children;
4828 } else {
4829 children = this._upperLayer.children;
4830 }
4831 children[0].move(0, 0, w1, h1);
4832 children[0].setFrame(x2, y2, w1, h1);
4833 children[1].move(w1, 0, w2, h1);
4834 children[1].setFrame(0, y2, w2, h1);
4835 children[2].move(0, h1, w1, h2);
4836 children[2].setFrame(x2, 0, w1, h2);
4837 children[3].move(w1, h1, w2, h2);
4838 children[3].setFrame(0, 0, w2, h2);
4839 }
4840};
4841
4842/**
4843 * @method _paintAllTiles
4844 * @param {Number} startX
4845 * @param {Number} startY
4846 * @private
4847 */
4848Tilemap.prototype._paintAllTiles = function(startX, startY) {
4849 var tileCols = Math.ceil(this._width / this._tileWidth) + 1;
4850 var tileRows = Math.ceil(this._height / this._tileHeight) + 1;
4851 for (var y = 0; y < tileRows; y++) {
4852 for (var x = 0; x < tileCols; x++) {
4853 this._paintTiles(startX, startY, x, y);
4854 }
4855 }
4856};
4857
4858/**
4859 * @method _paintTiles
4860 * @param {Number} startX
4861 * @param {Number} startY
4862 * @param {Number} x
4863 * @param {Number} y
4864 * @private
4865 */
4866Tilemap.prototype._paintTiles = function(startX, startY, x, y) {
4867 var tableEdgeVirtualId = 10000;
4868 var mx = startX + x;
4869 var my = startY + y;
4870 var dx = (mx * this._tileWidth).mod(this._layerWidth);
4871 var dy = (my * this._tileHeight).mod(this._layerHeight);
4872 var lx = dx / this._tileWidth;
4873 var ly = dy / this._tileHeight;
4874 var tileId0 = this._readMapData(mx, my, 0);
4875 var tileId1 = this._readMapData(mx, my, 1);
4876 var tileId2 = this._readMapData(mx, my, 2);
4877 var tileId3 = this._readMapData(mx, my, 3);
4878 var shadowBits = this._readMapData(mx, my, 4);
4879 var upperTileId1 = this._readMapData(mx, my - 1, 1);
4880 var lowerTiles = [];
4881 var upperTiles = [];
4882
4883 if (this._isHigherTile(tileId0)) {
4884 upperTiles.push(tileId0);
4885 } else {
4886 lowerTiles.push(tileId0);
4887 }
4888 if (this._isHigherTile(tileId1)) {
4889 upperTiles.push(tileId1);
4890 } else {
4891 lowerTiles.push(tileId1);
4892 }
4893
4894 lowerTiles.push(-shadowBits);
4895
4896 if (this._isTableTile(upperTileId1) && !this._isTableTile(tileId1)) {
4897 if (!Tilemap.isShadowingTile(tileId0)) {
4898 lowerTiles.push(tableEdgeVirtualId + upperTileId1);
4899 }
4900 }
4901
4902 if (this._isOverpassPosition(mx, my)) {
4903 upperTiles.push(tileId2);
4904 upperTiles.push(tileId3);
4905 } else {
4906 if (this._isHigherTile(tileId2)) {
4907 upperTiles.push(tileId2);
4908 } else {
4909 lowerTiles.push(tileId2);
4910 }
4911 if (this._isHigherTile(tileId3)) {
4912 upperTiles.push(tileId3);
4913 } else {
4914 lowerTiles.push(tileId3);
4915 }
4916 }
4917
4918 var lastLowerTiles = this._readLastTiles(0, lx, ly);
4919 if (!lowerTiles.equals(lastLowerTiles) ||
4920 (Tilemap.isTileA1(tileId0) && this._frameUpdated)) {
4921 this._lowerBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
4922 for (var i = 0; i < lowerTiles.length; i++) {
4923 var lowerTileId = lowerTiles[i];
4924 if (lowerTileId < 0) {
4925 this._drawShadow(this._lowerBitmap, shadowBits, dx, dy);
4926 } else if (lowerTileId >= tableEdgeVirtualId) {
4927 this._drawTableEdge(this._lowerBitmap, upperTileId1, dx, dy);
4928 } else {
4929 this._drawTile(this._lowerBitmap, lowerTileId, dx, dy);
4930 }
4931 }
4932 this._writeLastTiles(0, lx, ly, lowerTiles);
4933 }
4934
4935 var lastUpperTiles = this._readLastTiles(1, lx, ly);
4936 if (!upperTiles.equals(lastUpperTiles)) {
4937 this._upperBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
4938 for (var j = 0; j < upperTiles.length; j++) {
4939 this._drawTile(this._upperBitmap, upperTiles[j], dx, dy);
4940 }
4941 this._writeLastTiles(1, lx, ly, upperTiles);
4942 }
4943};
4944
4945/**
4946 * @method _readLastTiles
4947 * @param {Number} i
4948 * @param {Number} x
4949 * @param {Number} y
4950 * @private
4951 */
4952Tilemap.prototype._readLastTiles = function(i, x, y) {
4953 var array1 = this._lastTiles[i];
4954 if (array1) {
4955 var array2 = array1[y];
4956 if (array2) {
4957 var tiles = array2[x];
4958 if (tiles) {
4959 return tiles;
4960 }
4961 }
4962 }
4963 return [];
4964};
4965
4966/**
4967 * @method _writeLastTiles
4968 * @param {Number} i
4969 * @param {Number} x
4970 * @param {Number} y
4971 * @param {Array} tiles
4972 * @private
4973 */
4974Tilemap.prototype._writeLastTiles = function(i, x, y, tiles) {
4975 var array1 = this._lastTiles[i];
4976 if (!array1) {
4977 array1 = this._lastTiles[i] = [];
4978 }
4979 var array2 = array1[y];
4980 if (!array2) {
4981 array2 = array1[y] = [];
4982 }
4983 array2[x] = tiles;
4984};
4985
4986/**
4987 * @method _drawTile
4988 * @param {Bitmap} bitmap
4989 * @param {Number} tileId
4990 * @param {Number} dx
4991 * @param {Number} dy
4992 * @private
4993 */
4994Tilemap.prototype._drawTile = function(bitmap, tileId, dx, dy) {
4995 if (Tilemap.isVisibleTile(tileId)) {
4996 if (Tilemap.isAutotile(tileId)) {
4997 this._drawAutotile(bitmap, tileId, dx, dy);
4998 } else {
4999 this._drawNormalTile(bitmap, tileId, dx, dy);
5000 }
5001 }
5002};
5003
5004/**
5005 * @method _drawNormalTile
5006 * @param {Bitmap} bitmap
5007 * @param {Number} tileId
5008 * @param {Number} dx
5009 * @param {Number} dy
5010 * @private
5011 */
5012Tilemap.prototype._drawNormalTile = function(bitmap, tileId, dx, dy) {
5013 var setNumber = 0;
5014
5015 if (Tilemap.isTileA5(tileId)) {
5016 setNumber = 4;
5017 } else {
5018 setNumber = 5 + Math.floor(tileId / 256);
5019 }
5020
5021 var w = this._tileWidth;
5022 var h = this._tileHeight;
5023 var sx = (Math.floor(tileId / 128) % 2 * 8 + tileId % 8) * w;
5024 var sy = (Math.floor(tileId % 256 / 8) % 16) * h;
5025
5026 var source = this.bitmaps[setNumber];
5027 if (source) {
5028 bitmap.bltImage(source, sx, sy, w, h, dx, dy, w, h);
5029 }
5030};
5031
5032/**
5033 * @method _drawAutotile
5034 * @param {Bitmap} bitmap
5035 * @param {Number} tileId
5036 * @param {Number} dx
5037 * @param {Number} dy
5038 * @private
5039 */
5040Tilemap.prototype._drawAutotile = function(bitmap, tileId, dx, dy) {
5041 var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE;
5042 var kind = Tilemap.getAutotileKind(tileId);
5043 var shape = Tilemap.getAutotileShape(tileId);
5044 var tx = kind % 8;
5045 var ty = Math.floor(kind / 8);
5046 var bx = 0;
5047 var by = 0;
5048 var setNumber = 0;
5049 var isTable = false;
5050
5051 if (Tilemap.isTileA1(tileId)) {
5052 var waterSurfaceIndex = [0, 1, 2, 1][this.animationFrame % 4];
5053 setNumber = 0;
5054 if (kind === 0) {
5055 bx = waterSurfaceIndex * 2;
5056 by = 0;
5057 } else if (kind === 1) {
5058 bx = waterSurfaceIndex * 2;
5059 by = 3;
5060 } else if (kind === 2) {
5061 bx = 6;
5062 by = 0;
5063 } else if (kind === 3) {
5064 bx = 6;
5065 by = 3;
5066 } else {
5067 bx = Math.floor(tx / 4) * 8;
5068 by = ty * 6 + Math.floor(tx / 2) % 2 * 3;
5069 if (kind % 2 === 0) {
5070 bx += waterSurfaceIndex * 2;
5071 }
5072 else {
5073 bx += 6;
5074 autotileTable = Tilemap.WATERFALL_AUTOTILE_TABLE;
5075 by += this.animationFrame % 3;
5076 }
5077 }
5078 } else if (Tilemap.isTileA2(tileId)) {
5079 setNumber = 1;
5080 bx = tx * 2;
5081 by = (ty - 2) * 3;
5082 isTable = this._isTableTile(tileId);
5083 } else if (Tilemap.isTileA3(tileId)) {
5084 setNumber = 2;
5085 bx = tx * 2;
5086 by = (ty - 6) * 2;
5087 autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
5088 } else if (Tilemap.isTileA4(tileId)) {
5089 setNumber = 3;
5090 bx = tx * 2;
5091 by = Math.floor((ty - 10) * 2.5 + (ty % 2 === 1 ? 0.5 : 0));
5092 if (ty % 2 === 1) {
5093 autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
5094 }
5095 }
5096
5097 var table = autotileTable[shape];
5098 var source = this.bitmaps[setNumber];
5099
5100 if (table && source) {
5101 var w1 = this._tileWidth / 2;
5102 var h1 = this._tileHeight / 2;
5103 for (var i = 0; i < 4; i++) {
5104 var qsx = table[i][0];
5105 var qsy = table[i][1];
5106 var sx1 = (bx * 2 + qsx) * w1;
5107 var sy1 = (by * 2 + qsy) * h1;
5108 var dx1 = dx + (i % 2) * w1;
5109 var dy1 = dy + Math.floor(i / 2) * h1;
5110 if (isTable && (qsy === 1 || qsy === 5)) {
5111 var qsx2 = qsx;
5112 var qsy2 = 3;
5113 if (qsy === 1) {
5114 qsx2 = [0,3,2,1][qsx];
5115 }
5116 var sx2 = (bx * 2 + qsx2) * w1;
5117 var sy2 = (by * 2 + qsy2) * h1;
5118 bitmap.bltImage(source, sx2, sy2, w1, h1, dx1, dy1, w1, h1);
5119 dy1 += h1/2;
5120 bitmap.bltImage(source, sx1, sy1, w1, h1/2, dx1, dy1, w1, h1/2);
5121 } else {
5122 bitmap.bltImage(source, sx1, sy1, w1, h1, dx1, dy1, w1, h1);
5123 }
5124 }
5125 }
5126};
5127
5128/**
5129 * @method _drawTableEdge
5130 * @param {Bitmap} bitmap
5131 * @param {Number} tileId
5132 * @param {Number} dx
5133 * @param {Number} dy
5134 * @private
5135 */
5136Tilemap.prototype._drawTableEdge = function(bitmap, tileId, dx, dy) {
5137 if (Tilemap.isTileA2(tileId)) {
5138 var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE;
5139 var kind = Tilemap.getAutotileKind(tileId);
5140 var shape = Tilemap.getAutotileShape(tileId);
5141 var tx = kind % 8;
5142 var ty = Math.floor(kind / 8);
5143 var setNumber = 1;
5144 var bx = tx * 2;
5145 var by = (ty - 2) * 3;
5146 var table = autotileTable[shape];
5147
5148 if (table) {
5149 var source = this.bitmaps[setNumber];
5150 var w1 = this._tileWidth / 2;
5151 var h1 = this._tileHeight / 2;
5152 for (var i = 0; i < 2; i++) {
5153 var qsx = table[2 + i][0];
5154 var qsy = table[2 + i][1];
5155 var sx1 = (bx * 2 + qsx) * w1;
5156 var sy1 = (by * 2 + qsy) * h1 + h1/2;
5157 var dx1 = dx + (i % 2) * w1;
5158 var dy1 = dy + Math.floor(i / 2) * h1;
5159 bitmap.bltImage(source, sx1, sy1, w1, h1/2, dx1, dy1, w1, h1/2);
5160 }
5161 }
5162 }
5163};
5164
5165/**
5166 * @method _drawShadow
5167 * @param {Bitmap} bitmap
5168 * @param {Number} shadowBits
5169 * @param {Number} dx
5170 * @param {Number} dy
5171 * @private
5172 */
5173Tilemap.prototype._drawShadow = function(bitmap, shadowBits, dx, dy) {
5174 if (shadowBits & 0x0f) {
5175 var w1 = this._tileWidth / 2;
5176 var h1 = this._tileHeight / 2;
5177 var color = 'rgba(0,0,0,0.5)';
5178 for (var i = 0; i < 4; i++) {
5179 if (shadowBits & (1 << i)) {
5180 var dx1 = dx + (i % 2) * w1;
5181 var dy1 = dy + Math.floor(i / 2) * h1;
5182 bitmap.fillRect(dx1, dy1, w1, h1, color);
5183 }
5184 }
5185 }
5186};
5187
5188/**
5189 * @method _readMapData
5190 * @param {Number} x
5191 * @param {Number} y
5192 * @param {Number} z
5193 * @return {Number}
5194 * @private
5195 */
5196Tilemap.prototype._readMapData = function(x, y, z) {
5197 if (this._mapData) {
5198 var width = this._mapWidth;
5199 var height = this._mapHeight;
5200 if (this.horizontalWrap) {
5201 x = x.mod(width);
5202 }
5203 if (this.verticalWrap) {
5204 y = y.mod(height);
5205 }
5206 if (x >= 0 && x < width && y >= 0 && y < height) {
5207 return this._mapData[(z * height + y) * width + x] || 0;
5208 } else {
5209 return 0;
5210 }
5211 } else {
5212 return 0;
5213 }
5214};
5215
5216/**
5217 * @method _isHigherTile
5218 * @param {Number} tileId
5219 * @return {Boolean}
5220 * @private
5221 */
5222Tilemap.prototype._isHigherTile = function(tileId) {
5223 return this.flags[tileId] & 0x10;
5224};
5225
5226/**
5227 * @method _isTableTile
5228 * @param {Number} tileId
5229 * @return {Boolean}
5230 * @private
5231 */
5232Tilemap.prototype._isTableTile = function(tileId) {
5233 return Tilemap.isTileA2(tileId) && (this.flags[tileId] & 0x80);
5234};
5235
5236/**
5237 * @method _isOverpassPosition
5238 * @param {Number} mx
5239 * @param {Number} my
5240 * @return {Boolean}
5241 * @private
5242 */
5243Tilemap.prototype._isOverpassPosition = function(mx, my) {
5244 return false;
5245};
5246
5247/**
5248 * @method _sortChildren
5249 * @private
5250 */
5251Tilemap.prototype._sortChildren = function() {
5252 this.children.sort(this._compareChildOrder.bind(this));
5253};
5254
5255/**
5256 * @method _compareChildOrder
5257 * @param {Object} a
5258 * @param {Object} b
5259 * @private
5260 */
5261Tilemap.prototype._compareChildOrder = function(a, b) {
5262 if (a.z !== b.z) {
5263 return a.z - b.z;
5264 } else if (a.y !== b.y) {
5265 return a.y - b.y;
5266 } else {
5267 return a.spriteId - b.spriteId;
5268 }
5269};
5270
5271// Tile type checkers
5272
5273Tilemap.TILE_ID_B = 0;
5274Tilemap.TILE_ID_C = 256;
5275Tilemap.TILE_ID_D = 512;
5276Tilemap.TILE_ID_E = 768;
5277Tilemap.TILE_ID_A5 = 1536;
5278Tilemap.TILE_ID_A1 = 2048;
5279Tilemap.TILE_ID_A2 = 2816;
5280Tilemap.TILE_ID_A3 = 4352;
5281Tilemap.TILE_ID_A4 = 5888;
5282Tilemap.TILE_ID_MAX = 8192;
5283
5284Tilemap.isVisibleTile = function(tileId) {
5285 return tileId > 0 && tileId < this.TILE_ID_MAX;
5286};
5287
5288Tilemap.isAutotile = function(tileId) {
5289 return tileId >= this.TILE_ID_A1;
5290};
5291
5292Tilemap.getAutotileKind = function(tileId) {
5293 return Math.floor((tileId - this.TILE_ID_A1) / 48);
5294};
5295
5296Tilemap.getAutotileShape = function(tileId) {
5297 return (tileId - this.TILE_ID_A1) % 48;
5298};
5299
5300Tilemap.makeAutotileId = function(kind, shape) {
5301 return this.TILE_ID_A1 + kind * 48 + shape;
5302};
5303
5304Tilemap.isSameKindTile = function(tileID1, tileID2) {
5305 if (this.isAutotile(tileID1) && this.isAutotile(tileID2)) {
5306 return this.getAutotileKind(tileID1) === this.getAutotileKind(tileID2);
5307 } else {
5308 return tileID1 === tileID2;
5309 }
5310};
5311
5312Tilemap.isTileA1 = function(tileId) {
5313 return tileId >= this.TILE_ID_A1 && tileId < this.TILE_ID_A2;
5314};
5315
5316Tilemap.isTileA2 = function(tileId) {
5317 return tileId >= this.TILE_ID_A2 && tileId < this.TILE_ID_A3;
5318};
5319
5320Tilemap.isTileA3 = function(tileId) {
5321 return tileId >= this.TILE_ID_A3 && tileId < this.TILE_ID_A4;
5322};
5323
5324Tilemap.isTileA4 = function(tileId) {
5325 return tileId >= this.TILE_ID_A4 && tileId < this.TILE_ID_MAX;
5326};
5327
5328Tilemap.isTileA5 = function(tileId) {
5329 return tileId >= this.TILE_ID_A5 && tileId < this.TILE_ID_A1;
5330};
5331
5332Tilemap.isWaterTile = function(tileId) {
5333 if (this.isTileA1(tileId)) {
5334 return !(tileId >= this.TILE_ID_A1 + 96 && tileId < this.TILE_ID_A1 + 192);
5335 } else {
5336 return false;
5337 }
5338};
5339
5340Tilemap.isWaterfallTile = function(tileId) {
5341 if (tileId >= this.TILE_ID_A1 + 192 && tileId < this.TILE_ID_A2) {
5342 return this.getAutotileKind(tileId) % 2 === 1;
5343 } else {
5344 return false;
5345 }
5346};
5347
5348Tilemap.isGroundTile = function(tileId) {
5349 return this.isTileA1(tileId) || this.isTileA2(tileId) || this.isTileA5(tileId);
5350};
5351
5352Tilemap.isShadowingTile = function(tileId) {
5353 return this.isTileA3(tileId) || this.isTileA4(tileId);
5354};
5355
5356Tilemap.isRoofTile = function(tileId) {
5357 return this.isTileA3(tileId) && this.getAutotileKind(tileId) % 16 < 8;
5358};
5359
5360Tilemap.isWallTopTile = function(tileId) {
5361 return this.isTileA4(tileId) && this.getAutotileKind(tileId) % 16 < 8;
5362};
5363
5364Tilemap.isWallSideTile = function(tileId) {
5365 return (this.isTileA3(tileId) || this.isTileA4(tileId)) &&
5366 this.getAutotileKind(tileId) % 16 >= 8;
5367};
5368
5369Tilemap.isWallTile = function(tileId) {
5370 return this.isWallTopTile(tileId) || this.isWallSideTile(tileId);
5371};
5372
5373Tilemap.isFloorTypeAutotile = function(tileId) {
5374 return (this.isTileA1(tileId) && !this.isWaterfallTile(tileId)) ||
5375 this.isTileA2(tileId) || this.isWallTopTile(tileId);
5376};
5377
5378Tilemap.isWallTypeAutotile = function(tileId) {
5379 return this.isRoofTile(tileId) || this.isWallSideTile(tileId);
5380};
5381
5382Tilemap.isWaterfallTypeAutotile = function(tileId) {
5383 return this.isWaterfallTile(tileId);
5384};
5385
5386// Autotile shape number to coordinates of tileset images
5387
5388Tilemap.FLOOR_AUTOTILE_TABLE = [
5389 [[2,4],[1,4],[2,3],[1,3]],[[2,0],[1,4],[2,3],[1,3]],
5390 [[2,4],[3,0],[2,3],[1,3]],[[2,0],[3,0],[2,3],[1,3]],
5391 [[2,4],[1,4],[2,3],[3,1]],[[2,0],[1,4],[2,3],[3,1]],
5392 [[2,4],[3,0],[2,3],[3,1]],[[2,0],[3,0],[2,3],[3,1]],
5393 [[2,4],[1,4],[2,1],[1,3]],[[2,0],[1,4],[2,1],[1,3]],
5394 [[2,4],[3,0],[2,1],[1,3]],[[2,0],[3,0],[2,1],[1,3]],
5395 [[2,4],[1,4],[2,1],[3,1]],[[2,0],[1,4],[2,1],[3,1]],
5396 [[2,4],[3,0],[2,1],[3,1]],[[2,0],[3,0],[2,1],[3,1]],
5397 [[0,4],[1,4],[0,3],[1,3]],[[0,4],[3,0],[0,3],[1,3]],
5398 [[0,4],[1,4],[0,3],[3,1]],[[0,4],[3,0],[0,3],[3,1]],
5399 [[2,2],[1,2],[2,3],[1,3]],[[2,2],[1,2],[2,3],[3,1]],
5400 [[2,2],[1,2],[2,1],[1,3]],[[2,2],[1,2],[2,1],[3,1]],
5401 [[2,4],[3,4],[2,3],[3,3]],[[2,4],[3,4],[2,1],[3,3]],
5402 [[2,0],[3,4],[2,3],[3,3]],[[2,0],[3,4],[2,1],[3,3]],
5403 [[2,4],[1,4],[2,5],[1,5]],[[2,0],[1,4],[2,5],[1,5]],
5404 [[2,4],[3,0],[2,5],[1,5]],[[2,0],[3,0],[2,5],[1,5]],
5405 [[0,4],[3,4],[0,3],[3,3]],[[2,2],[1,2],[2,5],[1,5]],
5406 [[0,2],[1,2],[0,3],[1,3]],[[0,2],[1,2],[0,3],[3,1]],
5407 [[2,2],[3,2],[2,3],[3,3]],[[2,2],[3,2],[2,1],[3,3]],
5408 [[2,4],[3,4],[2,5],[3,5]],[[2,0],[3,4],[2,5],[3,5]],
5409 [[0,4],[1,4],[0,5],[1,5]],[[0,4],[3,0],[0,5],[1,5]],
5410 [[0,2],[3,2],[0,3],[3,3]],[[0,2],[1,2],[0,5],[1,5]],
5411 [[0,4],[3,4],[0,5],[3,5]],[[2,2],[3,2],[2,5],[3,5]],
5412 [[0,2],[3,2],[0,5],[3,5]],[[0,0],[1,0],[0,1],[1,1]]
5413];
5414
5415Tilemap.WALL_AUTOTILE_TABLE = [
5416 [[2,2],[1,2],[2,1],[1,1]],[[0,2],[1,2],[0,1],[1,1]],
5417 [[2,0],[1,0],[2,1],[1,1]],[[0,0],[1,0],[0,1],[1,1]],
5418 [[2,2],[3,2],[2,1],[3,1]],[[0,2],[3,2],[0,1],[3,1]],
5419 [[2,0],[3,0],[2,1],[3,1]],[[0,0],[3,0],[0,1],[3,1]],
5420 [[2,2],[1,2],[2,3],[1,3]],[[0,2],[1,2],[0,3],[1,3]],
5421 [[2,0],[1,0],[2,3],[1,3]],[[0,0],[1,0],[0,3],[1,3]],
5422 [[2,2],[3,2],[2,3],[3,3]],[[0,2],[3,2],[0,3],[3,3]],
5423 [[2,0],[3,0],[2,3],[3,3]],[[0,0],[3,0],[0,3],[3,3]]
5424];
5425
5426Tilemap.WATERFALL_AUTOTILE_TABLE = [
5427 [[2,0],[1,0],[2,1],[1,1]],[[0,0],[1,0],[0,1],[1,1]],
5428 [[2,0],[3,0],[2,1],[3,1]],[[0,0],[3,0],[0,1],[3,1]]
5429];
5430
5431// The important members from Pixi.js
5432
5433/**
5434 * [read-only] The array of children of the tilemap.
5435 *
5436 * @property children
5437 * @type Array
5438 */
5439
5440/**
5441 * [read-only] The object that contains the tilemap.
5442 *
5443 * @property parent
5444 * @type Object
5445 */
5446
5447/**
5448 * Adds a child to the container.
5449 *
5450 * @method addChild
5451 * @param {Object} child The child to add
5452 * @return {Object} The child that was added
5453 */
5454
5455/**
5456 * Adds a child to the container at a specified index.
5457 *
5458 * @method addChildAt
5459 * @param {Object} child The child to add
5460 * @param {Number} index The index to place the child in
5461 * @return {Object} The child that was added
5462 */
5463
5464/**
5465 * Removes a child from the container.
5466 *
5467 * @method removeChild
5468 * @param {Object} child The child to remove
5469 * @return {Object} The child that was removed
5470 */
5471
5472/**
5473 * Removes a child from the specified index position.
5474 *
5475 * @method removeChildAt
5476 * @param {Number} index The index to get the child from
5477 * @return {Object} The child that was removed
5478 */
5479
5480//-----------------------------------------------------------------------------
5481/**
5482 * The tilemap which displays 2D tile-based game map using shaders
5483 *
5484 * @class Tilemap
5485 * @constructor
5486 */
5487function ShaderTilemap() {
5488 Tilemap.apply(this, arguments);
5489 this.roundPixels = true;
5490}
5491
5492ShaderTilemap.prototype = Object.create(Tilemap.prototype);
5493ShaderTilemap.prototype.constructor = ShaderTilemap;
5494
5495// we need this constant for some platforms (Samsung S4, S5, Tab4, HTC One H8)
5496PIXI.glCore.VertexArrayObject.FORCE_NATIVE = true;
5497PIXI.settings.GC_MODE = PIXI.GC_MODES.AUTO;
5498PIXI.tilemap.TileRenderer.SCALE_MODE = PIXI.SCALE_MODES.NEAREST;
5499PIXI.tilemap.TileRenderer.DO_CLEAR = true;
5500
5501/**
5502 * Uploads animation state in renderer
5503 *
5504 * @method _hackRenderer
5505 * @private
5506 */
5507ShaderTilemap.prototype._hackRenderer = function(renderer) {
5508 var af = this.animationFrame % 4;
5509 if (af==3) af = 1;
5510 renderer.plugins.tilemap.tileAnim[0] = af * this._tileWidth;
5511 renderer.plugins.tilemap.tileAnim[1] = (this.animationFrame % 3) * this._tileHeight;
5512 return renderer;
5513};
5514
5515/**
5516 * PIXI render method
5517 *
5518 * @method renderCanvas
5519 * @param {Object} pixi renderer
5520 */
5521ShaderTilemap.prototype.renderCanvas = function(renderer) {
5522 this._hackRenderer(renderer);
5523 PIXI.Container.prototype.renderCanvas.call(this, renderer);
5524};
5525
5526
5527/**
5528 * PIXI render method
5529 *
5530 * @method renderWebGL
5531 * @param {Object} pixi renderer
5532 */
5533ShaderTilemap.prototype.renderWebGL = function(renderer) {
5534 this._hackRenderer(renderer);
5535 PIXI.Container.prototype.renderWebGL.call(this, renderer);
5536};
5537
5538/**
5539 * Forces to repaint the entire tilemap AND update bitmaps list if needed
5540 *
5541 * @method refresh
5542 */
5543ShaderTilemap.prototype.refresh = function() {
5544 if (this._lastBitmapLength !== this.bitmaps.length) {
5545 this._lastBitmapLength = this.bitmaps.length;
5546 this.refreshTileset();
5547 };
5548 this._needsRepaint = true;
5549};
5550
5551/**
5552 * Call after you update tileset
5553 *
5554 * @method updateBitmaps
5555 */
5556ShaderTilemap.prototype.refreshTileset = function() {
5557 var bitmaps = this.bitmaps.map(function(x) { return x._baseTexture ? new PIXI.Texture(x._baseTexture) : x; } );
5558 this.lowerLayer.setBitmaps(bitmaps);
5559 this.upperLayer.setBitmaps(bitmaps);
5560};
5561
5562/**
5563 * @method updateTransform
5564 * @private
5565 */
5566ShaderTilemap.prototype.updateTransform = function() {
5567 if (this.roundPixels) {
5568 var ox = Math.floor(this.origin.x);
5569 var oy = Math.floor(this.origin.y);
5570 } else {
5571 ox = this.origin.x;
5572 oy = this.origin.y;
5573 }
5574 var startX = Math.floor((ox - this._margin) / this._tileWidth);
5575 var startY = Math.floor((oy - this._margin) / this._tileHeight);
5576 this._updateLayerPositions(startX, startY);
5577 if (this._needsRepaint ||
5578 this._lastStartX !== startX || this._lastStartY !== startY) {
5579 this._lastStartX = startX;
5580 this._lastStartY = startY;
5581 this._paintAllTiles(startX, startY);
5582 this._needsRepaint = false;
5583 }
5584 this._sortChildren();
5585 PIXI.Container.prototype.updateTransform.call(this);
5586};
5587
5588/**
5589 * @method _createLayers
5590 * @private
5591 */
5592ShaderTilemap.prototype._createLayers = function() {
5593 var width = this._width;
5594 var height = this._height;
5595 var margin = this._margin;
5596 var tileCols = Math.ceil(width / this._tileWidth) + 1;
5597 var tileRows = Math.ceil(height / this._tileHeight) + 1;
5598 var layerWidth = this._layerWidth = tileCols * this._tileWidth;
5599 var layerHeight = this._layerHeight = tileRows * this._tileHeight;
5600 this._needsRepaint = true;
5601
5602 if (!this.lowerZLayer) {
5603 //@hackerham: create layers only in initialization. Doesn't depend on width/height
5604 this.addChild(this.lowerZLayer = new PIXI.tilemap.ZLayer(this, 0));
5605 this.addChild(this.upperZLayer = new PIXI.tilemap.ZLayer(this, 4));
5606
5607 var parameters = PluginManager.parameters('ShaderTilemap');
5608 var useSquareShader = Number(parameters.hasOwnProperty('squareShader') ? parameters['squareShader'] : 0);
5609
5610 this.lowerZLayer.addChild(this.lowerLayer = new PIXI.tilemap.CompositeRectTileLayer(0, [], useSquareShader));
5611 this.lowerLayer.shadowColor = new Float32Array([0.0, 0.0, 0.0, 0.5]);
5612 this.upperZLayer.addChild(this.upperLayer = new PIXI.tilemap.CompositeRectTileLayer(4, [], useSquareShader));
5613 }
5614};
5615
5616/**
5617 * @method _updateLayerPositions
5618 * @param {Number} startX
5619 * @param {Number} startY
5620 * @private
5621 */
5622ShaderTilemap.prototype._updateLayerPositions = function(startX, startY) {
5623 if (this.roundPixels) {
5624 var ox = Math.floor(this.origin.x);
5625 var oy = Math.floor(this.origin.y);
5626 } else {
5627 ox = this.origin.x;
5628 oy = this.origin.y;
5629 }
5630 this.lowerZLayer.position.x = startX * this._tileWidth - ox;
5631 this.lowerZLayer.position.y = startY * this._tileHeight - oy;
5632 this.upperZLayer.position.x = startX * this._tileWidth - ox;
5633 this.upperZLayer.position.y = startY * this._tileHeight - oy;
5634};
5635
5636/**
5637 * @method _paintAllTiles
5638 * @param {Number} startX
5639 * @param {Number} startY
5640 * @private
5641 */
5642ShaderTilemap.prototype._paintAllTiles = function(startX, startY) {
5643 this.lowerZLayer.clear();
5644 this.upperZLayer.clear();
5645 var tileCols = Math.ceil(this._width / this._tileWidth) + 1;
5646 var tileRows = Math.ceil(this._height / this._tileHeight) + 1;
5647 for (var y = 0; y < tileRows; y++) {
5648 for (var x = 0; x < tileCols; x++) {
5649 this._paintTiles(startX, startY, x, y);
5650 }
5651 }
5652};
5653
5654/**
5655 * @method _paintTiles
5656 * @param {Number} startX
5657 * @param {Number} startY
5658 * @param {Number} x
5659 * @param {Number} y
5660 * @private
5661 */
5662ShaderTilemap.prototype._paintTiles = function(startX, startY, x, y) {
5663 var mx = startX + x;
5664 var my = startY + y;
5665 var dx = x * this._tileWidth, dy = y * this._tileHeight;
5666 var tileId0 = this._readMapData(mx, my, 0);
5667 var tileId1 = this._readMapData(mx, my, 1);
5668 var tileId2 = this._readMapData(mx, my, 2);
5669 var tileId3 = this._readMapData(mx, my, 3);
5670 var shadowBits = this._readMapData(mx, my, 4);
5671 var upperTileId1 = this._readMapData(mx, my - 1, 1);
5672 var lowerLayer = this.lowerLayer.children[0];
5673 var upperLayer = this.upperLayer.children[0];
5674
5675 if (this._isHigherTile(tileId0)) {
5676 this._drawTile(upperLayer, tileId0, dx, dy);
5677 } else {
5678 this._drawTile(lowerLayer, tileId0, dx, dy);
5679 }
5680 if (this._isHigherTile(tileId1)) {
5681 this._drawTile(upperLayer, tileId1, dx, dy);
5682 } else {
5683 this._drawTile(lowerLayer, tileId1, dx, dy);
5684 }
5685
5686 this._drawShadow(lowerLayer, shadowBits, dx, dy);
5687 if (this._isTableTile(upperTileId1) && !this._isTableTile(tileId1)) {
5688 if (!Tilemap.isShadowingTile(tileId0)) {
5689 this._drawTableEdge(lowerLayer, upperTileId1, dx, dy);
5690 }
5691 }
5692
5693 if (this._isOverpassPosition(mx, my)) {
5694 this._drawTile(upperLayer, tileId2, dx, dy);
5695 this._drawTile(upperLayer, tileId3, dx, dy);
5696 } else {
5697 if (this._isHigherTile(tileId2)) {
5698 this._drawTile(upperLayer, tileId2, dx, dy);
5699 } else {
5700 this._drawTile(lowerLayer, tileId2, dx, dy);
5701 }
5702 if (this._isHigherTile(tileId3)) {
5703 this._drawTile(upperLayer, tileId3, dx, dy);
5704 } else {
5705 this._drawTile(lowerLayer, tileId3, dx, dy);
5706 }
5707 }
5708};
5709
5710/**
5711 * @method _drawTile
5712 * @param {Array} layers
5713 * @param {Number} tileId
5714 * @param {Number} dx
5715 * @param {Number} dy
5716 * @private
5717 */
5718ShaderTilemap.prototype._drawTile = function(layer, tileId, dx, dy) {
5719 if (Tilemap.isVisibleTile(tileId)) {
5720 if (Tilemap.isAutotile(tileId)) {
5721 this._drawAutotile(layer, tileId, dx, dy);
5722 } else {
5723 this._drawNormalTile(layer, tileId, dx, dy);
5724 }
5725 }
5726};
5727
5728/**
5729 * @method _drawNormalTile
5730 * @param {Array} layers
5731 * @param {Number} tileId
5732 * @param {Number} dx
5733 * @param {Number} dy
5734 * @private
5735 */
5736ShaderTilemap.prototype._drawNormalTile = function(layer, tileId, dx, dy) {
5737 var setNumber = 0;
5738
5739 if (Tilemap.isTileA5(tileId)) {
5740 setNumber = 4;
5741 } else {
5742 setNumber = 5 + Math.floor(tileId / 256);
5743 }
5744
5745 var w = this._tileWidth;
5746 var h = this._tileHeight;
5747 var sx = (Math.floor(tileId / 128) % 2 * 8 + tileId % 8) * w;
5748 var sy = (Math.floor(tileId % 256 / 8) % 16) * h;
5749
5750 layer.addRect(setNumber, sx, sy, dx, dy, w, h);
5751};
5752
5753/**
5754 * @method _drawAutotile
5755 * @param {Array} layers
5756 * @param {Number} tileId
5757 * @param {Number} dx
5758 * @param {Number} dy
5759 * @private
5760 */
5761ShaderTilemap.prototype._drawAutotile = function(layer, tileId, dx, dy) {
5762 var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE;
5763 var kind = Tilemap.getAutotileKind(tileId);
5764 var shape = Tilemap.getAutotileShape(tileId);
5765 var tx = kind % 8;
5766 var ty = Math.floor(kind / 8);
5767 var bx = 0;
5768 var by = 0;
5769 var setNumber = 0;
5770 var isTable = false;
5771 var animX = 0, animY = 0;
5772
5773 if (Tilemap.isTileA1(tileId)) {
5774 setNumber = 0;
5775 if (kind === 0) {
5776 animX = 2;
5777 by = 0;
5778 } else if (kind === 1) {
5779 animX = 2;
5780 by = 3;
5781 } else if (kind === 2) {
5782 bx = 6;
5783 by = 0;
5784 } else if (kind === 3) {
5785 bx = 6;
5786 by = 3;
5787 } else {
5788 bx = Math.floor(tx / 4) * 8;
5789 by = ty * 6 + Math.floor(tx / 2) % 2 * 3;
5790 if (kind % 2 === 0) {
5791 animX = 2;
5792 }
5793 else {
5794 bx += 6;
5795 autotileTable = Tilemap.WATERFALL_AUTOTILE_TABLE;
5796 animY = 1;
5797 }
5798 }
5799 } else if (Tilemap.isTileA2(tileId)) {
5800 setNumber = 1;
5801 bx = tx * 2;
5802 by = (ty - 2) * 3;
5803 isTable = this._isTableTile(tileId);
5804 } else if (Tilemap.isTileA3(tileId)) {
5805 setNumber = 2;
5806 bx = tx * 2;
5807 by = (ty - 6) * 2;
5808 autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
5809 } else if (Tilemap.isTileA4(tileId)) {
5810 setNumber = 3;
5811 bx = tx * 2;
5812 by = Math.floor((ty - 10) * 2.5 + (ty % 2 === 1 ? 0.5 : 0));
5813 if (ty % 2 === 1) {
5814 autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
5815 }
5816 }
5817
5818 var table = autotileTable[shape];
5819 var w1 = this._tileWidth / 2;
5820 var h1 = this._tileHeight / 2;
5821 for (var i = 0; i < 4; i++) {
5822 var qsx = table[i][0];
5823 var qsy = table[i][1];
5824 var sx1 = (bx * 2 + qsx) * w1;
5825 var sy1 = (by * 2 + qsy) * h1;
5826 var dx1 = dx + (i % 2) * w1;
5827 var dy1 = dy + Math.floor(i / 2) * h1;
5828 if (isTable && (qsy === 1 || qsy === 5)) {
5829 var qsx2 = qsx;
5830 var qsy2 = 3;
5831 if (qsy === 1) {
5832 //qsx2 = [0, 3, 2, 1][qsx];
5833 qsx2 = (4-qsx)%4;
5834 }
5835 var sx2 = (bx * 2 + qsx2) * w1;
5836 var sy2 = (by * 2 + qsy2) * h1;
5837 layer.addRect(setNumber, sx2, sy2, dx1, dy1, w1, h1, animX, animY);
5838 layer.addRect(setNumber, sx1, sy1, dx1, dy1+h1/2, w1, h1/2, animX, animY);
5839 } else {
5840 layer.addRect(setNumber, sx1, sy1, dx1, dy1, w1, h1, animX, animY);
5841 }
5842 }
5843};
5844
5845/**
5846 * @method _drawTableEdge
5847 * @param {Array} layers
5848 * @param {Number} tileId
5849 * @param {Number} dx
5850 * @param {Number} dy
5851 * @private
5852 */
5853ShaderTilemap.prototype._drawTableEdge = function(layer, tileId, dx, dy) {
5854 if (Tilemap.isTileA2(tileId)) {
5855 var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE;
5856 var kind = Tilemap.getAutotileKind(tileId);
5857 var shape = Tilemap.getAutotileShape(tileId);
5858 var tx = kind % 8;
5859 var ty = Math.floor(kind / 8);
5860 var setNumber = 1;
5861 var bx = tx * 2;
5862 var by = (ty - 2) * 3;
5863 var table = autotileTable[shape];
5864 var w1 = this._tileWidth / 2;
5865 var h1 = this._tileHeight / 2;
5866 for (var i = 0; i < 2; i++) {
5867 var qsx = table[2 + i][0];
5868 var qsy = table[2 + i][1];
5869 var sx1 = (bx * 2 + qsx) * w1;
5870 var sy1 = (by * 2 + qsy) * h1 + h1 / 2;
5871 var dx1 = dx + (i % 2) * w1;
5872 var dy1 = dy + Math.floor(i / 2) * h1;
5873 layer.addRect(setNumber, sx1, sy1, dx1, dy1, w1, h1/2);
5874 }
5875 }
5876};
5877
5878/**
5879 * @method _drawShadow
5880 * @param {Number} shadowBits
5881 * @param {Number} dx
5882 * @param {Number} dy
5883 * @private
5884 */
5885ShaderTilemap.prototype._drawShadow = function(layer, shadowBits, dx, dy) {
5886 if (shadowBits & 0x0f) {
5887 var w1 = this._tileWidth / 2;
5888 var h1 = this._tileHeight / 2;
5889 for (var i = 0; i < 4; i++) {
5890 if (shadowBits & (1 << i)) {
5891 var dx1 = dx + (i % 2) * w1;
5892 var dy1 = dy + Math.floor(i / 2) * h1;
5893 layer.addRect(-1, 0, 0, dx1, dy1, w1, h1);
5894 }
5895 }
5896 }
5897};
5898//-----------------------------------------------------------------------------
5899/**
5900 * The sprite object for a tiling image.
5901 *
5902 * @class TilingSprite
5903 * @constructor
5904 * @param {Bitmap} bitmap The image for the tiling sprite
5905 */
5906function TilingSprite() {
5907 this.initialize.apply(this, arguments);
5908}
5909
5910TilingSprite.prototype = Object.create(PIXI.extras.PictureTilingSprite.prototype);
5911TilingSprite.prototype.constructor = TilingSprite;
5912
5913TilingSprite.prototype.initialize = function(bitmap) {
5914 var texture = new PIXI.Texture(new PIXI.BaseTexture());
5915
5916 PIXI.extras.PictureTilingSprite.call(this, texture);
5917
5918 this._bitmap = null;
5919 this._width = 0;
5920 this._height = 0;
5921 this._frame = new Rectangle();
5922 this.spriteId = Sprite._counter++;
5923 /**
5924 * The origin point of the tiling sprite for scrolling.
5925 *
5926 * @property origin
5927 * @type Point
5928 */
5929 this.origin = new Point();
5930
5931 this.bitmap = bitmap;
5932};
5933
5934TilingSprite.prototype._renderCanvas_PIXI = PIXI.extras.PictureTilingSprite.prototype._renderCanvas;
5935TilingSprite.prototype._renderWebGL_PIXI = PIXI.extras.PictureTilingSprite.prototype._renderWebGL;
5936
5937/**
5938 * @method _renderCanvas
5939 * @param {Object} renderer
5940 * @private
5941 */
5942TilingSprite.prototype._renderCanvas = function(renderer) {
5943 if (this._bitmap) {
5944 this._bitmap.touch();
5945 }
5946 if (this.texture.frame.width > 0 && this.texture.frame.height > 0) {
5947 this._renderCanvas_PIXI(renderer);
5948 }
5949};
5950
5951/**
5952 * @method _renderWebGL
5953 * @param {Object} renderer
5954 * @private
5955 */
5956TilingSprite.prototype._renderWebGL = function(renderer) {
5957 if (this._bitmap) {
5958 this._bitmap.touch();
5959 }
5960 if (this.texture.frame.width > 0 && this.texture.frame.height > 0) {
5961 if (this._bitmap) {
5962 this._bitmap.checkDirty();
5963 }
5964 this._renderWebGL_PIXI(renderer);
5965 }
5966};
5967
5968/**
5969 * The image for the tiling sprite.
5970 *
5971 * @property bitmap
5972 * @type Bitmap
5973 */
5974Object.defineProperty(TilingSprite.prototype, 'bitmap', {
5975 get: function() {
5976 return this._bitmap;
5977 },
5978 set: function(value) {
5979 if (this._bitmap !== value) {
5980 this._bitmap = value;
5981 if (this._bitmap) {
5982 this._bitmap.addLoadListener(this._onBitmapLoad.bind(this));
5983 } else {
5984 this.texture.frame = Rectangle.emptyRectangle;
5985 }
5986 }
5987 },
5988 configurable: true
5989});
5990
5991/**
5992 * The opacity of the tiling sprite (0 to 255).
5993 *
5994 * @property opacity
5995 * @type Number
5996 */
5997Object.defineProperty(TilingSprite.prototype, 'opacity', {
5998 get: function() {
5999 return this.alpha * 255;
6000 },
6001 set: function(value) {
6002 this.alpha = value.clamp(0, 255) / 255;
6003 },
6004 configurable: true
6005});
6006
6007/**
6008 * Updates the tiling sprite for each frame.
6009 *
6010 * @method update
6011 */
6012TilingSprite.prototype.update = function() {
6013 this.children.forEach(function(child) {
6014 if (child.update) {
6015 child.update();
6016 }
6017 });
6018};
6019
6020/**
6021 * Sets the x, y, width, and height all at once.
6022 *
6023 * @method move
6024 * @param {Number} x The x coordinate of the tiling sprite
6025 * @param {Number} y The y coordinate of the tiling sprite
6026 * @param {Number} width The width of the tiling sprite
6027 * @param {Number} height The height of the tiling sprite
6028 */
6029TilingSprite.prototype.move = function(x, y, width, height) {
6030 this.x = x || 0;
6031 this.y = y || 0;
6032 this._width = width || 0;
6033 this._height = height || 0;
6034};
6035
6036/**
6037 * Specifies the region of the image that the tiling sprite will use.
6038 *
6039 * @method setFrame
6040 * @param {Number} x The x coordinate of the frame
6041 * @param {Number} y The y coordinate of the frame
6042 * @param {Number} width The width of the frame
6043 * @param {Number} height The height of the frame
6044 */
6045TilingSprite.prototype.setFrame = function(x, y, width, height) {
6046 this._frame.x = x;
6047 this._frame.y = y;
6048 this._frame.width = width;
6049 this._frame.height = height;
6050 this._refresh();
6051};
6052
6053/**
6054 * @method updateTransform
6055 * @private
6056 */
6057TilingSprite.prototype.updateTransform = function() {
6058 this.tilePosition.x = Math.round(-this.origin.x);
6059 this.tilePosition.y = Math.round(-this.origin.y);
6060 this.updateTransformTS();
6061};
6062
6063TilingSprite.prototype.updateTransformTS = PIXI.extras.TilingSprite.prototype.updateTransform;
6064
6065/**
6066 * @method _onBitmapLoad
6067 * @private
6068 */
6069TilingSprite.prototype._onBitmapLoad = function() {
6070 this.texture.baseTexture = this._bitmap.baseTexture;
6071 this._refresh();
6072};
6073
6074/**
6075 * @method _refresh
6076 * @private
6077 */
6078TilingSprite.prototype._refresh = function() {
6079 var frame = this._frame.clone();
6080 if (frame.width === 0 && frame.height === 0 && this._bitmap) {
6081 frame.width = this._bitmap.width;
6082 frame.height = this._bitmap.height;
6083 }
6084 this.texture.frame = frame;
6085 this.texture._updateID++;
6086 this.tilingTexture = null;
6087};
6088
6089
6090TilingSprite.prototype._speedUpCustomBlendModes = Sprite.prototype._speedUpCustomBlendModes;
6091
6092/**
6093 * @method _renderWebGL
6094 * @param {Object} renderer
6095 * @private
6096 */
6097TilingSprite.prototype._renderWebGL = function(renderer) {
6098 if (this._bitmap) {
6099 this._bitmap.touch();
6100 this._bitmap.checkDirty();
6101 }
6102
6103 this._speedUpCustomBlendModes(renderer);
6104
6105 this._renderWebGL_PIXI(renderer);
6106};
6107
6108// The important members from Pixi.js
6109
6110/**
6111 * The visibility of the tiling sprite.
6112 *
6113 * @property visible
6114 * @type Boolean
6115 */
6116
6117/**
6118 * The x coordinate of the tiling sprite.
6119 *
6120 * @property x
6121 * @type Number
6122 */
6123
6124/**
6125 * The y coordinate of the tiling sprite.
6126 *
6127 * @property y
6128 * @type Number
6129 */
6130
6131//-----------------------------------------------------------------------------
6132/**
6133 * The sprite which covers the entire game screen.
6134 *
6135 * @class ScreenSprite
6136 * @constructor
6137 */
6138function ScreenSprite() {
6139 this.initialize.apply(this, arguments);
6140}
6141
6142ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
6143ScreenSprite.prototype.constructor = ScreenSprite;
6144
6145ScreenSprite.prototype.initialize = function () {
6146 PIXI.Container.call(this);
6147
6148 this._graphics = new PIXI.Graphics();
6149 this.addChild(this._graphics);
6150 this.opacity = 0;
6151
6152 this._red = -1;
6153 this._green = -1;
6154 this._blue = -1;
6155 this._colorText = '';
6156 this.setBlack();
6157};
6158
6159/**
6160 * The opacity of the sprite (0 to 255).
6161 *
6162 * @property opacity
6163 * @type Number
6164 */
6165Object.defineProperty(ScreenSprite.prototype, 'opacity', {
6166 get: function () {
6167 return this.alpha * 255;
6168 },
6169 set: function (value) {
6170 this.alpha = value.clamp(0, 255) / 255;
6171 },
6172 configurable: true
6173});
6174
6175ScreenSprite.YEPWarned = false;
6176ScreenSprite.warnYep = function () {
6177 if (!ScreenSprite.YEPWarned) {
6178 console.log("Deprecation warning. Please update YEP_CoreEngine. ScreenSprite is not a sprite, it has graphics inside.");
6179 ScreenSprite.YEPWarned = true;
6180 }
6181};
6182
6183Object.defineProperty(ScreenSprite.prototype, 'anchor', {
6184 get: function () {
6185 ScreenSprite.warnYep();
6186 this.scale.x = 1;
6187 this.scale.y = 1;
6188 return {x: 0, y: 0};
6189 },
6190 set: function (value) {
6191 this.alpha = value.clamp(0, 255) / 255;
6192 },
6193 configurable: true
6194});
6195
6196Object.defineProperty(ScreenSprite.prototype, 'blendMode', {
6197 get: function () {
6198 return this._graphics.blendMode;
6199 },
6200 set: function (value) {
6201 this._graphics.blendMode = value;
6202 },
6203 configurable: true
6204});
6205
6206/**
6207 * Sets black to the color of the screen sprite.
6208 *
6209 * @method setBlack
6210 */
6211ScreenSprite.prototype.setBlack = function () {
6212 this.setColor(0, 0, 0);
6213};
6214
6215/**
6216 * Sets white to the color of the screen sprite.
6217 *
6218 * @method setWhite
6219 */
6220ScreenSprite.prototype.setWhite = function () {
6221 this.setColor(255, 255, 255);
6222};
6223
6224/**
6225 * Sets the color of the screen sprite by values.
6226 *
6227 * @method setColor
6228 * @param {Number} r The red value in the range (0, 255)
6229 * @param {Number} g The green value in the range (0, 255)
6230 * @param {Number} b The blue value in the range (0, 255)
6231 */
6232ScreenSprite.prototype.setColor = function (r, g, b) {
6233 if (this._red !== r || this._green !== g || this._blue !== b) {
6234 r = Math.round(r || 0).clamp(0, 255);
6235 g = Math.round(g || 0).clamp(0, 255);
6236 b = Math.round(b || 0).clamp(0, 255);
6237 this._red = r;
6238 this._green = g;
6239 this._blue = b;
6240 this._colorText = Utils.rgbToCssColor(r, g, b);
6241
6242 var graphics = this._graphics;
6243 graphics.clear();
6244 var intColor = (r << 16) | (g << 8) | b;
6245 graphics.beginFill(intColor, 1);
6246 //whole screen with zoom. BWAHAHAHAHA
6247 graphics.drawRect(-Graphics.width * 5, -Graphics.height * 5, Graphics.width * 10, Graphics.height * 10);
6248 }
6249};
6250
6251//-----------------------------------------------------------------------------
6252/**
6253 * The window in the game.
6254 *
6255 * @class Window
6256 * @constructor
6257 */
6258function Window() {
6259 this.initialize.apply(this, arguments);
6260}
6261
6262Window.prototype = Object.create(PIXI.Container.prototype);
6263Window.prototype.constructor = Window;
6264
6265Window.prototype.initialize = function() {
6266 PIXI.Container.call(this);
6267
6268 this._isWindow = true;
6269 this._windowskin = null;
6270 this._width = 0;
6271 this._height = 0;
6272 this._cursorRect = new Rectangle();
6273 this._openness = 255;
6274 this._animationCount = 0;
6275
6276 this._padding = 18;
6277 this._margin = 4;
6278 this._colorTone = [0, 0, 0];
6279
6280 this._windowSpriteContainer = null;
6281 this._windowBackSprite = null;
6282 this._windowCursorSprite = null;
6283 this._windowFrameSprite = null;
6284 this._windowContentsSprite = null;
6285 this._windowArrowSprites = [];
6286 this._windowPauseSignSprite = null;
6287
6288 this._createAllParts();
6289
6290 /**
6291 * The origin point of the window for scrolling.
6292 *
6293 * @property origin
6294 * @type Point
6295 */
6296 this.origin = new Point();
6297
6298 /**
6299 * The active state for the window.
6300 *
6301 * @property active
6302 * @type Boolean
6303 */
6304 this.active = true;
6305
6306 /**
6307 * The visibility of the down scroll arrow.
6308 *
6309 * @property downArrowVisible
6310 * @type Boolean
6311 */
6312 this.downArrowVisible = false;
6313
6314 /**
6315 * The visibility of the up scroll arrow.
6316 *
6317 * @property upArrowVisible
6318 * @type Boolean
6319 */
6320 this.upArrowVisible = false;
6321
6322 /**
6323 * The visibility of the pause sign.
6324 *
6325 * @property pause
6326 * @type Boolean
6327 */
6328 this.pause = false;
6329};
6330
6331/**
6332 * The image used as a window skin.
6333 *
6334 * @property windowskin
6335 * @type Bitmap
6336 */
6337Object.defineProperty(Window.prototype, 'windowskin', {
6338 get: function() {
6339 return this._windowskin;
6340 },
6341 set: function(value) {
6342 if (this._windowskin !== value) {
6343 this._windowskin = value;
6344 this._windowskin.addLoadListener(this._onWindowskinLoad.bind(this));
6345 }
6346 },
6347 configurable: true
6348});
6349
6350/**
6351 * The bitmap used for the window contents.
6352 *
6353 * @property contents
6354 * @type Bitmap
6355 */
6356Object.defineProperty(Window.prototype, 'contents', {
6357 get: function() {
6358 return this._windowContentsSprite.bitmap;
6359 },
6360 set: function(value) {
6361 this._windowContentsSprite.bitmap = value;
6362 },
6363 configurable: true
6364});
6365
6366/**
6367 * The width of the window in pixels.
6368 *
6369 * @property width
6370 * @type Number
6371 */
6372Object.defineProperty(Window.prototype, 'width', {
6373 get: function() {
6374 return this._width;
6375 },
6376 set: function(value) {
6377 this._width = value;
6378 this._refreshAllParts();
6379 },
6380 configurable: true
6381});
6382
6383/**
6384 * The height of the window in pixels.
6385 *
6386 * @property height
6387 * @type Number
6388 */
6389Object.defineProperty(Window.prototype, 'height', {
6390 get: function() {
6391 return this._height;
6392 },
6393 set: function(value) {
6394 this._height = value;
6395 this._refreshAllParts();
6396 },
6397 configurable: true
6398});
6399
6400/**
6401 * The size of the padding between the frame and contents.
6402 *
6403 * @property padding
6404 * @type Number
6405 */
6406Object.defineProperty(Window.prototype, 'padding', {
6407 get: function() {
6408 return this._padding;
6409 },
6410 set: function(value) {
6411 this._padding = value;
6412 this._refreshAllParts();
6413 },
6414 configurable: true
6415});
6416
6417/**
6418 * The size of the margin for the window background.
6419 *
6420 * @property margin
6421 * @type Number
6422 */
6423Object.defineProperty(Window.prototype, 'margin', {
6424 get: function() {
6425 return this._margin;
6426 },
6427 set: function(value) {
6428 this._margin = value;
6429 this._refreshAllParts();
6430 },
6431 configurable: true
6432});
6433
6434/**
6435 * The opacity of the window without contents (0 to 255).
6436 *
6437 * @property opacity
6438 * @type Number
6439 */
6440Object.defineProperty(Window.prototype, 'opacity', {
6441 get: function() {
6442 return this._windowSpriteContainer.alpha * 255;
6443 },
6444 set: function(value) {
6445 this._windowSpriteContainer.alpha = value.clamp(0, 255) / 255;
6446 },
6447 configurable: true
6448});
6449
6450/**
6451 * The opacity of the window background (0 to 255).
6452 *
6453 * @property backOpacity
6454 * @type Number
6455 */
6456Object.defineProperty(Window.prototype, 'backOpacity', {
6457 get: function() {
6458 return this._windowBackSprite.alpha * 255;
6459 },
6460 set: function(value) {
6461 this._windowBackSprite.alpha = value.clamp(0, 255) / 255;
6462 },
6463 configurable: true
6464});
6465
6466/**
6467 * The opacity of the window contents (0 to 255).
6468 *
6469 * @property contentsOpacity
6470 * @type Number
6471 */
6472Object.defineProperty(Window.prototype, 'contentsOpacity', {
6473 get: function() {
6474 return this._windowContentsSprite.alpha * 255;
6475 },
6476 set: function(value) {
6477 this._windowContentsSprite.alpha = value.clamp(0, 255) / 255;
6478 },
6479 configurable: true
6480});
6481
6482/**
6483 * The openness of the window (0 to 255).
6484 *
6485 * @property openness
6486 * @type Number
6487 */
6488Object.defineProperty(Window.prototype, 'openness', {
6489 get: function() {
6490 return this._openness;
6491 },
6492 set: function(value) {
6493 if (this._openness !== value) {
6494 this._openness = value.clamp(0, 255);
6495 this._windowSpriteContainer.scale.y = this._openness / 255;
6496 this._windowSpriteContainer.y = this.height / 2 * (1 - this._openness / 255);
6497 }
6498 },
6499 configurable: true
6500});
6501
6502/**
6503 * Updates the window for each frame.
6504 *
6505 * @method update
6506 */
6507Window.prototype.update = function() {
6508 if (this.active) {
6509 this._animationCount++;
6510 }
6511 this.children.forEach(function(child) {
6512 if (child.update) {
6513 child.update();
6514 }
6515 });
6516};
6517
6518/**
6519 * Sets the x, y, width, and height all at once.
6520 *
6521 * @method move
6522 * @param {Number} x The x coordinate of the window
6523 * @param {Number} y The y coordinate of the window
6524 * @param {Number} width The width of the window
6525 * @param {Number} height The height of the window
6526 */
6527Window.prototype.move = function(x, y, width, height) {
6528 this.x = x || 0;
6529 this.y = y || 0;
6530 if (this._width !== width || this._height !== height) {
6531 this._width = width || 0;
6532 this._height = height || 0;
6533 this._refreshAllParts();
6534 }
6535};
6536
6537/**
6538 * Returns true if the window is completely open (openness == 255).
6539 *
6540 * @method isOpen
6541 */
6542Window.prototype.isOpen = function() {
6543 return this._openness >= 255;
6544};
6545
6546/**
6547 * Returns true if the window is completely closed (openness == 0).
6548 *
6549 * @method isClosed
6550 */
6551Window.prototype.isClosed = function() {
6552 return this._openness <= 0;
6553};
6554
6555/**
6556 * Sets the position of the command cursor.
6557 *
6558 * @method setCursorRect
6559 * @param {Number} x The x coordinate of the cursor
6560 * @param {Number} y The y coordinate of the cursor
6561 * @param {Number} width The width of the cursor
6562 * @param {Number} height The height of the cursor
6563 */
6564Window.prototype.setCursorRect = function(x, y, width, height) {
6565 var cx = Math.floor(x || 0);
6566 var cy = Math.floor(y || 0);
6567 var cw = Math.floor(width || 0);
6568 var ch = Math.floor(height || 0);
6569 var rect = this._cursorRect;
6570 if (rect.x !== cx || rect.y !== cy || rect.width !== cw || rect.height !== ch) {
6571 this._cursorRect.x = cx;
6572 this._cursorRect.y = cy;
6573 this._cursorRect.width = cw;
6574 this._cursorRect.height = ch;
6575 this._refreshCursor();
6576 }
6577};
6578
6579/**
6580 * Changes the color of the background.
6581 *
6582 * @method setTone
6583 * @param {Number} r The red value in the range (-255, 255)
6584 * @param {Number} g The green value in the range (-255, 255)
6585 * @param {Number} b The blue value in the range (-255, 255)
6586 */
6587Window.prototype.setTone = function(r, g, b) {
6588 var tone = this._colorTone;
6589 if (r !== tone[0] || g !== tone[1] || b !== tone[2]) {
6590 this._colorTone = [r, g, b];
6591 this._refreshBack();
6592 }
6593};
6594
6595/**
6596 * Adds a child between the background and contents.
6597 *
6598 * @method addChildToBack
6599 * @param {Object} child The child to add
6600 * @return {Object} The child that was added
6601 */
6602Window.prototype.addChildToBack = function(child) {
6603 var containerIndex = this.children.indexOf(this._windowSpriteContainer);
6604 return this.addChildAt(child, containerIndex + 1);
6605};
6606
6607/**
6608 * @method updateTransform
6609 * @private
6610 */
6611Window.prototype.updateTransform = function() {
6612 this._updateCursor();
6613 this._updateArrows();
6614 this._updatePauseSign();
6615 this._updateContents();
6616 PIXI.Container.prototype.updateTransform.call(this);
6617};
6618
6619/**
6620 * @method _createAllParts
6621 * @private
6622 */
6623Window.prototype._createAllParts = function() {
6624 this._windowSpriteContainer = new PIXI.Container();
6625 this._windowBackSprite = new Sprite();
6626 this._windowCursorSprite = new Sprite();
6627 this._windowFrameSprite = new Sprite();
6628 this._windowContentsSprite = new Sprite();
6629 this._downArrowSprite = new Sprite();
6630 this._upArrowSprite = new Sprite();
6631 this._windowPauseSignSprite = new Sprite();
6632 this._windowBackSprite.bitmap = new Bitmap(1, 1);
6633 this._windowBackSprite.alpha = 192 / 255;
6634 this.addChild(this._windowSpriteContainer);
6635 this._windowSpriteContainer.addChild(this._windowBackSprite);
6636 this._windowSpriteContainer.addChild(this._windowFrameSprite);
6637 this.addChild(this._windowCursorSprite);
6638 this.addChild(this._windowContentsSprite);
6639 this.addChild(this._downArrowSprite);
6640 this.addChild(this._upArrowSprite);
6641 this.addChild(this._windowPauseSignSprite);
6642};
6643
6644/**
6645 * @method _onWindowskinLoad
6646 * @private
6647 */
6648Window.prototype._onWindowskinLoad = function() {
6649 this._refreshAllParts();
6650};
6651
6652/**
6653 * @method _refreshAllParts
6654 * @private
6655 */
6656Window.prototype._refreshAllParts = function() {
6657 this._refreshBack();
6658 this._refreshFrame();
6659 this._refreshCursor();
6660 this._refreshContents();
6661 this._refreshArrows();
6662 this._refreshPauseSign();
6663};
6664
6665/**
6666 * @method _refreshBack
6667 * @private
6668 */
6669Window.prototype._refreshBack = function() {
6670 var m = this._margin;
6671 var w = this._width - m * 2;
6672 var h = this._height - m * 2;
6673 var bitmap = new Bitmap(w, h);
6674
6675 this._windowBackSprite.bitmap = bitmap;
6676 this._windowBackSprite.setFrame(0, 0, w, h);
6677 this._windowBackSprite.move(m, m);
6678
6679 if (w > 0 && h > 0 && this._windowskin) {
6680 var p = 96;
6681 bitmap.blt(this._windowskin, 0, 0, p, p, 0, 0, w, h);
6682 for (var y = 0; y < h; y += p) {
6683 for (var x = 0; x < w; x += p) {
6684 bitmap.blt(this._windowskin, 0, p, p, p, x, y, p, p);
6685 }
6686 }
6687 var tone = this._colorTone;
6688 bitmap.adjustTone(tone[0], tone[1], tone[2]);
6689 }
6690};
6691
6692/**
6693 * @method _refreshFrame
6694 * @private
6695 */
6696Window.prototype._refreshFrame = function() {
6697 var w = this._width;
6698 var h = this._height;
6699 var m = 24;
6700 var bitmap = new Bitmap(w, h);
6701
6702 this._windowFrameSprite.bitmap = bitmap;
6703 this._windowFrameSprite.setFrame(0, 0, w, h);
6704
6705 if (w > 0 && h > 0 && this._windowskin) {
6706 var skin = this._windowskin;
6707 var p = 96;
6708 var q = 96;
6709 bitmap.blt(skin, p+m, 0+0, p-m*2, m, m, 0, w-m*2, m);
6710 bitmap.blt(skin, p+m, 0+q-m, p-m*2, m, m, h-m, w-m*2, m);
6711 bitmap.blt(skin, p+0, 0+m, m, p-m*2, 0, m, m, h-m*2);
6712 bitmap.blt(skin, p+q-m, 0+m, m, p-m*2, w-m, m, m, h-m*2);
6713 bitmap.blt(skin, p+0, 0+0, m, m, 0, 0, m, m);
6714 bitmap.blt(skin, p+q-m, 0+0, m, m, w-m, 0, m, m);
6715 bitmap.blt(skin, p+0, 0+q-m, m, m, 0, h-m, m, m);
6716 bitmap.blt(skin, p+q-m, 0+q-m, m, m, w-m, h-m, m, m);
6717 }
6718};
6719
6720/**
6721 * @method _refreshCursor
6722 * @private
6723 */
6724Window.prototype._refreshCursor = function() {
6725 var pad = this._padding;
6726 var x = this._cursorRect.x + pad - this.origin.x;
6727 var y = this._cursorRect.y + pad - this.origin.y;
6728 var w = this._cursorRect.width;
6729 var h = this._cursorRect.height;
6730 var m = 4;
6731 var x2 = Math.max(x, pad);
6732 var y2 = Math.max(y, pad);
6733 var ox = x - x2;
6734 var oy = y - y2;
6735 var w2 = Math.min(w, this._width - pad - x2);
6736 var h2 = Math.min(h, this._height - pad - y2);
6737 var bitmap = new Bitmap(w2, h2);
6738
6739 this._windowCursorSprite.bitmap = bitmap;
6740 this._windowCursorSprite.setFrame(0, 0, w2, h2);
6741 this._windowCursorSprite.move(x2, y2);
6742
6743 if (w > 0 && h > 0 && this._windowskin) {
6744 var skin = this._windowskin;
6745 var p = 96;
6746 var q = 48;
6747 bitmap.blt(skin, p+m, p+m, q-m*2, q-m*2, ox+m, oy+m, w-m*2, h-m*2);
6748 bitmap.blt(skin, p+m, p+0, q-m*2, m, ox+m, oy+0, w-m*2, m);
6749 bitmap.blt(skin, p+m, p+q-m, q-m*2, m, ox+m, oy+h-m, w-m*2, m);
6750 bitmap.blt(skin, p+0, p+m, m, q-m*2, ox+0, oy+m, m, h-m*2);
6751 bitmap.blt(skin, p+q-m, p+m, m, q-m*2, ox+w-m, oy+m, m, h-m*2);
6752 bitmap.blt(skin, p+0, p+0, m, m, ox+0, oy+0, m, m);
6753 bitmap.blt(skin, p+q-m, p+0, m, m, ox+w-m, oy+0, m, m);
6754 bitmap.blt(skin, p+0, p+q-m, m, m, ox+0, oy+h-m, m, m);
6755 bitmap.blt(skin, p+q-m, p+q-m, m, m, ox+w-m, oy+h-m, m, m);
6756 }
6757};
6758
6759/**
6760 * @method _refreshContents
6761 * @private
6762 */
6763Window.prototype._refreshContents = function() {
6764 this._windowContentsSprite.move(this.padding, this.padding);
6765};
6766
6767/**
6768 * @method _refreshArrows
6769 * @private
6770 */
6771Window.prototype._refreshArrows = function() {
6772 var w = this._width;
6773 var h = this._height;
6774 var p = 24;
6775 var q = p/2;
6776 var sx = 96+p;
6777 var sy = 0+p;
6778 this._downArrowSprite.bitmap = this._windowskin;
6779 this._downArrowSprite.anchor.x = 0.5;
6780 this._downArrowSprite.anchor.y = 0.5;
6781 this._downArrowSprite.setFrame(sx+q, sy+q+p, p, q);
6782 this._downArrowSprite.move(w/2, h-q);
6783 this._upArrowSprite.bitmap = this._windowskin;
6784 this._upArrowSprite.anchor.x = 0.5;
6785 this._upArrowSprite.anchor.y = 0.5;
6786 this._upArrowSprite.setFrame(sx+q, sy, p, q);
6787 this._upArrowSprite.move(w/2, q);
6788};
6789
6790/**
6791 * @method _refreshPauseSign
6792 * @private
6793 */
6794Window.prototype._refreshPauseSign = function() {
6795 var sx = 144;
6796 var sy = 96;
6797 var p = 24;
6798 this._windowPauseSignSprite.bitmap = this._windowskin;
6799 this._windowPauseSignSprite.anchor.x = 0.5;
6800 this._windowPauseSignSprite.anchor.y = 1;
6801 this._windowPauseSignSprite.move(this._width / 2, this._height);
6802 this._windowPauseSignSprite.setFrame(sx, sy, p, p);
6803 this._windowPauseSignSprite.alpha = 0;
6804};
6805
6806/**
6807 * @method _updateCursor
6808 * @private
6809 */
6810Window.prototype._updateCursor = function() {
6811 var blinkCount = this._animationCount % 40;
6812 var cursorOpacity = this.contentsOpacity;
6813 if (this.active) {
6814 if (blinkCount < 20) {
6815 cursorOpacity -= blinkCount * 8;
6816 } else {
6817 cursorOpacity -= (40 - blinkCount) * 8;
6818 }
6819 }
6820 this._windowCursorSprite.alpha = cursorOpacity / 255;
6821 this._windowCursorSprite.visible = this.isOpen();
6822};
6823
6824/**
6825 * @method _updateContents
6826 * @private
6827 */
6828Window.prototype._updateContents = function() {
6829 var w = this._width - this._padding * 2;
6830 var h = this._height - this._padding * 2;
6831 if (w > 0 && h > 0) {
6832 this._windowContentsSprite.setFrame(this.origin.x, this.origin.y, w, h);
6833 this._windowContentsSprite.visible = this.isOpen();
6834 } else {
6835 this._windowContentsSprite.visible = false;
6836 }
6837};
6838
6839/**
6840 * @method _updateArrows
6841 * @private
6842 */
6843Window.prototype._updateArrows = function() {
6844 this._downArrowSprite.visible = this.isOpen() && this.downArrowVisible;
6845 this._upArrowSprite.visible = this.isOpen() && this.upArrowVisible;
6846};
6847
6848/**
6849 * @method _updatePauseSign
6850 * @private
6851 */
6852Window.prototype._updatePauseSign = function() {
6853 var sprite = this._windowPauseSignSprite;
6854 var x = Math.floor(this._animationCount / 16) % 2;
6855 var y = Math.floor(this._animationCount / 16 / 2) % 2;
6856 var sx = 144;
6857 var sy = 96;
6858 var p = 24;
6859 if (!this.pause) {
6860 sprite.alpha = 0;
6861 } else if (sprite.alpha < 1) {
6862 sprite.alpha = Math.min(sprite.alpha + 0.1, 1);
6863 }
6864 sprite.setFrame(sx+x*p, sy+y*p, p, p);
6865 sprite.visible = this.isOpen();
6866};
6867
6868// The important members from Pixi.js
6869
6870/**
6871 * The visibility of the window.
6872 *
6873 * @property visible
6874 * @type Boolean
6875 */
6876
6877/**
6878 * The x coordinate of the window.
6879 *
6880 * @property x
6881 * @type Number
6882 */
6883
6884/**
6885 * The y coordinate of the window.
6886 *
6887 * @property y
6888 * @type Number
6889 */
6890
6891/**
6892 * [read-only] The array of children of the window.
6893 *
6894 * @property children
6895 * @type Array
6896 */
6897
6898/**
6899 * [read-only] The object that contains the window.
6900 *
6901 * @property parent
6902 * @type Object
6903 */
6904
6905/**
6906 * Adds a child to the container.
6907 *
6908 * @method addChild
6909 * @param {Object} child The child to add
6910 * @return {Object} The child that was added
6911 */
6912
6913/**
6914 * Adds a child to the container at a specified index.
6915 *
6916 * @method addChildAt
6917 * @param {Object} child The child to add
6918 * @param {Number} index The index to place the child in
6919 * @return {Object} The child that was added
6920 */
6921
6922/**
6923 * Removes a child from the container.
6924 *
6925 * @method removeChild
6926 * @param {Object} child The child to remove
6927 * @return {Object} The child that was removed
6928 */
6929
6930/**
6931 * Removes a child from the specified index position.
6932 *
6933 * @method removeChildAt
6934 * @param {Number} index The index to get the child from
6935 * @return {Object} The child that was removed
6936 */
6937
6938//-----------------------------------------------------------------------------
6939/**
6940 * The layer which contains game windows.
6941 *
6942 * @class WindowLayer
6943 * @constructor
6944 */
6945function WindowLayer() {
6946 this.initialize.apply(this, arguments);
6947}
6948
6949WindowLayer.prototype = Object.create(PIXI.Container.prototype);
6950WindowLayer.prototype.constructor = WindowLayer;
6951
6952WindowLayer.prototype.initialize = function() {
6953 PIXI.Container.call(this);
6954 this._width = 0;
6955 this._height = 0;
6956 this._tempCanvas = null;
6957 this._translationMatrix = [1, 0, 0, 0, 1, 0, 0, 0, 1];
6958
6959 this._windowMask = new PIXI.Graphics();
6960 this._windowMask.beginFill(0xffffff, 1);
6961 this._windowMask.drawRect(0, 0, 0, 0);
6962 this._windowMask.endFill();
6963 this._windowRect = this._windowMask.graphicsData[0].shape;
6964
6965 this._renderSprite = null;
6966 this.filterArea = new PIXI.Rectangle();
6967 this.filters = [WindowLayer.voidFilter];
6968
6969 //temporary fix for memory leak bug
6970 this.on('removed', this.onRemoveAsAChild);
6971};
6972
6973WindowLayer.prototype.onRemoveAsAChild = function() {
6974 this.removeChildren();
6975}
6976
6977WindowLayer.voidFilter = new PIXI.filters.VoidFilter();
6978
6979/**
6980 * The width of the window layer in pixels.
6981 *
6982 * @property width
6983 * @type Number
6984 */
6985Object.defineProperty(WindowLayer.prototype, 'width', {
6986 get: function() {
6987 return this._width;
6988 },
6989 set: function(value) {
6990 this._width = value;
6991 },
6992 configurable: true
6993});
6994
6995/**
6996 * The height of the window layer in pixels.
6997 *
6998 * @property height
6999 * @type Number
7000 */
7001Object.defineProperty(WindowLayer.prototype, 'height', {
7002 get: function() {
7003 return this._height;
7004 },
7005 set: function(value) {
7006 this._height = value;
7007 },
7008 configurable: true
7009});
7010
7011/**
7012 * Sets the x, y, width, and height all at once.
7013 *
7014 * @method move
7015 * @param {Number} x The x coordinate of the window layer
7016 * @param {Number} y The y coordinate of the window layer
7017 * @param {Number} width The width of the window layer
7018 * @param {Number} height The height of the window layer
7019 */
7020WindowLayer.prototype.move = function(x, y, width, height) {
7021 this.x = x;
7022 this.y = y;
7023 this.width = width;
7024 this.height = height;
7025};
7026
7027/**
7028 * Updates the window layer for each frame.
7029 *
7030 * @method update
7031 */
7032WindowLayer.prototype.update = function() {
7033 this.children.forEach(function(child) {
7034 if (child.update) {
7035 child.update();
7036 }
7037 });
7038};
7039
7040/**
7041 * @method _renderCanvas
7042 * @param {Object} renderSession
7043 * @private
7044 */
7045WindowLayer.prototype.renderCanvas = function(renderer) {
7046 if (!this.visible || !this.renderable) {
7047 return;
7048 }
7049
7050 if (!this._tempCanvas) {
7051 this._tempCanvas = document.createElement('canvas');
7052 }
7053
7054 this._tempCanvas.width = Graphics.width;
7055 this._tempCanvas.height = Graphics.height;
7056
7057 var realCanvasContext = renderer.context;
7058 var context = this._tempCanvas.getContext('2d');
7059
7060 context.save();
7061 context.clearRect(0, 0, Graphics.width, Graphics.height);
7062 context.beginPath();
7063 context.rect(this.x, this.y, this.width, this.height);
7064 context.closePath();
7065 context.clip();
7066
7067 renderer.context = context;
7068
7069 for (var i = 0; i < this.children.length; i++) {
7070 var child = this.children[i];
7071 if (child._isWindow && child.visible && child.openness > 0) {
7072 this._canvasClearWindowRect(renderer, child);
7073 context.save();
7074 child.renderCanvas(renderer);
7075 context.restore();
7076 }
7077 }
7078
7079 context.restore();
7080
7081 renderer.context = realCanvasContext;
7082 renderer.context.setTransform(1, 0, 0, 1, 0, 0);
7083 renderer.context.globalCompositeOperation = 'source-over';
7084 renderer.context.globalAlpha = 1;
7085 renderer.context.drawImage(this._tempCanvas, 0, 0);
7086
7087 for (var j = 0; j < this.children.length; j++) {
7088 if (!this.children[j]._isWindow) {
7089 this.children[j].renderCanvas(renderer);
7090 }
7091 }
7092};
7093
7094/**
7095 * @method _canvasClearWindowRect
7096 * @param {Object} renderSession
7097 * @param {Window} window
7098 * @private
7099 */
7100WindowLayer.prototype._canvasClearWindowRect = function(renderSession, window) {
7101 var rx = this.x + window.x;
7102 var ry = this.y + window.y + window.height / 2 * (1 - window._openness / 255);
7103 var rw = window.width;
7104 var rh = window.height * window._openness / 255;
7105 renderSession.context.clearRect(rx, ry, rw, rh);
7106};
7107
7108/**
7109 * @method _renderWebGL
7110 * @param {Object} renderSession
7111 * @private
7112 */
7113WindowLayer.prototype.renderWebGL = function(renderer) {
7114 if (!this.visible || !this.renderable) {
7115 return;
7116 }
7117
7118 if (this.children.length==0) {
7119 return;
7120 }
7121
7122 renderer.flush();
7123 this.filterArea.copy(this);
7124 renderer.filterManager.pushFilter(this, this.filters);
7125 renderer.currentRenderer.start();
7126
7127 var shift = new PIXI.Point();
7128 var rt = renderer._activeRenderTarget;
7129 var projectionMatrix = rt.projectionMatrix;
7130 shift.x = Math.round((projectionMatrix.tx + 1) / 2 * rt.sourceFrame.width);
7131 shift.y = Math.round((projectionMatrix.ty + 1) / 2 * rt.sourceFrame.height);
7132
7133 for (var i = 0; i < this.children.length; i++) {
7134 var child = this.children[i];
7135 if (child._isWindow && child.visible && child.openness > 0) {
7136 this._maskWindow(child, shift);
7137 renderer.maskManager.pushScissorMask(this, this._windowMask);
7138 renderer.clear();
7139 renderer.maskManager.popScissorMask();
7140 renderer.currentRenderer.start();
7141 child.renderWebGL(renderer);
7142 renderer.currentRenderer.flush();
7143 }
7144 }
7145
7146 renderer.flush();
7147 renderer.filterManager.popFilter();
7148 renderer.maskManager.popScissorMask();
7149
7150 for (var j = 0; j < this.children.length; j++) {
7151 if (!this.children[j]._isWindow) {
7152 this.children[j].renderWebGL(renderer);
7153 }
7154 }
7155};
7156
7157/**
7158 * @method _maskWindow
7159 * @param {Window} window
7160 * @private
7161 */
7162WindowLayer.prototype._maskWindow = function(window, shift) {
7163 this._windowMask._currentBounds = null;
7164 this._windowMask.boundsDirty = true;
7165 var rect = this._windowRect;
7166 rect.x = this.x + shift.x + window.x;
7167 rect.y = this.x + shift.y + window.y + window.height / 2 * (1 - window._openness / 255);
7168 rect.width = window.width;
7169 rect.height = window.height * window._openness / 255;
7170};
7171
7172// The important members from Pixi.js
7173
7174/**
7175 * The x coordinate of the window layer.
7176 *
7177 * @property x
7178 * @type Number
7179 */
7180
7181/**
7182 * The y coordinate of the window layer.
7183 *
7184 * @property y
7185 * @type Number
7186 */
7187
7188/**
7189 * [read-only] The array of children of the window layer.
7190 *
7191 * @property children
7192 * @type Array
7193 */
7194
7195/**
7196 * [read-only] The object that contains the window layer.
7197 *
7198 * @property parent
7199 * @type Object
7200 */
7201
7202/**
7203 * Adds a child to the container.
7204 *
7205 * @method addChild
7206 * @param {Object} child The child to add
7207 * @return {Object} The child that was added
7208 */
7209
7210/**
7211 * Adds a child to the container at a specified index.
7212 *
7213 * @method addChildAt
7214 * @param {Object} child The child to add
7215 * @param {Number} index The index to place the child in
7216 * @return {Object} The child that was added
7217 */
7218
7219/**
7220 * Removes a child from the container.
7221 *
7222 * @method removeChild
7223 * @param {Object} child The child to remove
7224 * @return {Object} The child that was removed
7225 */
7226
7227/**
7228 * Removes a child from the specified index position.
7229 *
7230 * @method removeChildAt
7231 * @param {Number} index The index to get the child from
7232 * @return {Object} The child that was removed
7233 */
7234
7235//-----------------------------------------------------------------------------
7236/**
7237 * The weather effect which displays rain, storm, or snow.
7238 *
7239 * @class Weather
7240 * @constructor
7241 */
7242function Weather() {
7243 this.initialize.apply(this, arguments);
7244}
7245
7246Weather.prototype = Object.create(PIXI.Container.prototype);
7247Weather.prototype.constructor = Weather;
7248
7249Weather.prototype.initialize = function() {
7250 PIXI.Container.call(this);
7251
7252 this._width = Graphics.width;
7253 this._height = Graphics.height;
7254 this._sprites = [];
7255
7256 this._createBitmaps();
7257 this._createDimmer();
7258
7259 /**
7260 * The type of the weather in ['none', 'rain', 'storm', 'snow'].
7261 *
7262 * @property type
7263 * @type String
7264 */
7265 this.type = 'none';
7266
7267 /**
7268 * The power of the weather in the range (0, 9).
7269 *
7270 * @property power
7271 * @type Number
7272 */
7273 this.power = 0;
7274
7275 /**
7276 * The origin point of the weather for scrolling.
7277 *
7278 * @property origin
7279 * @type Point
7280 */
7281 this.origin = new Point();
7282};
7283
7284/**
7285 * Updates the weather for each frame.
7286 *
7287 * @method update
7288 */
7289Weather.prototype.update = function() {
7290 this._updateDimmer();
7291 this._updateAllSprites();
7292};
7293
7294/**
7295 * @method _createBitmaps
7296 * @private
7297 */
7298Weather.prototype._createBitmaps = function() {
7299 this._rainBitmap = new Bitmap(1, 60);
7300 this._rainBitmap.fillAll('white');
7301 this._stormBitmap = new Bitmap(2, 100);
7302 this._stormBitmap.fillAll('white');
7303 this._snowBitmap = new Bitmap(9, 9);
7304 this._snowBitmap.drawCircle(4, 4, 4, 'white');
7305};
7306
7307/**
7308 * @method _createDimmer
7309 * @private
7310 */
7311Weather.prototype._createDimmer = function() {
7312 this._dimmerSprite = new ScreenSprite();
7313 this._dimmerSprite.setColor(80, 80, 80);
7314 this.addChild(this._dimmerSprite);
7315};
7316
7317/**
7318 * @method _updateDimmer
7319 * @private
7320 */
7321Weather.prototype._updateDimmer = function() {
7322 this._dimmerSprite.opacity = Math.floor(this.power * 6);
7323};
7324
7325/**
7326 * @method _updateAllSprites
7327 * @private
7328 */
7329Weather.prototype._updateAllSprites = function() {
7330 var maxSprites = Math.floor(this.power * 10);
7331 while (this._sprites.length < maxSprites) {
7332 this._addSprite();
7333 }
7334 while (this._sprites.length > maxSprites) {
7335 this._removeSprite();
7336 }
7337 this._sprites.forEach(function(sprite) {
7338 this._updateSprite(sprite);
7339 sprite.x = sprite.ax - this.origin.x;
7340 sprite.y = sprite.ay - this.origin.y;
7341 }, this);
7342};
7343
7344/**
7345 * @method _addSprite
7346 * @private
7347 */
7348Weather.prototype._addSprite = function() {
7349 var sprite = new Sprite(this.viewport);
7350 sprite.opacity = 0;
7351 this._sprites.push(sprite);
7352 this.addChild(sprite);
7353};
7354
7355/**
7356 * @method _removeSprite
7357 * @private
7358 */
7359Weather.prototype._removeSprite = function() {
7360 this.removeChild(this._sprites.pop());
7361};
7362
7363/**
7364 * @method _updateSprite
7365 * @param {Sprite} sprite
7366 * @private
7367 */
7368Weather.prototype._updateSprite = function(sprite) {
7369 switch (this.type) {
7370 case 'rain':
7371 this._updateRainSprite(sprite);
7372 break;
7373 case 'storm':
7374 this._updateStormSprite(sprite);
7375 break;
7376 case 'snow':
7377 this._updateSnowSprite(sprite);
7378 break;
7379 }
7380 if (sprite.opacity < 40) {
7381 this._rebornSprite(sprite);
7382 }
7383};
7384
7385/**
7386 * @method _updateRainSprite
7387 * @param {Sprite} sprite
7388 * @private
7389 */
7390Weather.prototype._updateRainSprite = function(sprite) {
7391 sprite.bitmap = this._rainBitmap;
7392 sprite.rotation = Math.PI / 16;
7393 sprite.ax -= 6 * Math.sin(sprite.rotation);
7394 sprite.ay += 6 * Math.cos(sprite.rotation);
7395 sprite.opacity -= 6;
7396};
7397
7398/**
7399 * @method _updateStormSprite
7400 * @param {Sprite} sprite
7401 * @private
7402 */
7403Weather.prototype._updateStormSprite = function(sprite) {
7404 sprite.bitmap = this._stormBitmap;
7405 sprite.rotation = Math.PI / 8;
7406 sprite.ax -= 8 * Math.sin(sprite.rotation);
7407 sprite.ay += 8 * Math.cos(sprite.rotation);
7408 sprite.opacity -= 8;
7409};
7410
7411/**
7412 * @method _updateSnowSprite
7413 * @param {Sprite} sprite
7414 * @private
7415 */
7416Weather.prototype._updateSnowSprite = function(sprite) {
7417 sprite.bitmap = this._snowBitmap;
7418 sprite.rotation = Math.PI / 16;
7419 sprite.ax -= 3 * Math.sin(sprite.rotation);
7420 sprite.ay += 3 * Math.cos(sprite.rotation);
7421 sprite.opacity -= 3;
7422};
7423
7424/**
7425 * @method _rebornSprite
7426 * @param {Sprite} sprite
7427 * @private
7428 */
7429Weather.prototype._rebornSprite = function(sprite) {
7430 sprite.ax = Math.randomInt(Graphics.width + 100) - 100 + this.origin.x;
7431 sprite.ay = Math.randomInt(Graphics.height + 200) - 200 + this.origin.y;
7432 sprite.opacity = 160 + Math.randomInt(60);
7433};
7434
7435//-----------------------------------------------------------------------------
7436/**
7437 * The color matrix filter for WebGL.
7438 *
7439 * @class ToneFilter
7440 * @extends PIXI.Filter
7441 * @constructor
7442 */
7443function ToneFilter() {
7444 PIXI.filters.ColorMatrixFilter.call(this);
7445}
7446
7447ToneFilter.prototype = Object.create(PIXI.filters.ColorMatrixFilter.prototype);
7448ToneFilter.prototype.constructor = ToneFilter;
7449
7450/**
7451 * Changes the hue.
7452 *
7453 * @method adjustHue
7454 * @param {Number} value The hue value in the range (-360, 360)
7455 */
7456ToneFilter.prototype.adjustHue = function(value) {
7457 this.hue(value, true);
7458};
7459
7460/**
7461 * Changes the saturation.
7462 *
7463 * @method adjustSaturation
7464 * @param {Number} value The saturation value in the range (-255, 255)
7465 */
7466ToneFilter.prototype.adjustSaturation = function(value) {
7467 value = (value || 0).clamp(-255, 255) / 255;
7468 this.saturate(value, true);
7469};
7470
7471/**
7472 * Changes the tone.
7473 *
7474 * @method adjustTone
7475 * @param {Number} r The red strength in the range (-255, 255)
7476 * @param {Number} g The green strength in the range (-255, 255)
7477 * @param {Number} b The blue strength in the range (-255, 255)
7478 */
7479ToneFilter.prototype.adjustTone = function(r, g, b) {
7480 r = (r || 0).clamp(-255, 255) / 255;
7481 g = (g || 0).clamp(-255, 255) / 255;
7482 b = (b || 0).clamp(-255, 255) / 255;
7483
7484 if (r !== 0 || g !== 0 || b !== 0) {
7485 var matrix = [
7486 1, 0, 0, r, 0,
7487 0, 1, 0, g, 0,
7488 0, 0, 1, b, 0,
7489 0, 0, 0, 1, 0
7490 ];
7491
7492 this._loadMatrix(matrix, true);
7493 }
7494};
7495
7496//-----------------------------------------------------------------------------
7497/**
7498 * The sprite which changes the screen color in 2D canvas mode.
7499 *
7500 * @class ToneSprite
7501 * @constructor
7502 */
7503function ToneSprite() {
7504 this.initialize.apply(this, arguments);
7505}
7506
7507ToneSprite.prototype = Object.create(PIXI.Container.prototype);
7508ToneSprite.prototype.constructor = ToneSprite;
7509
7510ToneSprite.prototype.initialize = function() {
7511 PIXI.Container.call(this);
7512 this.clear();
7513};
7514
7515/**
7516 * Clears the tone.
7517 *
7518 * @method reset
7519 */
7520ToneSprite.prototype.clear = function() {
7521 this._red = 0;
7522 this._green = 0;
7523 this._blue = 0;
7524 this._gray = 0;
7525};
7526
7527/**
7528 * Sets the tone.
7529 *
7530 * @method setTone
7531 * @param {Number} r The red strength in the range (-255, 255)
7532 * @param {Number} g The green strength in the range (-255, 255)
7533 * @param {Number} b The blue strength in the range (-255, 255)
7534 * @param {Number} gray The grayscale level in the range (0, 255)
7535 */
7536ToneSprite.prototype.setTone = function(r, g, b, gray) {
7537 this._red = Math.round(r || 0).clamp(-255, 255);
7538 this._green = Math.round(g || 0).clamp(-255, 255);
7539 this._blue = Math.round(b || 0).clamp(-255, 255);
7540 this._gray = Math.round(gray || 0).clamp(0, 255);
7541};
7542
7543/**
7544 * @method _renderCanvas
7545 * @param {Object} renderSession
7546 * @private
7547 */
7548ToneSprite.prototype._renderCanvas = function(renderer) {
7549 if (this.visible) {
7550 var context = renderer.context;
7551 var t = this.worldTransform;
7552 var r = renderer.resolution;
7553 var width = Graphics.width;
7554 var height = Graphics.height;
7555 context.save();
7556 context.setTransform(t.a, t.b, t.c, t.d, t.tx * r, t.ty * r);
7557 if (Graphics.canUseSaturationBlend() && this._gray > 0) {
7558 context.globalCompositeOperation = 'saturation';
7559 context.globalAlpha = this._gray / 255;
7560 context.fillStyle = '#ffffff';
7561 context.fillRect(0, 0, width, height);
7562 }
7563 context.globalAlpha = 1;
7564 var r1 = Math.max(0, this._red);
7565 var g1 = Math.max(0, this._green);
7566 var b1 = Math.max(0, this._blue);
7567 if (r1 || g1 || b1) {
7568 context.globalCompositeOperation = 'lighter';
7569 context.fillStyle = Utils.rgbToCssColor(r1, g1, b1);
7570 context.fillRect(0, 0, width, height);
7571 }
7572 if (Graphics.canUseDifferenceBlend()) {
7573 var r2 = Math.max(0, -this._red);
7574 var g2 = Math.max(0, -this._green);
7575 var b2 = Math.max(0, -this._blue);
7576 if (r2 || g2 || b2) {
7577 context.globalCompositeOperation = 'difference';
7578 context.fillStyle = '#ffffff';
7579 context.fillRect(0, 0, width, height);
7580 context.globalCompositeOperation = 'lighter';
7581 context.fillStyle = Utils.rgbToCssColor(r2, g2, b2);
7582 context.fillRect(0, 0, width, height);
7583 context.globalCompositeOperation = 'difference';
7584 context.fillStyle = '#ffffff';
7585 context.fillRect(0, 0, width, height);
7586 }
7587 }
7588 context.restore();
7589 }
7590};
7591
7592/**
7593 * @method _renderWebGL
7594 * @param {Object} renderSession
7595 * @private
7596 */
7597ToneSprite.prototype._renderWebGL = function(renderer) {
7598 // Not supported
7599};
7600
7601//-----------------------------------------------------------------------------
7602/**
7603 * The root object of the display tree.
7604 *
7605 * @class Stage
7606 * @constructor
7607 */
7608function Stage() {
7609 this.initialize.apply(this, arguments);
7610}
7611
7612Stage.prototype = Object.create(PIXI.Container.prototype);
7613Stage.prototype.constructor = Stage;
7614
7615Stage.prototype.initialize = function() {
7616 PIXI.Container.call(this);
7617
7618 // The interactive flag causes a memory leak.
7619 this.interactive = false;
7620};
7621
7622/**
7623 * [read-only] The array of children of the stage.
7624 *
7625 * @property children
7626 * @type Array
7627 */
7628
7629/**
7630 * Adds a child to the container.
7631 *
7632 * @method addChild
7633 * @param {Object} child The child to add
7634 * @return {Object} The child that was added
7635 */
7636
7637/**
7638 * Adds a child to the container at a specified index.
7639 *
7640 * @method addChildAt
7641 * @param {Object} child The child to add
7642 * @param {Number} index The index to place the child in
7643 * @return {Object} The child that was added
7644 */
7645
7646/**
7647 * Removes a child from the container.
7648 *
7649 * @method removeChild
7650 * @param {Object} child The child to remove
7651 * @return {Object} The child that was removed
7652 */
7653
7654/**
7655 * Removes a child from the specified index position.
7656 *
7657 * @method removeChildAt
7658 * @param {Number} index The index to get the child from
7659 * @return {Object} The child that was removed
7660 */
7661
7662//-----------------------------------------------------------------------------
7663/**
7664 * The audio object of Web Audio API.
7665 *
7666 * @class WebAudio
7667 * @constructor
7668 * @param {String} url The url of the audio file
7669 */
7670function WebAudio() {
7671 this.initialize.apply(this, arguments);
7672}
7673
7674WebAudio._standAlone = (function(top){
7675 return !top.ResourceHandler;
7676})(this);
7677
7678WebAudio.prototype.initialize = function(url) {
7679 if (!WebAudio._initialized) {
7680 WebAudio.initialize();
7681 }
7682 this.clear();
7683
7684 if(!WebAudio._standAlone){
7685 this._loader = ResourceHandler.createLoader(url, this._load.bind(this, url), function() {
7686 this._hasError = true;
7687 }.bind(this));
7688 }
7689 this._load(url);
7690 this._url = url;
7691};
7692
7693WebAudio._masterVolume = 1;
7694WebAudio._context = null;
7695WebAudio._masterGainNode = null;
7696WebAudio._initialized = false;
7697WebAudio._unlocked = false;
7698
7699/**
7700 * Initializes the audio system.
7701 *
7702 * @static
7703 * @method initialize
7704 * @param {Boolean} noAudio Flag for the no-audio mode
7705 * @return {Boolean} True if the audio system is available
7706 */
7707WebAudio.initialize = function(noAudio) {
7708 if (!this._initialized) {
7709 if (!noAudio) {
7710 this._createContext();
7711 this._detectCodecs();
7712 this._createMasterGainNode();
7713 this._setupEventHandlers();
7714 }
7715 this._initialized = true;
7716 }
7717 return !!this._context;
7718};
7719
7720/**
7721 * Checks whether the browser can play ogg files.
7722 *
7723 * @static
7724 * @method canPlayOgg
7725 * @return {Boolean} True if the browser can play ogg files
7726 */
7727WebAudio.canPlayOgg = function() {
7728 if (!this._initialized) {
7729 this.initialize();
7730 }
7731 return !!this._canPlayOgg;
7732};
7733
7734/**
7735 * Checks whether the browser can play m4a files.
7736 *
7737 * @static
7738 * @method canPlayM4a
7739 * @return {Boolean} True if the browser can play m4a files
7740 */
7741WebAudio.canPlayM4a = function() {
7742 if (!this._initialized) {
7743 this.initialize();
7744 }
7745 return !!this._canPlayM4a;
7746};
7747
7748/**
7749 * Sets the master volume of the all audio.
7750 *
7751 * @static
7752 * @method setMasterVolume
7753 * @param {Number} value Master volume (min: 0, max: 1)
7754 */
7755WebAudio.setMasterVolume = function(value) {
7756 this._masterVolume = value;
7757 if (this._masterGainNode) {
7758 this._masterGainNode.gain.setValueAtTime(this._masterVolume, this._context.currentTime);
7759 }
7760};
7761
7762/**
7763 * @static
7764 * @method _createContext
7765 * @private
7766 */
7767WebAudio._createContext = function() {
7768 try {
7769 if (typeof AudioContext !== 'undefined') {
7770 this._context = new AudioContext();
7771 } else if (typeof webkitAudioContext !== 'undefined') {
7772 this._context = new webkitAudioContext();
7773 }
7774 } catch (e) {
7775 this._context = null;
7776 }
7777};
7778
7779/**
7780 * @static
7781 * @method _detectCodecs
7782 * @private
7783 */
7784WebAudio._detectCodecs = function() {
7785 var audio = document.createElement('audio');
7786 if (audio.canPlayType) {
7787 this._canPlayOgg = audio.canPlayType('audio/ogg');
7788 this._canPlayM4a = audio.canPlayType('audio/mp4');
7789 }
7790};
7791
7792/**
7793 * @static
7794 * @method _createMasterGainNode
7795 * @private
7796 */
7797WebAudio._createMasterGainNode = function() {
7798 var context = WebAudio._context;
7799 if (context) {
7800 this._masterGainNode = context.createGain();
7801 this._masterGainNode.gain.setValueAtTime(this._masterVolume, context.currentTime);
7802 this._masterGainNode.connect(context.destination);
7803 }
7804};
7805
7806/**
7807 * @static
7808 * @method _setupEventHandlers
7809 * @private
7810 */
7811WebAudio._setupEventHandlers = function() {
7812 var resumeHandler = function() {
7813 var context = WebAudio._context;
7814 if (context && context.state === "suspended" && typeof context.resume === "function") {
7815 context.resume().then(function() {
7816 WebAudio._onTouchStart();
7817 })
7818 } else {
7819 WebAudio._onTouchStart();
7820 }
7821 };
7822 document.addEventListener("keydown", resumeHandler);
7823 document.addEventListener("mousedown", resumeHandler);
7824 document.addEventListener("touchend", resumeHandler);
7825 document.addEventListener('touchstart', this._onTouchStart.bind(this));
7826 document.addEventListener('visibilitychange', this._onVisibilityChange.bind(this));
7827};
7828
7829/**
7830 * @static
7831 * @method _onTouchStart
7832 * @private
7833 */
7834WebAudio._onTouchStart = function() {
7835 var context = WebAudio._context;
7836 if (context && !this._unlocked) {
7837 // Unlock Web Audio on iOS
7838 var node = context.createBufferSource();
7839 node.start(0);
7840 this._unlocked = true;
7841 }
7842};
7843
7844/**
7845 * @static
7846 * @method _onVisibilityChange
7847 * @private
7848 */
7849WebAudio._onVisibilityChange = function() {
7850 if (document.visibilityState === 'hidden') {
7851 this._onHide();
7852 } else {
7853 this._onShow();
7854 }
7855};
7856
7857/**
7858 * @static
7859 * @method _onHide
7860 * @private
7861 */
7862WebAudio._onHide = function() {
7863 if (this._shouldMuteOnHide()) {
7864 this._fadeOut(1);
7865 }
7866};
7867
7868/**
7869 * @static
7870 * @method _onShow
7871 * @private
7872 */
7873WebAudio._onShow = function() {
7874 if (this._shouldMuteOnHide()) {
7875 this._fadeIn(0.5);
7876 }
7877};
7878
7879/**
7880 * @static
7881 * @method _shouldMuteOnHide
7882 * @private
7883 */
7884WebAudio._shouldMuteOnHide = function() {
7885 return Utils.isMobileDevice();
7886};
7887
7888/**
7889 * @static
7890 * @method _fadeIn
7891 * @param {Number} duration
7892 * @private
7893 */
7894WebAudio._fadeIn = function(duration) {
7895 if (this._masterGainNode) {
7896 var gain = this._masterGainNode.gain;
7897 var currentTime = WebAudio._context.currentTime;
7898 gain.setValueAtTime(0, currentTime);
7899 gain.linearRampToValueAtTime(this._masterVolume, currentTime + duration);
7900 }
7901};
7902
7903/**
7904 * @static
7905 * @method _fadeOut
7906 * @param {Number} duration
7907 * @private
7908 */
7909WebAudio._fadeOut = function(duration) {
7910 if (this._masterGainNode) {
7911 var gain = this._masterGainNode.gain;
7912 var currentTime = WebAudio._context.currentTime;
7913 gain.setValueAtTime(this._masterVolume, currentTime);
7914 gain.linearRampToValueAtTime(0, currentTime + duration);
7915 }
7916};
7917
7918/**
7919 * Clears the audio data.
7920 *
7921 * @method clear
7922 */
7923WebAudio.prototype.clear = function() {
7924 this.stop();
7925 this._buffer = null;
7926 this._sourceNode = null;
7927 this._gainNode = null;
7928 this._pannerNode = null;
7929 this._totalTime = 0;
7930 this._sampleRate = 0;
7931 this._loopStart = 0;
7932 this._loopLength = 0;
7933 this._startTime = 0;
7934 this._volume = 1;
7935 this._pitch = 1;
7936 this._pan = 0;
7937 this._endTimer = null;
7938 this._loadListeners = [];
7939 this._stopListeners = [];
7940 this._hasError = false;
7941 this._autoPlay = false;
7942};
7943
7944/**
7945 * [read-only] The url of the audio file.
7946 *
7947 * @property url
7948 * @type String
7949 */
7950Object.defineProperty(WebAudio.prototype, 'url', {
7951 get: function() {
7952 return this._url;
7953 },
7954 configurable: true
7955});
7956
7957/**
7958 * The volume of the audio.
7959 *
7960 * @property volume
7961 * @type Number
7962 */
7963Object.defineProperty(WebAudio.prototype, 'volume', {
7964 get: function() {
7965 return this._volume;
7966 },
7967 set: function(value) {
7968 this._volume = value;
7969 if (this._gainNode) {
7970 this._gainNode.gain.setValueAtTime(this._volume, WebAudio._context.currentTime);
7971 }
7972 },
7973 configurable: true
7974});
7975
7976/**
7977 * The pitch of the audio.
7978 *
7979 * @property pitch
7980 * @type Number
7981 */
7982Object.defineProperty(WebAudio.prototype, 'pitch', {
7983 get: function() {
7984 return this._pitch;
7985 },
7986 set: function(value) {
7987 if (this._pitch !== value) {
7988 this._pitch = value;
7989 if (this.isPlaying()) {
7990 this.play(this._sourceNode.loop, 0);
7991 }
7992 }
7993 },
7994 configurable: true
7995});
7996
7997/**
7998 * The pan of the audio.
7999 *
8000 * @property pan
8001 * @type Number
8002 */
8003Object.defineProperty(WebAudio.prototype, 'pan', {
8004 get: function() {
8005 return this._pan;
8006 },
8007 set: function(value) {
8008 this._pan = value;
8009 this._updatePanner();
8010 },
8011 configurable: true
8012});
8013
8014/**
8015 * Checks whether the audio data is ready to play.
8016 *
8017 * @method isReady
8018 * @return {Boolean} True if the audio data is ready to play
8019 */
8020WebAudio.prototype.isReady = function() {
8021 return !!this._buffer;
8022};
8023
8024/**
8025 * Checks whether a loading error has occurred.
8026 *
8027 * @method isError
8028 * @return {Boolean} True if a loading error has occurred
8029 */
8030WebAudio.prototype.isError = function() {
8031 return this._hasError;
8032};
8033
8034/**
8035 * Checks whether the audio is playing.
8036 *
8037 * @method isPlaying
8038 * @return {Boolean} True if the audio is playing
8039 */
8040WebAudio.prototype.isPlaying = function() {
8041 return !!this._sourceNode;
8042};
8043
8044/**
8045 * Plays the audio.
8046 *
8047 * @method play
8048 * @param {Boolean} loop Whether the audio data play in a loop
8049 * @param {Number} offset The start position to play in seconds
8050 */
8051WebAudio.prototype.play = function(loop, offset) {
8052 if (this.isReady()) {
8053 offset = offset || 0;
8054 this._startPlaying(loop, offset);
8055 } else if (WebAudio._context) {
8056 this._autoPlay = true;
8057 this.addLoadListener(function() {
8058 if (this._autoPlay) {
8059 this.play(loop, offset);
8060 }
8061 }.bind(this));
8062 }
8063};
8064
8065/**
8066 * Stops the audio.
8067 *
8068 * @method stop
8069 */
8070WebAudio.prototype.stop = function() {
8071 this._autoPlay = false;
8072 this._removeEndTimer();
8073 this._removeNodes();
8074 if (this._stopListeners) {
8075 while (this._stopListeners.length > 0) {
8076 var listner = this._stopListeners.shift();
8077 listner();
8078 }
8079 }
8080};
8081
8082/**
8083 * Performs the audio fade-in.
8084 *
8085 * @method fadeIn
8086 * @param {Number} duration Fade-in time in seconds
8087 */
8088WebAudio.prototype.fadeIn = function(duration) {
8089 if (this.isReady()) {
8090 if (this._gainNode) {
8091 var gain = this._gainNode.gain;
8092 var currentTime = WebAudio._context.currentTime;
8093 gain.setValueAtTime(0, currentTime);
8094 gain.linearRampToValueAtTime(this._volume, currentTime + duration);
8095 }
8096 } else if (this._autoPlay) {
8097 this.addLoadListener(function() {
8098 this.fadeIn(duration);
8099 }.bind(this));
8100 }
8101};
8102
8103/**
8104 * Performs the audio fade-out.
8105 *
8106 * @method fadeOut
8107 * @param {Number} duration Fade-out time in seconds
8108 */
8109WebAudio.prototype.fadeOut = function(duration) {
8110 if (this._gainNode) {
8111 var gain = this._gainNode.gain;
8112 var currentTime = WebAudio._context.currentTime;
8113 gain.setValueAtTime(this._volume, currentTime);
8114 gain.linearRampToValueAtTime(0, currentTime + duration);
8115 }
8116 this._autoPlay = false;
8117};
8118
8119/**
8120 * Gets the seek position of the audio.
8121 *
8122 * @method seek
8123 */
8124WebAudio.prototype.seek = function() {
8125 if (WebAudio._context) {
8126 var pos = (WebAudio._context.currentTime - this._startTime) * this._pitch;
8127 if (this._loopLength > 0) {
8128 while (pos >= this._loopStart + this._loopLength) {
8129 pos -= this._loopLength;
8130 }
8131 }
8132 return pos;
8133 } else {
8134 return 0;
8135 }
8136};
8137
8138/**
8139 * Add a callback function that will be called when the audio data is loaded.
8140 *
8141 * @method addLoadListener
8142 * @param {Function} listner The callback function
8143 */
8144WebAudio.prototype.addLoadListener = function(listner) {
8145 this._loadListeners.push(listner);
8146};
8147
8148/**
8149 * Add a callback function that will be called when the playback is stopped.
8150 *
8151 * @method addStopListener
8152 * @param {Function} listner The callback function
8153 */
8154WebAudio.prototype.addStopListener = function(listner) {
8155 this._stopListeners.push(listner);
8156};
8157
8158/**
8159 * @method _load
8160 * @param {String} url
8161 * @private
8162 */
8163WebAudio.prototype._load = function(url) {
8164 if (WebAudio._context) {
8165 var xhr = new XMLHttpRequest();
8166 if(Decrypter.hasEncryptedAudio) url = Decrypter.extToEncryptExt(url);
8167 xhr.open('GET', url);
8168 xhr.responseType = 'arraybuffer';
8169 xhr.onload = function() {
8170 if (xhr.status < 400) {
8171 this._onXhrLoad(xhr);
8172 }
8173 }.bind(this);
8174 xhr.onerror = this._loader || function(){this._hasError = true;}.bind(this);
8175 xhr.send();
8176 }
8177};
8178
8179/**
8180 * @method _onXhrLoad
8181 * @param {XMLHttpRequest} xhr
8182 * @private
8183 */
8184WebAudio.prototype._onXhrLoad = function(xhr) {
8185 var array = xhr.response;
8186 if(Decrypter.hasEncryptedAudio) array = Decrypter.decryptArrayBuffer(array);
8187 this._readLoopComments(new Uint8Array(array));
8188 WebAudio._context.decodeAudioData(array, function(buffer) {
8189 this._buffer = buffer;
8190 this._totalTime = buffer.duration;
8191 if (this._loopLength > 0 && this._sampleRate > 0) {
8192 this._loopStart /= this._sampleRate;
8193 this._loopLength /= this._sampleRate;
8194 } else {
8195 this._loopStart = 0;
8196 this._loopLength = this._totalTime;
8197 }
8198 this._onLoad();
8199 }.bind(this));
8200};
8201
8202/**
8203 * @method _startPlaying
8204 * @param {Boolean} loop
8205 * @param {Number} offset
8206 * @private
8207 */
8208WebAudio.prototype._startPlaying = function(loop, offset) {
8209 if (this._loopLength > 0) {
8210 while (offset >= this._loopStart + this._loopLength) {
8211 offset -= this._loopLength;
8212 }
8213 }
8214 this._removeEndTimer();
8215 this._removeNodes();
8216 this._createNodes();
8217 this._connectNodes();
8218 this._sourceNode.loop = loop;
8219 this._sourceNode.start(0, offset);
8220 this._startTime = WebAudio._context.currentTime - offset / this._pitch;
8221 this._createEndTimer();
8222};
8223
8224/**
8225 * @method _createNodes
8226 * @private
8227 */
8228WebAudio.prototype._createNodes = function() {
8229 var context = WebAudio._context;
8230 this._sourceNode = context.createBufferSource();
8231 this._sourceNode.buffer = this._buffer;
8232 this._sourceNode.loopStart = this._loopStart;
8233 this._sourceNode.loopEnd = this._loopStart + this._loopLength;
8234 this._sourceNode.playbackRate.setValueAtTime(this._pitch, context.currentTime);
8235 this._gainNode = context.createGain();
8236 this._gainNode.gain.setValueAtTime(this._volume, context.currentTime);
8237 this._pannerNode = context.createPanner();
8238 this._pannerNode.panningModel = 'equalpower';
8239 this._updatePanner();
8240};
8241
8242/**
8243 * @method _connectNodes
8244 * @private
8245 */
8246WebAudio.prototype._connectNodes = function() {
8247 this._sourceNode.connect(this._gainNode);
8248 this._gainNode.connect(this._pannerNode);
8249 this._pannerNode.connect(WebAudio._masterGainNode);
8250};
8251
8252/**
8253 * @method _removeNodes
8254 * @private
8255 */
8256WebAudio.prototype._removeNodes = function() {
8257 if (this._sourceNode) {
8258 this._sourceNode.stop(0);
8259 this._sourceNode = null;
8260 this._gainNode = null;
8261 this._pannerNode = null;
8262 }
8263};
8264
8265/**
8266 * @method _createEndTimer
8267 * @private
8268 */
8269WebAudio.prototype._createEndTimer = function() {
8270 if (this._sourceNode && !this._sourceNode.loop) {
8271 var endTime = this._startTime + this._totalTime / this._pitch;
8272 var delay = endTime - WebAudio._context.currentTime;
8273 this._endTimer = setTimeout(function() {
8274 this.stop();
8275 }.bind(this), delay * 1000);
8276 }
8277};
8278
8279/**
8280 * @method _removeEndTimer
8281 * @private
8282 */
8283WebAudio.prototype._removeEndTimer = function() {
8284 if (this._endTimer) {
8285 clearTimeout(this._endTimer);
8286 this._endTimer = null;
8287 }
8288};
8289
8290/**
8291 * @method _updatePanner
8292 * @private
8293 */
8294WebAudio.prototype._updatePanner = function() {
8295 if (this._pannerNode) {
8296 var x = this._pan;
8297 var z = 1 - Math.abs(x);
8298 this._pannerNode.setPosition(x, 0, z);
8299 }
8300};
8301
8302/**
8303 * @method _onLoad
8304 * @private
8305 */
8306WebAudio.prototype._onLoad = function() {
8307 while (this._loadListeners.length > 0) {
8308 var listner = this._loadListeners.shift();
8309 listner();
8310 }
8311};
8312
8313/**
8314 * @method _readLoopComments
8315 * @param {Uint8Array} array
8316 * @private
8317 */
8318WebAudio.prototype._readLoopComments = function(array) {
8319 this._readOgg(array);
8320 this._readMp4(array);
8321};
8322
8323/**
8324 * @method _readOgg
8325 * @param {Uint8Array} array
8326 * @private
8327 */
8328WebAudio.prototype._readOgg = function(array) {
8329 var index = 0;
8330 while (index < array.length) {
8331 if (this._readFourCharacters(array, index) === 'OggS') {
8332 index += 26;
8333 var vorbisHeaderFound = false;
8334 var numSegments = array[index++];
8335 var segments = [];
8336 for (var i = 0; i < numSegments; i++) {
8337 segments.push(array[index++]);
8338 }
8339 for (i = 0; i < numSegments; i++) {
8340 if (this._readFourCharacters(array, index + 1) === 'vorb') {
8341 var headerType = array[index];
8342 if (headerType === 1) {
8343 this._sampleRate = this._readLittleEndian(array, index + 12);
8344 } else if (headerType === 3) {
8345 this._readMetaData(array, index, segments[i]);
8346 }
8347 vorbisHeaderFound = true;
8348 }
8349 index += segments[i];
8350 }
8351 if (!vorbisHeaderFound) {
8352 break;
8353 }
8354 } else {
8355 break;
8356 }
8357 }
8358};
8359
8360/**
8361 * @method _readMp4
8362 * @param {Uint8Array} array
8363 * @private
8364 */
8365WebAudio.prototype._readMp4 = function(array) {
8366 if (this._readFourCharacters(array, 4) === 'ftyp') {
8367 var index = 0;
8368 while (index < array.length) {
8369 var size = this._readBigEndian(array, index);
8370 var name = this._readFourCharacters(array, index + 4);
8371 if (name === 'moov') {
8372 index += 8;
8373 } else {
8374 if (name === 'mvhd') {
8375 this._sampleRate = this._readBigEndian(array, index + 20);
8376 }
8377 if (name === 'udta' || name === 'meta') {
8378 this._readMetaData(array, index, size);
8379 }
8380 index += size;
8381 if (size <= 1) {
8382 break;
8383 }
8384 }
8385 }
8386 }
8387};
8388
8389/**
8390 * @method _readMetaData
8391 * @param {Uint8Array} array
8392 * @param {Number} index
8393 * @param {Number} size
8394 * @private
8395 */
8396WebAudio.prototype._readMetaData = function(array, index, size) {
8397 for (var i = index; i < index + size - 10; i++) {
8398 if (this._readFourCharacters(array, i) === 'LOOP') {
8399 var text = '';
8400 while (array[i] > 0) {
8401 text += String.fromCharCode(array[i++]);
8402 }
8403 if (text.match(/LOOPSTART=([0-9]+)/)) {
8404 this._loopStart = parseInt(RegExp.$1);
8405 }
8406 if (text.match(/LOOPLENGTH=([0-9]+)/)) {
8407 this._loopLength = parseInt(RegExp.$1);
8408 }
8409 if (text == 'LOOPSTART' || text == 'LOOPLENGTH') {
8410 var text2 = '';
8411 i += 16;
8412 while (array[i] > 0) {
8413 text2 += String.fromCharCode(array[i++]);
8414 }
8415 if (text == 'LOOPSTART') {
8416 this._loopStart = parseInt(text2);
8417 } else {
8418 this._loopLength = parseInt(text2);
8419 }
8420 }
8421 }
8422 }
8423};
8424
8425/**
8426 * @method _readLittleEndian
8427 * @param {Uint8Array} array
8428 * @param {Number} index
8429 * @private
8430 */
8431WebAudio.prototype._readLittleEndian = function(array, index) {
8432 return (array[index + 3] * 0x1000000 + array[index + 2] * 0x10000 +
8433 array[index + 1] * 0x100 + array[index + 0]);
8434};
8435
8436/**
8437 * @method _readBigEndian
8438 * @param {Uint8Array} array
8439 * @param {Number} index
8440 * @private
8441 */
8442WebAudio.prototype._readBigEndian = function(array, index) {
8443 return (array[index + 0] * 0x1000000 + array[index + 1] * 0x10000 +
8444 array[index + 2] * 0x100 + array[index + 3]);
8445};
8446
8447/**
8448 * @method _readFourCharacters
8449 * @param {Uint8Array} array
8450 * @param {Number} index
8451 * @private
8452 */
8453WebAudio.prototype._readFourCharacters = function(array, index) {
8454 var string = '';
8455 for (var i = 0; i < 4; i++) {
8456 string += String.fromCharCode(array[index + i]);
8457 }
8458 return string;
8459};
8460
8461//-----------------------------------------------------------------------------
8462/**
8463 * The static class that handles HTML5 Audio.
8464 *
8465 * @class Html5Audio
8466 * @constructor
8467 */
8468function Html5Audio() {
8469 throw new Error('This is a static class');
8470}
8471
8472Html5Audio._initialized = false;
8473Html5Audio._unlocked = false;
8474Html5Audio._audioElement = null;
8475Html5Audio._gainTweenInterval = null;
8476Html5Audio._tweenGain = 0;
8477Html5Audio._tweenTargetGain = 0;
8478Html5Audio._tweenGainStep = 0;
8479Html5Audio._staticSePath = null;
8480
8481/**
8482 * Sets up the Html5 Audio.
8483 *
8484 * @static
8485 * @method setup
8486 * @param {String} url The url of the audio file
8487 */
8488Html5Audio.setup = function (url) {
8489 if (!this._initialized) {
8490 this.initialize();
8491 }
8492 this.clear();
8493
8494 if(Decrypter.hasEncryptedAudio && this._audioElement.src) {
8495 window.URL.revokeObjectURL(this._audioElement.src);
8496 }
8497 this._url = url;
8498};
8499
8500/**
8501 * Initializes the audio system.
8502 *
8503 * @static
8504 * @method initialize
8505 * @return {Boolean} True if the audio system is available
8506 */
8507Html5Audio.initialize = function () {
8508 if (!this._initialized) {
8509 if (!this._audioElement) {
8510 try {
8511 this._audioElement = new Audio();
8512 } catch (e) {
8513 this._audioElement = null;
8514 }
8515 }
8516 if (!!this._audioElement) this._setupEventHandlers();
8517 this._initialized = true;
8518 }
8519 return !!this._audioElement;
8520};
8521
8522/**
8523 * @static
8524 * @method _setupEventHandlers
8525 * @private
8526 */
8527Html5Audio._setupEventHandlers = function () {
8528 document.addEventListener('touchstart', this._onTouchStart.bind(this));
8529 document.addEventListener('visibilitychange', this._onVisibilityChange.bind(this));
8530 this._audioElement.addEventListener("loadeddata", this._onLoadedData.bind(this));
8531 this._audioElement.addEventListener("error", this._onError.bind(this));
8532 this._audioElement.addEventListener("ended", this._onEnded.bind(this));
8533};
8534
8535/**
8536 * @static
8537 * @method _onTouchStart
8538 * @private
8539 */
8540Html5Audio._onTouchStart = function () {
8541 if (this._audioElement && !this._unlocked) {
8542 if (this._isLoading) {
8543 this._load(this._url);
8544 this._unlocked = true;
8545 } else {
8546 if (this._staticSePath) {
8547 this._audioElement.src = this._staticSePath;
8548 this._audioElement.volume = 0;
8549 this._audioElement.loop = false;
8550 this._audioElement.play();
8551 this._unlocked = true;
8552 }
8553 }
8554 }
8555};
8556
8557/**
8558 * @static
8559 * @method _onVisibilityChange
8560 * @private
8561 */
8562Html5Audio._onVisibilityChange = function () {
8563 if (document.visibilityState === 'hidden') {
8564 this._onHide();
8565 } else {
8566 this._onShow();
8567 }
8568};
8569
8570/**
8571 * @static
8572 * @method _onLoadedData
8573 * @private
8574 */
8575Html5Audio._onLoadedData = function () {
8576 this._buffered = true;
8577 if (this._unlocked) this._onLoad();
8578};
8579
8580/**
8581 * @static
8582 * @method _onError
8583 * @private
8584 */
8585Html5Audio._onError = function () {
8586 this._hasError = true;
8587};
8588
8589/**
8590 * @static
8591 * @method _onEnded
8592 * @private
8593 */
8594Html5Audio._onEnded = function () {
8595 if (!this._audioElement.loop) {
8596 this.stop();
8597 }
8598};
8599
8600/**
8601 * @static
8602 * @method _onHide
8603 * @private
8604 */
8605Html5Audio._onHide = function () {
8606 this._audioElement.volume = 0;
8607 this._tweenGain = 0;
8608};
8609
8610/**
8611 * @static
8612 * @method _onShow
8613 * @private
8614 */
8615Html5Audio._onShow = function () {
8616 this.fadeIn(0.5);
8617};
8618
8619/**
8620 * Clears the audio data.
8621 *
8622 * @static
8623 * @method clear
8624 */
8625Html5Audio.clear = function () {
8626 this.stop();
8627 this._volume = 1;
8628 this._loadListeners = [];
8629 this._hasError = false;
8630 this._autoPlay = false;
8631 this._isLoading = false;
8632 this._buffered = false;
8633};
8634
8635/**
8636 * Set the URL of static se.
8637 *
8638 * @static
8639 * @param {String} url
8640 */
8641Html5Audio.setStaticSe = function (url) {
8642 if (!this._initialized) {
8643 this.initialize();
8644 this.clear();
8645 }
8646 this._staticSePath = url;
8647};
8648
8649/**
8650 * [read-only] The url of the audio file.
8651 *
8652 * @property url
8653 * @type String
8654 */
8655Object.defineProperty(Html5Audio, 'url', {
8656 get: function () {
8657 return Html5Audio._url;
8658 },
8659 configurable: true
8660});
8661
8662/**
8663 * The volume of the audio.
8664 *
8665 * @property volume
8666 * @type Number
8667 */
8668Object.defineProperty(Html5Audio, 'volume', {
8669 get: function () {
8670 return Html5Audio._volume;
8671 }.bind(this),
8672 set: function (value) {
8673 Html5Audio._volume = value;
8674 if (Html5Audio._audioElement) {
8675 Html5Audio._audioElement.volume = this._volume;
8676 }
8677 },
8678 configurable: true
8679});
8680
8681/**
8682 * Checks whether the audio data is ready to play.
8683 *
8684 * @static
8685 * @method isReady
8686 * @return {Boolean} True if the audio data is ready to play
8687 */
8688Html5Audio.isReady = function () {
8689 return this._buffered;
8690};
8691
8692/**
8693 * Checks whether a loading error has occurred.
8694 *
8695 * @static
8696 * @method isError
8697 * @return {Boolean} True if a loading error has occurred
8698 */
8699Html5Audio.isError = function () {
8700 return this._hasError;
8701};
8702
8703/**
8704 * Checks whether the audio is playing.
8705 *
8706 * @static
8707 * @method isPlaying
8708 * @return {Boolean} True if the audio is playing
8709 */
8710Html5Audio.isPlaying = function () {
8711 return !this._audioElement.paused;
8712};
8713
8714/**
8715 * Plays the audio.
8716 *
8717 * @static
8718 * @method play
8719 * @param {Boolean} loop Whether the audio data play in a loop
8720 * @param {Number} offset The start position to play in seconds
8721 */
8722Html5Audio.play = function (loop, offset) {
8723 if (this.isReady()) {
8724 offset = offset || 0;
8725 this._startPlaying(loop, offset);
8726 } else if (Html5Audio._audioElement) {
8727 this._autoPlay = true;
8728 this.addLoadListener(function () {
8729 if (this._autoPlay) {
8730 this.play(loop, offset);
8731 if (this._gainTweenInterval) {
8732 clearInterval(this._gainTweenInterval);
8733 this._gainTweenInterval = null;
8734 }
8735 }
8736 }.bind(this));
8737 if (!this._isLoading) this._load(this._url);
8738 }
8739};
8740
8741/**
8742 * Stops the audio.
8743 *
8744 * @static
8745 * @method stop
8746 */
8747Html5Audio.stop = function () {
8748 if (this._audioElement) this._audioElement.pause();
8749 this._autoPlay = false;
8750 if (this._tweenInterval) {
8751 clearInterval(this._tweenInterval);
8752 this._tweenInterval = null;
8753 this._audioElement.volume = 0;
8754 }
8755};
8756
8757/**
8758 * Performs the audio fade-in.
8759 *
8760 * @static
8761 * @method fadeIn
8762 * @param {Number} duration Fade-in time in seconds
8763 */
8764Html5Audio.fadeIn = function (duration) {
8765 if (this.isReady()) {
8766 if (this._audioElement) {
8767 this._tweenTargetGain = this._volume;
8768 this._tweenGain = 0;
8769 this._startGainTween(duration);
8770 }
8771 } else if (this._autoPlay) {
8772 this.addLoadListener(function () {
8773 this.fadeIn(duration);
8774 }.bind(this));
8775 }
8776};
8777
8778/**
8779 * Performs the audio fade-out.
8780 *
8781 * @static
8782 * @method fadeOut
8783 * @param {Number} duration Fade-out time in seconds
8784 */
8785Html5Audio.fadeOut = function (duration) {
8786 if (this._audioElement) {
8787 this._tweenTargetGain = 0;
8788 this._tweenGain = this._volume;
8789 this._startGainTween(duration);
8790 }
8791};
8792
8793/**
8794 * Gets the seek position of the audio.
8795 *
8796 * @static
8797 * @method seek
8798 */
8799Html5Audio.seek = function () {
8800 if (this._audioElement) {
8801 return this._audioElement.currentTime;
8802 } else {
8803 return 0;
8804 }
8805};
8806
8807/**
8808 * Add a callback function that will be called when the audio data is loaded.
8809 *
8810 * @static
8811 * @method addLoadListener
8812 * @param {Function} listner The callback function
8813 */
8814Html5Audio.addLoadListener = function (listner) {
8815 this._loadListeners.push(listner);
8816};
8817
8818/**
8819 * @static
8820 * @method _load
8821 * @param {String} url
8822 * @private
8823 */
8824Html5Audio._load = function (url) {
8825 if (this._audioElement) {
8826 this._isLoading = true;
8827 this._audioElement.src = url;
8828 this._audioElement.load();
8829 }
8830};
8831
8832/**
8833 * @static
8834 * @method _startPlaying
8835 * @param {Boolean} loop
8836 * @param {Number} offset
8837 * @private
8838 */
8839Html5Audio._startPlaying = function (loop, offset) {
8840 this._audioElement.loop = loop;
8841 if (this._gainTweenInterval) {
8842 clearInterval(this._gainTweenInterval);
8843 this._gainTweenInterval = null;
8844 }
8845 if (this._audioElement) {
8846 this._audioElement.volume = this._volume;
8847 this._audioElement.currentTime = offset;
8848 this._audioElement.play();
8849 }
8850};
8851
8852/**
8853 * @static
8854 * @method _onLoad
8855 * @private
8856 */
8857Html5Audio._onLoad = function () {
8858 this._isLoading = false;
8859 while (this._loadListeners.length > 0) {
8860 var listener = this._loadListeners.shift();
8861 listener();
8862 }
8863};
8864
8865/**
8866 * @static
8867 * @method _startGainTween
8868 * @params {Number} duration
8869 * @private
8870 */
8871Html5Audio._startGainTween = function (duration) {
8872 this._audioElement.volume = this._tweenGain;
8873 if (this._gainTweenInterval) {
8874 clearInterval(this._gainTweenInterval);
8875 this._gainTweenInterval = null;
8876 }
8877 this._tweenGainStep = (this._tweenTargetGain - this._tweenGain) / (60 * duration);
8878 this._gainTweenInterval = setInterval(function () {
8879 Html5Audio._applyTweenValue(Html5Audio._tweenTargetGain);
8880 }, 1000 / 60);
8881};
8882
8883/**
8884 * @static
8885 * @method _applyTweenValue
8886 * @param {Number} volume
8887 * @private
8888 */
8889Html5Audio._applyTweenValue = function (volume) {
8890 Html5Audio._tweenGain += Html5Audio._tweenGainStep;
8891 if (Html5Audio._tweenGain < 0 && Html5Audio._tweenGainStep < 0) {
8892 Html5Audio._tweenGain = 0;
8893 }
8894 else if (Html5Audio._tweenGain > volume && Html5Audio._tweenGainStep > 0) {
8895 Html5Audio._tweenGain = volume;
8896 }
8897
8898 if (Math.abs(Html5Audio._tweenTargetGain - Html5Audio._tweenGain) < 0.01) {
8899 Html5Audio._tweenGain = Html5Audio._tweenTargetGain;
8900 clearInterval(Html5Audio._gainTweenInterval);
8901 Html5Audio._gainTweenInterval = null;
8902 }
8903
8904 Html5Audio._audioElement.volume = Html5Audio._tweenGain;
8905};
8906
8907//-----------------------------------------------------------------------------
8908/**
8909 * The static class that handles JSON with object information.
8910 *
8911 * @class JsonEx
8912 */
8913function JsonEx() {
8914 throw new Error('This is a static class');
8915}
8916
8917/**
8918 * The maximum depth of objects.
8919 *
8920 * @static
8921 * @property maxDepth
8922 * @type Number
8923 * @default 100
8924 */
8925JsonEx.maxDepth = 100;
8926
8927JsonEx._id = 1;
8928JsonEx._generateId = function(){
8929 return JsonEx._id++;
8930};
8931
8932/**
8933 * Converts an object to a JSON string with object information.
8934 *
8935 * @static
8936 * @method stringify
8937 * @param {Object} object The object to be converted
8938 * @return {String} The JSON string
8939 */
8940JsonEx.stringify = function(object) {
8941 var circular = [];
8942 JsonEx._id = 1;
8943 var json = JSON.stringify(this._encode(object, circular, 0));
8944 this._cleanMetadata(object);
8945 this._restoreCircularReference(circular);
8946
8947 return json;
8948};
8949
8950JsonEx._restoreCircularReference = function(circulars){
8951 circulars.forEach(function(circular){
8952 var key = circular[0];
8953 var value = circular[1];
8954 var content = circular[2];
8955
8956 value[key] = content;
8957 });
8958};
8959
8960/**
8961 * Parses a JSON string and reconstructs the corresponding object.
8962 *
8963 * @static
8964 * @method parse
8965 * @param {String} json The JSON string
8966 * @return {Object} The reconstructed object
8967 */
8968JsonEx.parse = function(json) {
8969 var circular = [];
8970 var registry = {};
8971 var contents = this._decode(JSON.parse(json), circular, registry);
8972 this._cleanMetadata(contents);
8973 this._linkCircularReference(contents, circular, registry);
8974
8975 return contents;
8976};
8977
8978JsonEx._linkCircularReference = function(contents, circulars, registry){
8979 circulars.forEach(function(circular){
8980 var key = circular[0];
8981 var value = circular[1];
8982 var id = circular[2];
8983
8984 value[key] = registry[id];
8985 });
8986};
8987
8988JsonEx._cleanMetadata = function(object){
8989 if(!object) return;
8990
8991 delete object['@'];
8992 delete object['@c'];
8993
8994 if(typeof object === 'object'){
8995 Object.keys(object).forEach(function(key){
8996 var value = object[key];
8997 if(typeof value === 'object'){
8998 JsonEx._cleanMetadata(value);
8999 }
9000 });
9001 }
9002};
9003
9004
9005/**
9006 * Makes a deep copy of the specified object.
9007 *
9008 * @static
9009 * @method makeDeepCopy
9010 * @param {Object} object The object to be copied
9011 * @return {Object} The copied object
9012 */
9013JsonEx.makeDeepCopy = function(object) {
9014 return this.parse(this.stringify(object));
9015};
9016
9017/**
9018 * @static
9019 * @method _encode
9020 * @param {Object} value
9021 * @param {Array} circular
9022 * @param {Number} depth
9023 * @return {Object}
9024 * @private
9025 */
9026JsonEx._encode = function(value, circular, depth) {
9027 depth = depth || 0;
9028 if (++depth >= this.maxDepth) {
9029 throw new Error('Object too deep');
9030 }
9031 var type = Object.prototype.toString.call(value);
9032 if (type === '[object Object]' || type === '[object Array]') {
9033 value['@c'] = JsonEx._generateId();
9034
9035 var constructorName = this._getConstructorName(value);
9036 if (constructorName !== 'Object' && constructorName !== 'Array') {
9037 value['@'] = constructorName;
9038 }
9039 for (var key in value) {
9040 if (value.hasOwnProperty(key) && !key.match(/^@./)) {
9041 if(value[key] && typeof value[key] === 'object'){
9042 if(value[key]['@c']){
9043 circular.push([key, value, value[key]]);
9044 value[key] = {'@r': value[key]['@c']};
9045 }else{
9046 value[key] = this._encode(value[key], circular, depth + 1);
9047
9048 if(value[key] instanceof Array){
9049 //wrap array
9050 circular.push([key, value, value[key]]);
9051
9052 value[key] = {
9053 '@c': value[key]['@c'],
9054 '@a': value[key]
9055 };
9056 }
9057 }
9058 }else{
9059 value[key] = this._encode(value[key], circular, depth + 1);
9060 }
9061 }
9062 }
9063 }
9064 depth--;
9065 return value;
9066};
9067
9068/**
9069 * @static
9070 * @method _decode
9071 * @param {Object} value
9072 * @param {Array} circular
9073 * @param {Object} registry
9074 * @return {Object}
9075 * @private
9076 */
9077JsonEx._decode = function(value, circular, registry) {
9078 var type = Object.prototype.toString.call(value);
9079 if (type === '[object Object]' || type === '[object Array]') {
9080 registry[value['@c']] = value;
9081
9082 if (value['@']) {
9083 var constructor = window[value['@']];
9084 if (constructor) {
9085 value = this._resetPrototype(value, constructor.prototype);
9086 }
9087 }
9088 for (var key in value) {
9089 if (value.hasOwnProperty(key)) {
9090 if(value[key] && value[key]['@a']){
9091 //object is array wrapper
9092 var body = value[key]['@a'];
9093 body['@c'] = value[key]['@c'];
9094 value[key] = body;
9095 }
9096 if(value[key] && value[key]['@r']){
9097 //object is reference
9098 circular.push([key, value, value[key]['@r']])
9099 }
9100 value[key] = this._decode(value[key], circular, registry);
9101 }
9102 }
9103 }
9104 return value;
9105};
9106
9107/**
9108 * @static
9109 * @method _getConstructorName
9110 * @param {Object} value
9111 * @return {String}
9112 * @private
9113 */
9114JsonEx._getConstructorName = function(value) {
9115 var name = value.constructor.name;
9116 if (name === undefined) {
9117 var func = /^\s*function\s*([A-Za-z0-9_$]*)/;
9118 name = func.exec(value.constructor)[1];
9119 }
9120 return name;
9121};
9122
9123/**
9124 * @static
9125 * @method _resetPrototype
9126 * @param {Object} value
9127 * @param {Object} prototype
9128 * @return {Object}
9129 * @private
9130 */
9131JsonEx._resetPrototype = function(value, prototype) {
9132 if (Object.setPrototypeOf !== undefined) {
9133 Object.setPrototypeOf(value, prototype);
9134 } else if ('__proto__' in value) {
9135 value.__proto__ = prototype;
9136 } else {
9137 var newValue = Object.create(prototype);
9138 for (var key in value) {
9139 if (value.hasOwnProperty(key)) {
9140 newValue[key] = value[key];
9141 }
9142 }
9143 value = newValue;
9144 }
9145 return value;
9146};
9147
9148
9149function Decrypter() {
9150 throw new Error('This is a static class');
9151}
9152
9153Decrypter.hasEncryptedImages = false;
9154Decrypter.hasEncryptedAudio = false;
9155Decrypter._requestImgFile = [];
9156Decrypter._headerlength = 16;
9157Decrypter._xhrOk = 400;
9158Decrypter._encryptionKey = "";
9159Decrypter._ignoreList = [
9160 "img/system/Window.png"
9161];
9162Decrypter.SIGNATURE = "5250474d56000000";
9163Decrypter.VER = "000301";
9164Decrypter.REMAIN = "0000000000";
9165
9166Decrypter.checkImgIgnore = function(url){
9167 for(var cnt = 0; cnt < this._ignoreList.length; cnt++) {
9168 if(url === this._ignoreList[cnt]) return true;
9169 }
9170 return false;
9171};
9172
9173Decrypter.decryptImg = function(url, bitmap) {
9174 url = this.extToEncryptExt(url);
9175
9176 var requestFile = new XMLHttpRequest();
9177 requestFile.open("GET", url);
9178 requestFile.responseType = "arraybuffer";
9179 requestFile.send();
9180
9181 requestFile.onload = function () {
9182 if(this.status < Decrypter._xhrOk) {
9183 var arrayBuffer = Decrypter.decryptArrayBuffer(requestFile.response);
9184 bitmap._image.src = Decrypter.createBlobUrl(arrayBuffer);
9185 bitmap._image.addEventListener('load', bitmap._loadListener = Bitmap.prototype._onLoad.bind(bitmap));
9186 bitmap._image.addEventListener('error', bitmap._errorListener = bitmap._loader || Bitmap.prototype._onError.bind(bitmap));
9187 }
9188 };
9189
9190 requestFile.onerror = function () {
9191 if (bitmap._loader) {
9192 bitmap._loader();
9193 } else {
9194 bitmap._onError();
9195 }
9196 };
9197};
9198
9199Decrypter.decryptHTML5Audio = function(url, bgm, pos) {
9200 var requestFile = new XMLHttpRequest();
9201 requestFile.open("GET", url);
9202 requestFile.responseType = "arraybuffer";
9203 requestFile.send();
9204
9205 requestFile.onload = function () {
9206 if(this.status < Decrypter._xhrOk) {
9207 var arrayBuffer = Decrypter.decryptArrayBuffer(requestFile.response);
9208 var url = Decrypter.createBlobUrl(arrayBuffer);
9209 AudioManager.createDecryptBuffer(url, bgm, pos);
9210 }
9211 };
9212};
9213
9214Decrypter.cutArrayHeader = function(arrayBuffer, length) {
9215 return arrayBuffer.slice(length);
9216};
9217
9218Decrypter.decryptArrayBuffer = function(arrayBuffer) {
9219 if (!arrayBuffer) return null;
9220 var header = new Uint8Array(arrayBuffer, 0, this._headerlength);
9221
9222 var i;
9223 var ref = this.SIGNATURE + this.VER + this.REMAIN;
9224 var refBytes = new Uint8Array(16);
9225 for (i = 0; i < this._headerlength; i++) {
9226 refBytes[i] = parseInt("0x" + ref.substr(i * 2, 2), 16);
9227 }
9228 for (i = 0; i < this._headerlength; i++) {
9229 if (header[i] !== refBytes[i]) {
9230 throw new Error("Header is wrong");
9231 }
9232 }
9233
9234 arrayBuffer = this.cutArrayHeader(arrayBuffer, Decrypter._headerlength);
9235 var view = new DataView(arrayBuffer);
9236 this.readEncryptionkey();
9237 if (arrayBuffer) {
9238 var byteArray = new Uint8Array(arrayBuffer);
9239 for (i = 0; i < this._headerlength; i++) {
9240 byteArray[i] = byteArray[i] ^ parseInt(Decrypter._encryptionKey[i], 16);
9241 view.setUint8(i, byteArray[i]);
9242 }
9243 }
9244
9245 return arrayBuffer;
9246};
9247
9248Decrypter.createBlobUrl = function(arrayBuffer){
9249 var blob = new Blob([arrayBuffer]);
9250 return window.URL.createObjectURL(blob);
9251};
9252
9253Decrypter.extToEncryptExt = function(url) {
9254 var ext = url.split('.').pop();
9255 var encryptedExt = ext;
9256
9257 if(ext === "ogg") encryptedExt = ".rpgmvo";
9258 else if(ext === "m4a") encryptedExt = ".rpgmvm";
9259 else if(ext === "png") encryptedExt = ".rpgmvp";
9260 else encryptedExt = ext;
9261
9262 return url.slice(0, url.lastIndexOf(ext) - 1) + encryptedExt;
9263};
9264
9265Decrypter.readEncryptionkey = function(){
9266 this._encryptionKey = $dataSystem.encryptionKey.split(/(.{2})/).filter(Boolean);
9267};
9268
9269//-----------------------------------------------------------------------------
9270/**
9271 * The static class that handles resource loading.
9272 *
9273 * @class ResourceHandler
9274 */
9275function ResourceHandler() {
9276 throw new Error('This is a static class');
9277}
9278
9279ResourceHandler._reloaders = [];
9280ResourceHandler._defaultRetryInterval = [500, 1000, 3000];
9281
9282ResourceHandler.createLoader = function(url, retryMethod, resignMethod, retryInterval) {
9283 retryInterval = retryInterval || this._defaultRetryInterval;
9284 var reloaders = this._reloaders;
9285 var retryCount = 0;
9286 return function() {
9287 if (retryCount < retryInterval.length) {
9288 setTimeout(retryMethod, retryInterval[retryCount]);
9289 retryCount++;
9290 } else {
9291 if (resignMethod) {
9292 resignMethod();
9293 }
9294 if (url) {
9295 if (reloaders.length === 0) {
9296 Graphics.printLoadingError(url);
9297 SceneManager.stop();
9298 }
9299 reloaders.push(function() {
9300 retryCount = 0;
9301 retryMethod();
9302 });
9303 }
9304 }
9305 };
9306};
9307
9308ResourceHandler.exists = function() {
9309 return this._reloaders.length > 0;
9310};
9311
9312ResourceHandler.retry = function() {
9313 if (this._reloaders.length > 0) {
9314 Graphics.eraseLoadingError();
9315 SceneManager.resume();
9316 this._reloaders.forEach(function(reloader) {
9317 reloader();
9318 });
9319 this._reloaders.length = 0;
9320 }
9321};