From e62ef48cc59b1d41b715c71b43d1336507bb4c29 Mon Sep 17 00:00:00 2001 From: David Figatner Date: Sun, 9 Aug 2020 20:33:22 +0800 Subject: [PATCH] published 1.0.0! --- bundle/pixi-cull.min.js | 2 +- docs/bundle.js | 84254 ++++++++++++++---------------- docs/jsdoc/Simple.html | 2 +- docs/jsdoc/SpatialHash.html | 2 +- docs/jsdoc/global.html | 2 +- docs/jsdoc/index.html | 2 +- docs/jsdoc/simple.js.html | 2 +- docs/jsdoc/spatial-hash.js.html | 2 +- yarn.lock | 826 +- 9 files changed, 41039 insertions(+), 44055 deletions(-) diff --git a/bundle/pixi-cull.min.js b/bundle/pixi-cull.min.js index 26fa8f5..24c19d2 100644 --- a/bundle/pixi-cull.min.js +++ b/bundle/pixi-cull.min.js @@ -1 +1 @@ -!function n(s,h,l){function o(e,t){if(!h[e]){if(!s[e]){var i="function"==typeof require&&require;if(!t&&i)return i(e,!0);if(u)return u(e,!0);var r=new Error("Cannot find module '"+e+"'");throw r.code="MODULE_NOT_FOUND",r}var a=h[e]={exports:{}};s[e][0].call(a.exports,function(t){return o(s[e][1][t]||t)},a,a.exports,n,s,h,l)}return h[e].exports}for(var u="function"==typeof require&&require,t=0;tt.x&&f.xt.y&&f.yt.x&&f.x-f.widtht.y&&f.y-f.heightt.x&&f.x-f.widtht.y&&f.y-f.height=e&&i.push(a)}return i}},{key:"getBounds",value:function(t){return{xStart:Math.floor(t.x/this.xSize),yStart:Math.floor(t.y/this.ySize),xEnd:Math.floor((t.x+t.width)/this.xSize),yEnd:Math.floor((t.y+t.height)/this.ySize)}}},{key:"insert",value:function(t,e){this.hash[e]?this.hash[e].push(t):this.hash[e]=[t]}},{key:"removeFromHash",value:function(t){for(var e=t[this.spatial];e.hashes.length;){var i=e.hashes.pop(),r=this.hash[i];r.splice(r.indexOf(t),1)}}},{key:"neighbors",value:function(t){var e=this,i=[];return t[this.spatial].hashes.forEach(function(t){return i=i.concat(e.hash[t])}),i}},{key:"query",value:function(t,e){e=void 0===e||e;for(var i=0,r=[],a=this.getBounds(t),n=a.xStart,s=a.yStart,h=a.xEnd,l=a.yEnd,o=s;o<=l;o++)for(var u=n;u<=h;u++){var c=this.hash[u+","+o];if(c){if(e){var y=!0,v=!1,f=void 0;try{for(var d,x=c[Symbol.iterator]();!(y=(d=x.next()).done);y=!0){var b=d.value,p=b[this.AABB];p.x+p.width>t.x&&p.xt.y&&p.yv.x&&v.xv.y&&v.yt&&(t=this.hash[e].length);return t}},{key:"getWorldBounds",value:function(){var t=1/0,e=1/0,i=0,r=0;for(var a in this.hash){var n=a.split(","),s=parseInt(n[0]),h=parseInt(n[1]);t=st.x&&f.xt.y&&f.yt.x&&f.x-f.widtht.y&&f.y-f.heightt.x&&f.x-f.widtht.y&&f.y-f.height=e&&i.push(a)}return i}},{key:"getBounds",value:function(t){return{xStart:Math.floor(t.x/this.xSize),yStart:Math.floor(t.y/this.ySize),xEnd:Math.floor((t.x+t.width)/this.xSize),yEnd:Math.floor((t.y+t.height)/this.ySize)}}},{key:"insert",value:function(t,e){this.hash[e]?this.hash[e].push(t):this.hash[e]=[t]}},{key:"removeFromHash",value:function(t){for(var e=t[this.spatial];e.hashes.length;){var i=e.hashes.pop(),r=this.hash[i];r.splice(r.indexOf(t),1)}}},{key:"neighbors",value:function(t){var e=this,i=[];return t[this.spatial].hashes.forEach(function(t){return i=i.concat(e.hash[t])}),i}},{key:"query",value:function(t,e){e=void 0===e||e;for(var i=0,r=[],a=this.getBounds(t),n=a.xStart,s=a.yStart,h=a.xEnd,l=a.yEnd,o=s;o<=l;o++)for(var u=n;u<=h;u++){var c=this.hash[u+","+o];if(c){if(e){var y=!0,v=!1,f=void 0;try{for(var d,x=c[Symbol.iterator]();!(y=(d=x.next()).done);y=!0){var b=d.value,p=b[this.AABB];p.x+p.width>t.x&&p.xt.y&&p.yv.x&&v.xv.y&&v.yt&&(t=this.hash[e].length);return t}},{key:"getWorldBounds",value:function(){var t=1/0,e=1/0,i=0,r=0;for(var a in this.hash)var n=a.split(","),s=parseInt(n[0]),h=parseInt(n[1]),t=s bounds.x && box.x < bounds.x + bounds.width && + box.y + box.height > bounds.y && box.y < bounds.y + bounds.height + } } } - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); + /** + * update the AABB for all objects + * automatically called from update() when calculatePIXI=true and skipUpdate=false + */ + updateObjects() + { + if (this.dirtyTest) + { + for (let list of this.lists) + { + if (!list.staticObject) + { + for (let object of list) + { + if (!object.staticObject && object[this.dirty]) + { + this.updateObject(object) + object[this.dirty] = false + } + } + } + } + } + else + { + for (let list of this.lists) + { + if (!list.staticObject) + { + for (let object of list) + { + if (!object.staticObject) + { + this.updateObject(object) + } + } + } + } + } } -} -function drainQueue() { - if (draining) { - return; + /** + * update the has of an object + * automatically called from updateObjects() + * @param {*} object + */ + updateObject(object) + { + const box = object.getLocalBounds() + object[this.AABB] = object[this.AABB] || {} + object[this.AABB].x = object.x + (box.x - object.pivot.x) * object.scale.x + object[this.AABB].y = object.y + (box.y - object.pivot.y) * object.scale.y + object[this.AABB].width = box.width * object.scale.x + object[this.AABB].height = box.height * object.scale.y } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); + /** + * returns an array of objects contained within bounding box + * @param {object} boudns bounding box to search + * @param {number} bounds.x + * @param {number} bounds.y + * @param {number} bounds.width + * @param {number} bounds.height + * @return {object[]} search results + */ + query(bounds) + { + let results = [] + for (let list of this.lists) + { + for (let object of list) + { + const box = object[this.AABB] + if (box.x + box.width > bounds.x && box.x - box.width < bounds.x + bounds.width && + box.y + box.height > bounds.y && box.y - box.height < bounds.y + bounds.height) + { + results.push(object) + } } } - queueIndex = -1; - len = queue.length; + return results } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; + /** + * iterates through objects contained within bounding box + * stops iterating if the callback returns true + * @param {object} bounds bounding box to search + * @param {number} bounds.x + * @param {number} bounds.y + * @param {number} bounds.width + * @param {number} bounds.height + * @param {function} callback + * @return {boolean} true if callback returned early + */ + queryCallback(bounds, callback) + { + for (let list of this.lists) + { + for (let object of list) + { + const box = object[this.AABB] + if (box.x + box.width > bounds.x && box.x - box.width < bounds.x + bounds.width && + box.y + box.height > bounds.y && box.y - box.height < bounds.y + bounds.height) + { + if (callback(object)) + { + return true + } + } + } } + return false } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; + /** + * get stats (only updated after update() is called) + * @return {SimpleStats} + */ + stats() + { + let visible = 0, count = 0 + for (let list of this.lists) + { + list.forEach(object => + { + visible += object.visible ? 1 : 0 + count++ + }) + } + return { total: count, visible, culled: count - visible } + } } -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; +/** + * @typedef {object} SimpleStats + * @property {number} total + * @property {number} visible + * @property {number} culled + */ +module.exports = Simple },{}],3:[function(require,module,exports){ -(function (global){ -/*! https://mths.be/punycode v1.4.1 by @mathias */ -;(function(root) { +// Copyright 2018 YOPEY YOPEY LLC +// David Figatner +// MIT License - /** Detect free variables */ - var freeExports = typeof exports == 'object' && exports && - !exports.nodeType && exports; - var freeModule = typeof module == 'object' && module && - !module.nodeType && module; - var freeGlobal = typeof global == 'object' && global; - if ( - freeGlobal.global === freeGlobal || - freeGlobal.window === freeGlobal || - freeGlobal.self === freeGlobal - ) { - root = freeGlobal; - } +class SpatialHash +{ + /** + * creates a spatial-hash cull + * @param {object} [options] + * @param {number} [options.size=1000] cell size used to create hash (xSize = ySize) + * @param {number} [options.xSize] horizontal cell size + * @param {number} [options.ySize] vertical cell size + * @param {boolean} [options.calculatePIXI=true] calculate bounding box automatically; if this is set to false then it uses object[options.AABB] for bounding box + * @param {boolean} [options.visible=visible] parameter of the object to set (usually visible or renderable) + * @param {boolean} [options.simpleTest=true] iterate through visible buckets to check for bounds + * @param {string} [options.dirtyTest=true] only update spatial hash for objects with object[options.dirtyTest]=true; this has a HUGE impact on performance + * @param {string} [options.AABB=AABB] object property that holds bounding box so that object[type] = { x: number, y: number, width: number, height: number } + * @param {string} [options.spatial=spatial] object property that holds object's hash list + * @param {string} [options.dirty=dirty] object property for dirtyTest + */ + constructor(options) + { + options = options || {} + this.xSize = options.xSize || options.size || 1000 + this.ySize = options.ySize || options.size || 1000 + this.AABB = options.type || 'AABB' + this.spatial = options.spatial || 'spatial' + this.calculatePIXI = typeof options.calculatePIXI !== 'undefined' ? options.calculatePIXI : true + this.visibleText = typeof options.visibleTest !== 'undefined' ? options.visibleTest : true + this.simpleTest = typeof options.simpleTest !== 'undefined' ? options.simpleTest : true + this.dirtyTest = typeof options.dirtyTest !== 'undefined' ? options.dirtyTest : true + this.visible = options.visible || 'visible' + this.dirty = options.dirty || 'dirty' + this.width = this.height = 0 + this.hash = {} + this.objects = [] + this.containers = [] + } - /** - * The `punycode` object. - * @name punycode - * @type Object - */ - var punycode, + /** + * add an object to be culled + * side effect: adds object.spatialHashes to track existing hashes + * @param {*} object + * @param {boolean} [staticObject] set to true if the object's position/size does not change + * @return {*} object + */ + add(object, staticObject) + { + object[this.spatial] = { hashes: [] } + if (this.calculatePIXI && this.dirtyTest) + { + object[this.dirty] = true + } + if (staticObject) + { + object.staticObject = true + } + this.updateObject(object) + this.containers[0].push(object) + } - /** Highest positive signed 32-bit float value */ - maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + /** + * remove an object added by add() + * @param {*} object + * @return {*} object + */ + remove(object) + { + this.containers[0].splice(this.list[0].indexOf(object), 1) + this.removeFromHash(object) + return object + } - /** Bootstring parameters */ - base = 36, - tMin = 1, - tMax = 26, - skew = 38, - damp = 700, - initialBias = 72, - initialN = 128, // 0x80 - delimiter = '-', // '\x2D' + /** + * add an array of objects to be culled + * @param {PIXI.Container} container + * @param {boolean} [staticObject] set to true if the objects in the container's position/size do not change + * note: this only works with pixi v5.0.0rc2+ because it relies on the new container events childAdded and childRemoved + */ + addContainer(container, staticObject) + { + const added = function(object) + { + object[this.spatial] = { hashes: [] } + this.updateObject(object) + }.bind(this) - /** Regular expressions */ - regexPunycode = /^xn--/, - regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - - /** Error messages */ - errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }, - - /** Convenience shortcuts */ - baseMinusTMin = base - tMin, - floor = Math.floor, - stringFromCharCode = String.fromCharCode, - - /** Temporary variable */ - key; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw new RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, fn) { - var length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); - } - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - } + const removed = function (object) + { + this.removeFromHash(object) + }.bind(this) - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } + for (let object of container.children) + { + object[this.spatial] = { hashes: [] } + this.updateObject(object) + } + container.cull = {} + this.containers.push(container) + container.on('childAdded', added) + container.on('childRemoved', removed) + container.cull.added = added + container.cull.removed = removed + if (staticObject) + { + container.cull.static = true + } + } - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - } + /** + * remove an array added by addContainer() + * @param {PIXI.Container} container + * @return {PIXI.Container} container + */ + removeContainer(container) + { + this.containers.splice(this.containers.indexOf(container), 1) + container.children.forEach(object => this.removeFromHash(object)) + container.off('added', container.cull.added) + container.off('removed', container.cull.removed) + delete container.cull + return container + } - /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ - function decode(input) { - // Don't use UCS-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; + /** + * update the hashes and cull the items in the list + * @param {AABB} AABB + * @param {boolean} [skipUpdate] skip updating the hashes of all objects + * @return {number} number of buckets in results + */ + cull(AABB, skipUpdate) + { + if (!skipUpdate) + { + this.updateObjects() + } + this.invisible() + const objects = this.query(AABB, this.simpleTest) + objects.forEach(object => object[this.visible] = true) + return this.lastBuckets + } - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. + /** + * set all objects in hash to visible=false + */ + invisible() + { + for (let container of this.containers) + { + container.children.forEach(object => object[this.visible] = false) + } + } - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } + /** + * update the hashes for all objects + * automatically called from update() when skipUpdate=false + */ + updateObjects() + { + if (this.dirtyTest) + { + for (let object of this.objects) + { + if (object[this.dirty]) + { + this.updateObject(object) + object[this.dirty] = false + } + } + for (let container of this.containers) + { + for (let object of container.children) + { + if (object[this.dirty]) + { + this.updateObject(object) + object[this.dirty] = false + } + } + } + } + else + { + for (let container of this.containers) + { + if (!container.cull.static) + { + container.children.forEach(object => this.updateObject(object)) + } + } + } + } - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } + /** + * update the has of an object + * automatically called from updateObjects() + * @param {*} object + * @param {boolean} [force] force update for calculatePIXI + */ + updateObject(object) + { + let AABB + if (this.calculatePIXI) + { + const box = object.getLocalBounds() + AABB = object[this.AABB] = { + x: object.x + (box.x - object.pivot.x) * object.scale.x, + y: object.y + (box.y - object.pivot.y) * object.scale.y, + width: box.width * object.scale.x, + height: box.height * object.scale.y + } + } + else + { + AABB = object[this.AABB] + } - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. + let spatial = object[this.spatial] + if (!spatial) + { + spatial = object[this.spatial] = { hashes: [] } + } + const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB) - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + // only remove and insert if mapping has changed + if (spatial.xStart !== xStart || spatial.yStart !== yStart || spatial.xEnd !== xEnd || spatial.yEnd !== yEnd) + { + if (spatial.hashes.length) + { + this.removeFromHash(object) + } + for (let y = yStart; y <= yEnd; y++) + { + for (let x = xStart; x <= xEnd; x++) + { + const key = x + ',' + y + this.insert(object, key) + spatial.hashes.push(key) + } + } + spatial.xStart = xStart + spatial.yStart = yStart + spatial.xEnd = xEnd + spatial.yEnd = yEnd + } + } - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + /** + * returns an array of buckets with >= minimum of objects in each bucket + * @param {number} [minimum=1] + * @return {array} array of buckets + */ + getBuckets(minimum=1) + { + const hashes = [] + for (let key in this.hash) + { + const hash = this.hash[key] + if (hash.length >= minimum) + { + hashes.push(hash) + } + } + return hashes + } - if (index >= inputLength) { - error('invalid-input'); - } + /** + * gets hash bounds + * @param {AABB} AABB + * @return {Bounds} + * @private + */ + getBounds(AABB) + { + let xStart = Math.floor(AABB.x / this.xSize) + let yStart = Math.floor(AABB.y / this.ySize) + let xEnd = Math.floor((AABB.x + AABB.width) / this.xSize) + let yEnd = Math.floor((AABB.y + AABB.height) / this.ySize) + return { xStart, yStart, xEnd, yEnd } + } - digit = basicToDigit(input.charCodeAt(index++)); + /** + * insert object into the spatial hash + * automatically called from updateObject() + * @param {*} object + * @param {string} key + */ + insert(object, key) + { + if (!this.hash[key]) + { + this.hash[key] = [object] + } + else + { + this.hash[key].push(object) + } + } - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } + /** + * removes object from the hash table + * should be called when removing an object + * automatically called from updateObject() + * @param {object} object + */ + removeFromHash(object) + { + const spatial = object[this.spatial] + while (spatial.hashes.length) + { + const key = spatial.hashes.pop() + const list = this.hash[key] + list.splice(list.indexOf(object), 1) + } + } - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + /** + * get all neighbors that share the same hash as object + * @param {*} object in the spatial hash + * @return {Array} of objects that are in the same hash as object + */ + neighbors(object) + { + let results = [] + object[this.spatial].hashes.forEach(key => results = results.concat(this.hash[key])) + return results + } - if (digit < t) { - break; - } + /** + * returns an array of objects contained within bounding box + * @param {AABB} AABB bounding box to search + * @param {boolean} [simpleTest=true] perform a simple bounds check of all items in the buckets + * @return {object[]} search results + */ + query(AABB, simpleTest) + { + simpleTest = typeof simpleTest !== 'undefined' ? simpleTest : true + let buckets = 0 + let results = [] + const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB) + for (let y = yStart; y <= yEnd; y++) + { + for (let x = xStart; x <= xEnd; x++) + { + const entry = this.hash[x + ',' + y] + if (entry) + { + if (simpleTest) + { + for (let object of entry) + { + const box = object[this.AABB] + if (box.x + box.width > AABB.x && box.x < AABB.x + AABB.width && + box.y + box.height > AABB.y && box.y < AABB.y + AABB.height) + { + results.push(object) + } + } + } + else + { + results = results.concat(entry) + } + buckets++ + } + } + } + this.lastBuckets = buckets + return results + } - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } + /** + * iterates through objects contained within bounding box + * stops iterating if the callback returns true + * @param {AABB} AABB bounding box to search + * @param {function} callback + * @param {boolean} [simpleTest=true] perform a simple bounds check of all items in the buckets + * @return {boolean} true if callback returned early + */ + queryCallback(AABB, callback, simpleTest) + { + simpleTest = typeof simpleTest !== 'undefined' ? simpleTest : true + const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB) + for (let y = yStart; y <= yEnd; y++) + { + for (let x = xStart; x <= xEnd; x++) + { + const entry = this.hash[x + ',' + y] + if (entry) + { + for (let i = 0; i < entry.length; i++) + { + const object = entry[i] + if (simpleTest) + { + const AABB = object.AABB + if (AABB.x + AABB.width > AABB.x && AABB.x < AABB.x + AABB.width && + AABB.y + AABB.height > AABB.y && AABB.y < AABB.y + AABB.height) + { + if (callback(object)) + { + return true + } + } + } + else + { + if (callback(object)) + { + return true + } + } + } + } + } + } + return false + } - w *= baseMinusT; + /** + * get stats + * @return {Stats} + */ + stats() + { + let visible = 0, count = 0 + for (let list of this.containers) + { + for (let i = 0; i < list.children.length; i++) + { + const object = list.children[i] + visible += object.visible ? 1 : 0 + count++ + } + } + return { + total: count, + visible, + culled: count - visible + } + } - } + /** + * helper function to evaluate hash table + * @return {number} the number of buckets in the hash table + * */ + getNumberOfBuckets() + { + return Object.keys(this.hash).length + } - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); + /** + * helper function to evaluate hash table + * @return {number} the average number of entries in each bucket + */ + getAverageSize() + { + let total = 0 + for (let key in this.hash) + { + total += this.hash[key].length + } + return total / this.getBuckets().length + } - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } + /** + * helper function to evaluate the hash table + * @return {number} the largest sized bucket + */ + getLargest() + { + let largest = 0 + for (let key in this.hash) + { + if (this.hash[key].length > largest) + { + largest = this.hash[key].length + } + } + return largest + } - n += floor(i / out); - i %= out; + /** + * gets quadrant bounds + * @return {Bounds} + */ + getWorldBounds() + { + let xStart = Infinity, yStart = Infinity, xEnd = 0, yEnd = 0 + for (let key in this.hash) + { + const split = key.split(',') + let x = parseInt(split[0]) + let y = parseInt(split[1]) + xStart = x < xStart ? x : xStart + yStart = y < yStart ? y : yStart + xEnd = x > xEnd ? x : xEnd + yEnd = y > yEnd ? y : yEnd + } + return { xStart, yStart, xEnd, yEnd } + } - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); + /** + * helper function to evalute the hash table + * @param {AABB} [AABB] bounding box to search or entire world + * @return {number} sparseness percentage (i.e., buckets with at least 1 element divided by total possible buckets) + */ + getSparseness(AABB) + { + let count = 0, total = 0 + const { xStart, yStart, xEnd, yEnd } = AABB ? this.getBounds(AABB) : this.getWorldBounds() + for (let y = yStart; y < yEnd; y++) + { + for (let x = xStart; x < xEnd; x++) + { + count += (this.hash[x + ',' + y] ? 1 : 0) + total++ + } + } + return count / total + } +} - } +/** + * @typedef {object} Stats + * @property {number} total + * @property {number} visible + * @property {number} culled + */ - return ucs2encode(output); - } +/** + * @typedef {object} Bounds + * @property {number} xStart + * @property {number} yStart + * @property {number} xEnd + * @property {number} xEnd + */ - /** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - function encode(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; +/** + * @typedef {object} AABB + * @property {number} x + * @property {number} y + * @property {number} width + * @property {number} height + */ - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); +module.exports = SpatialHash +},{}],4:[function(require,module,exports){ +const PIXI = window.PIXI = require('pixi.js') +const Viewport = require('pixi-viewport').Viewport +const Random = require('yy-random') +const forkMe = require('fork-me-github') +const FPS = require('yy-fps') - // Cache the length - inputLength = input.length; +const Cull = require('../code') - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; +let _application, _viewport, _dots, _div, _simple, _hash, _mode = 'simple', _stats, _fps //, _test - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } +const START_X = -25000 +const START_Y = -25000 +const WIDTH = 50000 +const HEIGHT = 50000 +const DOTS = 10000 +const DOTS_SIZE = 100 - handledCPCount = basicLength = output.length; +function ui() +{ + _fps = new FPS({ side: 'bottomleft' }) + _div = { + choices: document.getElementById('choices'), + visible: document.getElementById('visible'), + cull: document.getElementById('culled'), + total: document.getElementById('total'), + buckets: document.getElementById('buckets'), + hash: document.getElementById('hash'), + visibleBuckets: document.getElementById('visible-buckets'), + culledBuckets: document.getElementById('culled-buckets'), + totalBuckets: document.getElementById('total-buckets'), + simpleTest: document.getElementById('simple-test'), + dirtyTest: document.getElementById('dirty-test'), + sparseness: document.getElementById('sparseness-buckets'), + largest: document.getElementById('largest-bucket'), + average: document.getElementById('average-bucket') + } - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. + _div.buckets.style.display = _mode === 'hash' ? 'block' : 'none' - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } + _div.choices.addEventListener('change', () => + { + _mode = _div.choices.querySelector('input[name=cull-types]:checked').value + if (_mode === 'none') + { + for (let dot of _dots.children) + { + dot.visible = true + } + } + updateCull() + _div.buckets.style.display = _mode === 'hash' ? 'block' : 'none' + if (_mode === 'hash') + { + _div.sparseness.innerHTML = Math.round(_hash.getSparseness() * 100) + '%' + _div.largest.innerHTML = _hash.getLargest() + _div.average.innerHTML = Math.round(_hash.getAverageSize() * 100) / 100 + _div.hash.style.display = 'block' + } + else + { + _div.hash.style.display = 'none' + } + }) - // Main encoding loop: - while (handledCPCount < inputLength) { + _div.simpleTest.addEventListener('change', () => + { + _hash.simpleTest = _div.simpleTest.checked + updateCull() + }) - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } + _div.dirtyTest.addEventListener('change', () => + { + _hash.dirtyTest = _simple.dirtyTest = _div.dirtyTest.checked + }) - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } + document.querySelector('.instructions').style.opacity = 0; + forkMe(null, { side: 'left' }) +} - delta += (m - n) * handledCPCountPlusOne; - n = m; +function pixi() +{ + const view = document.querySelector('.pixi') + _application = new PIXI.Application({ width: view.offsetWidth, height: view.offsetHeight, view, transparent: true }) + _viewport = _application.stage.addChild(new Viewport()) + _viewport.drag().pinch().decelerate().wheel() + _viewport.resize(view.offsetWidth, view.offsetHeight, WIDTH, HEIGHT) + _viewport.fitWidth(5000) + const ticker = PIXI.ticker || PIXI.Ticker + ticker.shared.add(update) + // _test = _viewport.addChild(new PIXI.Graphics()) - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; + window.addEventListener('resize', () => { + // weird hack needed for flexbox to work correctly; probably a better way to do this + _application.renderer.resize(0, 0) - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } + _viewport.resize(view.offsetWidth, view.offsetHeight) + _application.renderer.resize(view.offsetWidth, view.offsetHeight) + _viewport.dirty = true + }) +} - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } +function dots() +{ + _dots = _viewport.addChild(new PIXI.Container()) + for (let i = 0; i < DOTS; i++) + { + const dot = _dots.addChild(new PIXI.Sprite(PIXI.Texture.WHITE)) + dot.tint = Random.color() + dot.width = dot.height = DOTS_SIZE + dot.position.set(Random.range(START_X, WIDTH), Random.range(START_Y, HEIGHT)) + } - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } + _simple = new Cull.Simple() + _simple.addList(_dots.children, true) + _hash = new Cull.SpatialHash() + _hash.addContainer(_dots, true) +} - ++delta; - ++n; +function update() +{ + if (_viewport.dirty) + { + updateCull() + _viewport.dirty = false + } + _fps.frame() +} - } - return output.join(''); - } +function updateCull() +{ + switch (_mode) + { + case 'simple': + _simple.cull(_viewport.getVisibleBounds()) + _stats = _simple.stats() + break - /** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ - function toUnicode(input) { - return mapDomain(input, function(string) { - return regexPunycode.test(string) - ? decode(string.slice(4).toLowerCase()) - : string; - }); - } + case 'hash': + const visible = _div.visibleBuckets.innerHTML = _hash.cull(_viewport.getVisibleBounds()) + const total = _div.totalBuckets.innerHTML = _hash.getBuckets().length + _div.culledBuckets.innerHTML = total - visible + _stats = _hash.stats() + break - /** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ - function toASCII(input) { - return mapDomain(input, function(string) { - return regexNonASCII.test(string) - ? 'xn--' + encode(string) - : string; - }); - } + case 'none': + _stats = { visible: _dots.children.length, culled: 0, total: _dots.children.length } + break + } + _viewport.dirty = false + _div.visible.innerHTML = _stats.visible + _div.cull.innerHTML = _stats.culled + _div.total.innerHTML = _stats.total +} - /*--------------------------------------------------------------------------*/ +window.onload = () => +{ + pixi() + dots() + ui() + updateCull() +} +},{"../code":1,"fork-me-github":42,"pixi-viewport":48,"pixi.js":49,"yy-fps":61,"yy-random":62}],5:[function(require,module,exports){ +/*! + * @pixi/accessibility - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/accessibility is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - /** Define the public API */ - punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '1.4.1', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; +Object.defineProperty(exports, '__esModule', { value: true }); - /** Expose `punycode` */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd - ) { - define('punycode', function() { - return punycode; - }); - } else if (freeExports && freeModule) { - if (module.exports == freeExports) { - // in Node.js, io.js, or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else { - // in Narwhal or RingoJS v0.7.0- - for (key in punycode) { - punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); - } - } - } else { - // in Rhino or a web browser - root.punycode = punycode; - } +var display = require('@pixi/display'); +var utils = require('@pixi/utils'); -}(this)); +/** + * Default property values of accessible objects + * used by {@link PIXI.AccessibilityManager}. + * + * @private + * @function accessibleTarget + * @memberof PIXI + * @type {Object} + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibleTarget + * ); + */ +var accessibleTarget = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + accessible: false, + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {?string} + * @memberof PIXI.DisplayObject# + */ + accessibleTitle: null, + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + * @memberof PIXI.DisplayObject# + */ + accessibleHint: null, + /** + * @member {number} + * @memberof PIXI.DisplayObject# + * @private + * @todo Needs docs. + */ + tabIndex: 0, + /** + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @todo Needs docs. + */ + _accessibleActive: false, + /** + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @todo Needs docs. + */ + _accessibleDiv: null, + /** + * Specify the type of div the accessible layer is. Screen readers treat the element differently + * depending on this type. Defaults to button. + * + * @member {string} + * @memberof PIXI.DisplayObject# + * @default 'button' + */ + accessibleType: 'button', + /** + * Specify the pointer-events the accessible div will use + * Defaults to auto. + * + * @member {string} + * @memberof PIXI.DisplayObject# + * @default 'auto' + */ + accessiblePointerEvents: 'auto', + /** + * Setting to false will prevent any children inside this container to + * be accessible. Defaults to true. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @default true + */ + accessibleChildren: true, + renderId: -1, +}; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],4:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +// add some extra variables to the container.. +display.DisplayObject.mixin(accessibleTarget); +var KEY_CODE_TAB = 9; +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; +/** + * The Accessibility manager recreates the ability to tab and have content read by screen readers. + * This is very important as it can possibly help people with disabilities access PixiJS content. + * + * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility` + * + * @class + * @memberof PIXI + */ +var AccessibilityManager = /** @class */ (function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + /** + * @type {?HTMLElement} + * @private + */ + this._hookDiv = null; + if (utils.isMobile.tablet || utils.isMobile.phone) { + this.createTouchHook(); + } + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + div.style.width = DIV_TOUCH_SIZE + "px"; + div.style.height = DIV_TOUCH_SIZE + "px"; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + "px"; + div.style.left = DIV_TOUCH_POS_Y + "px"; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + /** + * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + /** + * Setting this to true will visually show the divs. + * + * @type {boolean} + */ + this.debug = false; + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.AbstractRenderer} + */ + this.renderer = renderer; + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + /** + * pre-bind the functions + * + * @type {Function} + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + /** + * pre-bind the functions + * + * @type {Function} + * @private + */ + this._onMouseMove = this._onMouseMove.bind(this); + this._isActive = false; + this._isMobileAccessibility = false; + /** + * count to throttle div updates on android devices + * @type number + * @private + */ + this.androidUpdateCount = 0; + /** + * the frequency to update the div elements () + * @private + */ + this.androidUpdateFrequency = 500; // 2fps + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + Object.defineProperty(AccessibilityManager.prototype, "isActive", { + /** + * A flag + * @member {boolean} + * @readonly + */ + get: function () { + return this._isActive; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", { + /** + * A flag + * @member {boolean} + * @readonly + */ + get: function () { + return this._isMobileAccessibility; + }, + enumerable: false, + configurable: true + }); + /** + * Creates the touch hooks. + * + * @private + */ + AccessibilityManager.prototype.createTouchHook = function () { + var _this = this; + var hookDiv = document.createElement('button'); + hookDiv.style.width = DIV_HOOK_SIZE + "px"; + hookDiv.style.height = DIV_HOOK_SIZE + "px"; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + "px"; + hookDiv.style.left = DIV_HOOK_POS_Y + "px"; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(); + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'select to enable accessability for this content'; + hookDiv.addEventListener('focus', function () { + _this._isMobileAccessibility = true; + _this.activate(); + _this.destroyTouchHook(); + }); + document.body.appendChild(hookDiv); + this._hookDiv = hookDiv; + }; + /** + * Destroys the touch hooks. + * + * @private + */ + AccessibilityManager.prototype.destroyTouchHook = function () { + if (!this._hookDiv) { + return; + } + document.body.removeChild(this._hookDiv); + this._hookDiv = null; + }; + /** + * Activating will cause the Accessibility layer to be shown. + * This is called when a user presses the tab key. + * + * @private + */ + AccessibilityManager.prototype.activate = function () { + if (this._isActive) { + return; + } + this._isActive = true; + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + // TODO: Remove casting when CanvasRenderer is converted + this.renderer.on('postrender', this.update, this); + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + /** + * Deactivating will cause the Accessibility layer to be hidden. + * This is called when a user moves the mouse. + * + * @private + */ + AccessibilityManager.prototype.deactivate = function () { + if (!this._isActive || this._isMobileAccessibility) { + return; + } + this._isActive = false; + window.document.removeEventListener('mousemove', this._onMouseMove, true); + window.addEventListener('keydown', this._onKeyDown, false); + // TODO: Remove casting when CanvasRenderer is converted + this.renderer.off('postrender', this.update); + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) { + if (!displayObject.visible || !displayObject.accessibleChildren) { + return; + } + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + displayObject.renderId = this.renderId; + } + var children = displayObject.children; + for (var i = 0; i < children.length; i++) { + this.updateAccessibleObjects(children[i]); + } + }; + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + AccessibilityManager.prototype.update = function () { + /* On Android default web browser, tab order seems to be calculated by position rather than tabIndex, + * moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate, + * so I am just running update every half a second, seems to fix it. + */ + var now = performance.now(); + if (utils.isMobile.android.device && now < this.androidUpdateCount) { + return; + } + this.androidUpdateCount = now + this.androidUpdateFrequency; + if (!this.renderer.renderingToScreen) { + return; + } + // update children... + if (this.renderer._lastObjectRendered) { + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + } + // TODO: Remove casting when CanvasRenderer is converted + var rect = this.renderer.view.getBoundingClientRect(); + var resolution = this.renderer.resolution; + var sx = (rect.width / this.renderer.width) * resolution; + var sy = (rect.height / this.renderer.height) * resolution; + var div = this.div; + div.style.left = rect.left + "px"; + div.style.top = rect.top + "px"; + div.style.width = this.renderer.width + "px"; + div.style.height = this.renderer.height + "px"; + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + i--; + } + else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + if (child.hitArea) { + div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px"; + div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px"; + div.style.width = hitArea.width * wt.a * sx + "px"; + div.style.height = hitArea.height * wt.d * sy + "px"; + } + else { + hitArea = child.getBounds(); + this.capHitArea(hitArea); + div.style.left = hitArea.x * sx + "px"; + div.style.top = hitArea.y * sy + "px"; + div.style.width = hitArea.width * sx + "px"; + div.style.height = hitArea.height * sy + "px"; + // update button titles and hints if they exist and they've changed + if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { + div.title = child.accessibleTitle; + } + if (div.getAttribute('aria-label') !== child.accessibleHint + && child.accessibleHint !== null) { + div.setAttribute('aria-label', child.accessibleHint); + } + } + // the title or index may have changed, if so lets update it! + if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) { + div.title = child.accessibleTitle; + div.tabIndex = child.tabIndex; + if (this.debug) + { this.updateDebugHTML(div); } + } + } + } + // increment the render id.. + this.renderId++; + }; + /** + * private function that will visually add the information to the + * accessability div + * + * @param {HTMLElement} div + */ + AccessibilityManager.prototype.updateDebugHTML = function (div) { + div.innerHTML = "type: " + div.type + "
title : " + div.title + "
tabIndex: " + div.tabIndex; + }; + /** + * Adjust the hit area based on the bounds of a display object + * + * @param {PIXI.Rectangle} hitArea - Bounds of the child + */ + AccessibilityManager.prototype.capHitArea = function (hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + // TODO: Remove casting when CanvasRenderer is converted + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {PIXI.DisplayObject} displayObject - The child to make accessible. + */ + AccessibilityManager.prototype.addChild = function (displayObject) { + // this.activate(); + var div = this.pool.pop(); + if (!div) { + div = document.createElement('button'); + div.style.width = DIV_TOUCH_SIZE + "px"; + div.style.height = DIV_TOUCH_SIZE + "px"; + div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + div.style.borderStyle = 'none'; + // ARIA attributes ensure that button title and hint updates are announced properly + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. + div.setAttribute('aria-live', 'off'); + } + else { + div.setAttribute('aria-live', 'polite'); + } + if (navigator.userAgent.match(/rv:.*Gecko\//)) { + // FireFox needs this to announce only the new button name + div.setAttribute('aria-relevant', 'additions'); + } + else { + // required by IE, other browsers don't much care + div.setAttribute('aria-relevant', 'text'); + } + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + // set pointer events + div.style.pointerEvents = displayObject.accessiblePointerEvents; + // set the type, this defaults to button! + div.type = displayObject.accessibleType; + if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { + div.title = displayObject.accessibleTitle; + } + else if (!displayObject.accessibleHint + || displayObject.accessibleHint === null) { + div.title = "displayObject " + displayObject.tabIndex; + } + if (displayObject.accessibleHint + && displayObject.accessibleHint !== null) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + if (this.debug) + { this.updateDebugHTML(div); } + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + AccessibilityManager.prototype._onClick = function (e) { + // TODO: Remove casting when CanvasRenderer is converted + var interactionManager = this.renderer.plugins.interaction; + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + interactionManager.dispatchEvent(e.target.displayObject, 'pointertap', interactionManager.eventData); + interactionManager.dispatchEvent(e.target.displayObject, 'tap', interactionManager.eventData); + }; + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + AccessibilityManager.prototype._onFocus = function (e) { + if (!e.target.getAttribute('aria-live')) { + e.target.setAttribute('aria-live', 'assertive'); + } + // TODO: Remove casting when CanvasRenderer is converted + var interactionManager = this.renderer.plugins.interaction; + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + AccessibilityManager.prototype._onFocusOut = function (e) { + if (!e.target.getAttribute('aria-live')) { + e.target.setAttribute('aria-live', 'polite'); + } + // TODO: Remove casting when CanvasRenderer is converted + var interactionManager = this.renderer.plugins.interaction; + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + AccessibilityManager.prototype._onKeyDown = function (e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + this.activate(); + }; + /** + * Is called when the mouse moves across the renderer element + * + * @private + * @param {MouseEvent} e - The mouse event. + */ + AccessibilityManager.prototype._onMouseMove = function (e) { + if (e.movementX === 0 && e.movementY === 0) { + return; + } + this.deactivate(); + }; + /** + * Destroys the accessibility manager + * + */ + AccessibilityManager.prototype.destroy = function () { + this.destroyTouchHook(); + this.div = null; + window.document.removeEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown); + this.pool = null; + this.children = null; + this.renderer = null; + }; + return AccessibilityManager; +}()); + +exports.AccessibilityManager = AccessibilityManager; +exports.accessibleTarget = accessibleTarget; + +},{"@pixi/display":9,"@pixi/utils":38}],6:[function(require,module,exports){ +/*! + * @pixi/app - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/app is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ 'use strict'; -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} +Object.defineProperty(exports, '__esModule', { value: true }); -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; +var display = require('@pixi/display'); +var core = require('@pixi/core'); - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } +/** + * Convenience class to create a new PIXI application. + * + * This class automatically creates the renderer, ticker and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.from('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = /** @class */ (function () { + /** + * @param {object} [options] - The optional renderer parameters. + * @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction. + * **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set + * options.sharedTicker to true in case that it is already started. Stop it by your own. + * @param {number} [options.width=800] - The width of the renderers view. + * @param {number} [options.height=600] - The height of the renderers view. + * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. + * @param {boolean} [options.transparent=false] - If the render view is transparent. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1. + * @param {boolean} [options.antialias=false] - Sets antialias + * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the WebGL context. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2. + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this + * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise + * it is ignored. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card. **(WebGL only)**. + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker. + * If set to false, you cannot register a handler to occur before anything that runs on the shared ticker. + * The system ticker will always run before both the shared ticker and the app ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader. + * @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to. + */ + function Application(options) { + var _this = this; + // The default options + options = Object.assign({ + forceCanvas: false, + }, options); + /** + * WebGL renderer if available, otherwise CanvasRenderer. + * @member {PIXI.Renderer|PIXI.CanvasRenderer} + */ + this.renderer = core.autoDetectRenderer(options); + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new display.Container(); + // install plugins here + Application._plugins.forEach(function (plugin) { + plugin.init.call(_this, options); + }); + } + /** + * Register a middleware plugin for the application + * @static + * @param {PIXI.Application.Plugin} plugin - Plugin being installed + */ + Application.registerPlugin = function (plugin) { + Application._plugins.push(plugin); + }; + /** + * Render the current stage. + */ + Application.prototype.render = function () { + // TODO: Since CanvasRenderer has not been converted this function thinks it takes DisplayObject & PIXI.DisplayObject + // This can be fixed when CanvasRenderer is converted. + this.renderer.render(this.stage); + }; + Object.defineProperty(Application.prototype, "view", { + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + get: function () { + return this.renderer.view; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Application.prototype, "screen", { + /** + * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen. + * @member {PIXI.Rectangle} + * @readonly + */ + get: function () { + return this.renderer.screen; + }, + enumerable: false, + configurable: true + }); + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] - Automatically remove canvas from DOM. + * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy + * method called as well. 'stageOptions' will be passed on to those calls. + * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the texture of the child sprite + * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the base texture of the child sprite + */ + Application.prototype.destroy = function (removeView, stageOptions) { + var _this = this; + // Destroy plugins in the opposite order + // which they were constructed + var plugins = Application._plugins.slice(0); + plugins.reverse(); + plugins.forEach(function (plugin) { + plugin.destroy.call(_this); + }); + this.stage.destroy(stageOptions); + this.stage = null; + this.renderer.destroy(removeView); + this.renderer = null; + }; + return Application; +}()); +/** + * @memberof PIXI.Application + * @typedef {object} Plugin + * @property {function} init - Called when Application is constructed, scoped to Application instance. + * Passes in `options` as the only argument, which are Application constructor options. + * @property {function} destroy - Called when destroying Application, scoped to Application instance + */ +/** + * Collection of installed plugins. + * @static + * @private + * @type {PIXI.Application.Plugin[]} + */ +Application._plugins = []; - var regexp = /\+/g; - qs = qs.split(sep); +/** + * Middleware for for Application's resize functionality + * @private + * @class + */ +var ResizePlugin = /** @class */ (function () { + function ResizePlugin() { + } + /** + * Initialize the plugin with scope of application instance + * @static + * @private + * @param {object} [options] - See application options + */ + ResizePlugin.init = function (options) { + var _this = this; + /** + * The HTML element or window to automatically resize the + * renderer's view element to match width and height. + * @type {Window|HTMLElement} + * @name resizeTo + * @memberof PIXI.Application# + */ + Object.defineProperty(this, 'resizeTo', { + set: function (dom) { + window.removeEventListener('resize', this.queueResize); + this._resizeTo = dom; + if (dom) { + window.addEventListener('resize', this.queueResize); + this.resize(); + } + }, + get: function () { + return this._resizeTo; + }, + }); + /** + * Resize is throttled, so it's + * safe to call this multiple times per frame and it'll + * only be called once. + * @method PIXI.Application#queueResize + */ + this.queueResize = function () { + if (!_this._resizeTo) { + return; + } + _this.cancelResize(); + // // Throttle resize events per raf + _this._resizeId = requestAnimationFrame(function () { return _this.resize(); }); + }; + /** + * Cancel the resize queue. + * @method PIXI.Application#cancelResize + * @private + */ + this.cancelResize = function () { + if (_this._resizeId) { + cancelAnimationFrame(_this._resizeId); + _this._resizeId = null; + } + }; + /** + * Execute an immediate resize on the renderer, this is not + * throttled and can be expensive to call many times in a row. + * Will resize only if `resizeTo` property is set. + * @method PIXI.Application#resize + */ + this.resize = function () { + if (!_this._resizeTo) { + return; + } + // clear queue resize + _this.cancelResize(); + var width; + var height; + // Resize to the window + if (_this._resizeTo === window) { + width = window.innerWidth; + height = window.innerHeight; + } + // Resize to other HTML entities + else { + var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight; + width = clientWidth; + height = clientHeight; + } + _this.renderer.resize(width, height); + }; + // On resize + this._resizeId = null; + this._resizeTo = null; + this.resizeTo = options.resizeTo || null; + }; + /** + * Clean up the ticker, scoped to application + * @static + * @private + */ + ResizePlugin.destroy = function () { + this.cancelResize(); + this.cancelResize = null; + this.queueResize = null; + this.resizeTo = null; + this.resize = null; + }; + return ResizePlugin; +}()); - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } +Application.registerPlugin(ResizePlugin); - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } +exports.Application = Application; - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } +},{"@pixi/core":8,"@pixi/display":9}],7:[function(require,module,exports){ +/*! + * @pixi/constants - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); +Object.defineProperty(exports, '__esModule', { value: true }); - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - - return obj; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; +/** + * Different types of environments for WebGL. + * + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ +(function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; +})(exports.ENV || (exports.ENV = {})); +(function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; +})(exports.RENDERER_TYPE || (exports.RENDERER_TYPE = {})); +(function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; +})(exports.BUFFER_BITS || (exports.BUFFER_BITS = {})); +(function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; +})(exports.BLEND_MODES || (exports.BLEND_MODES = {})); +(function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; +})(exports.DRAW_MODES || (exports.DRAW_MODES = {})); +(function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; +})(exports.FORMATS || (exports.FORMATS = {})); +(function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; +})(exports.TARGETS || (exports.TARGETS = {})); +(function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; +})(exports.TYPES || (exports.TYPES = {})); +(function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; +})(exports.SCALE_MODES || (exports.SCALE_MODES = {})); +(function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; +})(exports.WRAP_MODES || (exports.WRAP_MODES = {})); +(function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; +})(exports.MIPMAP_MODES || (exports.MIPMAP_MODES = {})); +(function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; +})(exports.ALPHA_MODES || (exports.ALPHA_MODES = {})); +(function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; +})(exports.CLEAR_MODES || (exports.CLEAR_MODES = {})); +(function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; +})(exports.GC_MODES || (exports.GC_MODES = {})); +(function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; +})(exports.PRECISION || (exports.PRECISION = {})); +(function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; +})(exports.MASK_TYPES || (exports.MASK_TYPES = {})); +(function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; +})(exports.MSAA_QUALITY || (exports.MSAA_QUALITY = {})); -},{}],5:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +},{}],8:[function(require,module,exports){ +/*! + * @pixi/core - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/core is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ 'use strict'; -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } -}; - -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return map(objectKeys(obj), function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (isArray(obj[k])) { - return map(obj[k], function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - - } +Object.defineProperty(exports, '__esModule', { value: true }); - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; +var settings = require('@pixi/settings'); +var constants = require('@pixi/constants'); +var utils = require('@pixi/utils'); +var runner = require('@pixi/runner'); +var ticker = require('@pixi/ticker'); +var math = require('@pixi/math'); -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; +/** + * The maximum support for using WebGL. If a device does not + * support WebGL version, for instance WebGL 2, it will still + * attempt to fallback support to WebGL 1. If you want to + * explicitly remove feature support to target a more stable + * baseline, prefer a lower environment. + * + * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium} + * we disable webgl2 by default for all non-apple mobile devices. + * + * @static + * @name PREFER_ENV + * @memberof PIXI.settings + * @type {number} + * @default PIXI.ENV.WEBGL2 + */ +settings.settings.PREFER_ENV = utils.isMobile.any ? constants.ENV.WEBGL : constants.ENV.WEBGL2; +/** + * If set to `true`, *only* Textures and BaseTexture objects stored + * in the caches ({@link PIXI.utils.TextureCache TextureCache} and + * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can be + * used when calling {@link PIXI.Texture.from Texture.from} or + * {@link PIXI.BaseTexture.from BaseTexture.from}. + * Otherwise, these `from` calls throw an exception. Using this property + * can be useful if you want to enforce preloading all assets with + * {@link PIXI.Loader Loader}. + * + * @static + * @name STRICT_TEXTURE_CACHE + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ +settings.settings.STRICT_TEXTURE_CACHE = false; -function map (xs, f) { - if (xs.map) return xs.map(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - res.push(f(xs[i], i)); - } - return res; +/** + * Collection of installed resource types, class must extend {@link PIXI.resources.Resource}. + * @example + * class CustomResource extends PIXI.resources.Resource { + * // MUST have source, options constructor signature + * // for auto-detected resources to be created. + * constructor(source, options) { + * super(); + * } + * upload(renderer, baseTexture, glTexture) { + * // upload with GL + * return true; + * } + * // used to auto-detect resource + * static test(source, extension) { + * return extension === 'xyz'|| source instanceof SomeClass; + * } + * } + * // Install the new resource type + * PIXI.resources.INSTALLED.push(CustomResource); + * + * @name PIXI.resources.INSTALLED + * @type {Array<*>} + * @static + * @readonly + */ +var INSTALLED = []; +/** + * Create a resource element from a single source element. This + * auto-detects which type of resource to create. All resources that + * are auto-detectable must have a static `test` method and a constructor + * with the arguments `(source, options?)`. Currently, the supported + * resources for auto-detection include: + * - {@link PIXI.resources.ImageResource} + * - {@link PIXI.resources.CanvasResource} + * - {@link PIXI.resources.VideoResource} + * - {@link PIXI.resources.SVGResource} + * - {@link PIXI.resources.BufferResource} + * @static + * @function PIXI.resources.autoDetectResource + * @param {string|*} source - Resource source, this can be the URL to the resource, + * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri + * or any other resource that can be auto-detected. If not resource is + * detected, it's assumed to be an ImageResource. + * @param {object} [options] - Pass-through options to use for Resource + * @param {number} [options.width] - Width of BufferResource or SVG rasterization + * @param {number} [options.height] - Height of BufferResource or SVG rasterization + * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading + * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height + * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object + * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin + * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately + * @param {number} [options.updateFPS=0] - Video option to update how many times a second the + * texture should be updated from the video. Leave at 0 to update at every render + * @return {PIXI.resources.Resource} The created resource. + */ +function autoDetectResource(source, options) { + if (!source) { + return null; + } + var extension = ''; + if (typeof source === 'string') { + // search for file extension: period, 3-4 chars, then ?, # or EOL + var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source); + if (result) { + extension = result[1].toLowerCase(); + } + } + for (var i = INSTALLED.length - 1; i >= 0; --i) { + var ResourcePlugin = INSTALLED[i]; + if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) { + return new ResourcePlugin(source, options); + } + } + throw new Error('Unrecognized source type to auto-detect Resource'); } -var objectKeys = Object.keys || function (obj) { - var res = []; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); - } - return res; -}; - -},{}],6:[function(require,module,exports){ -'use strict'; - -exports.decode = exports.parse = require('./decode'); -exports.encode = exports.stringify = require('./encode'); - -},{"./decode":4,"./encode":5}],7:[function(require,module,exports){ -(function (setImmediate,clearImmediate){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); +/** + * Base resource class for textures that manages validation and uploading, depending on its type. + * + * Uploading of a base texture to the GPU is required. + * + * @class + * @memberof PIXI.resources + */ +var Resource = /** @class */ (function () { + /** + * @param {number} [width=0] - Width of the resource + * @param {number} [height=0] - Height of the resource + */ + function Resource(width, height) { + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + /** + * Internal width of the resource + * @member {number} + * @protected + */ + this._width = width; + /** + * Internal height of the resource + * @member {number} + * @protected + */ + this._height = height; + /** + * If resource has been destroyed + * @member {boolean} + * @readonly + * @default false + */ + this.destroyed = false; + /** + * `true` if resource is created by BaseTexture + * useful for doing cleanup with BaseTexture destroy + * and not cleaning up resources that were created + * externally. + * @member {boolean} + * @protected + */ + this.internal = false; + /** + * Mini-runner for handling resize events + * accepts 2 parameters: width, height + * + * @member {Runner} + * @private + */ + this.onResize = new runner.Runner('setRealSize'); + /** + * Mini-runner for handling update events + * + * @member {Runner} + * @private + */ + this.onUpdate = new runner.Runner('update'); + /** + * Handle internal errors, such as loading errors + * accepts 1 param: error + * + * @member {Runner} + * @private + */ + this.onError = new runner.Runner('onError'); } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":2,"timers":7}],8:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var punycode = require('punycode'); -var util = require('./util'); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; - -function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.host = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.query = null; - this.pathname = null; - this.path = null; - this.href = null; -} - -// Reference: RFC 3986, RFC 1808, RFC 2396 - -// define these here so at least they only have to be -// compiled once on the first module load. -var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }, - querystring = require('querystring'); - -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) return url; - - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; -} - -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } - - // Copy chrome, IE, opera backslash-handling behavior. - // Back slashes before the query string get converted to forward slashes - // See: https://code.google.com/p/chromium/issues/detail?id=25916 - var queryIndex = url.indexOf('?'), - splitter = - (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', - uSplit = url.split(splitter), - slashRegex = /\\/g; - uSplit[0] = uSplit[0].replace(slashRegex, '/'); - url = uSplit.join(splitter); - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - var simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.path = rest; - this.href = rest; - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - if (parseQueryString) { - this.query = querystring.parse(this.search.substr(1)); - } else { - this.query = this.search.substr(1); + /** + * Bind to a parent BaseTexture + * + * @param {PIXI.BaseTexture} baseTexture - Parent texture + */ + Resource.prototype.bind = function (baseTexture) { + this.onResize.add(baseTexture); + this.onUpdate.add(baseTexture); + this.onError.add(baseTexture); + // Call a resize immediate if we already + // have the width and height of the resource + if (this._width || this._height) { + this.onResize.emit(this._width, this._height); } - } else if (parseQueryString) { - this.search = ''; - this.query = {}; - } - return this; - } - } - - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; - - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } + }; + /** + * Unbind to a parent BaseTexture + * + * @param {PIXI.BaseTexture} baseTexture - Parent texture + */ + Resource.prototype.unbind = function (baseTexture) { + this.onResize.remove(baseTexture); + this.onUpdate.remove(baseTexture); + this.onError.remove(baseTexture); + }; + /** + * Trigger a resize event + * @param {number} width - X dimension + * @param {number} height - Y dimension + */ + Resource.prototype.resize = function (width, height) { + if (width !== this._width || height !== this._height) { + this._width = width; + this._height = height; + this.onResize.emit(width, height); } - } - } - - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } - - if (!ipv6Hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - this.hostname = punycode.toASCII(this.hostname); - } - - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } - } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - if (rest.indexOf(ae) === -1) - continue; - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } - } - - - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; - } - if (rest) this.pathname = rest; - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; - } - - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } - - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; -}; - -// format a parsed object into a url string -function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (util.isString(obj)) obj = urlParse(obj); - if (!(obj instanceof Url)) return Url.prototype.format.call(obj); - return obj.format(); -} - -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } - - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; + }; + Object.defineProperty(Resource.prototype, "valid", { + /** + * Has been validated + * @readonly + * @member {boolean} + */ + get: function () { + return !!this._width && !!this._height; + }, + enumerable: false, + configurable: true + }); + /** + * Has been updated trigger event + */ + Resource.prototype.update = function () { + if (!this.destroyed) { + this.onUpdate.emit(); + } + }; + /** + * This can be overridden to start preloading a resource + * or do any other prepare step. + * @protected + * @return {Promise} Handle the validate event + */ + Resource.prototype.load = function () { + return Promise.resolve(this); + }; + Object.defineProperty(Resource.prototype, "width", { + /** + * The width of the resource. + * + * @member {number} + * @readonly + */ + get: function () { + return this._width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Resource.prototype, "height", { + /** + * The height of the resource. + * + * @member {number} + * @readonly + */ + get: function () { + return this._height; + }, + enumerable: false, + configurable: true + }); + /** + * Set the style, optional to override + * + * @param {PIXI.Renderer} renderer - yeah, renderer! + * @param {PIXI.BaseTexture} baseTexture - the texture + * @param {PIXI.GLTexture} glTexture - texture instance for this webgl context + * @returns {boolean} `true` is success + */ + Resource.prototype.style = function (_renderer, _baseTexture, _glTexture) { + return false; + }; + /** + * Clean up anything, this happens when destroying is ready. + * + * @protected + */ + Resource.prototype.dispose = function () { + // override + }; + /** + * Call when destroying resource, unbind any BaseTexture object + * before calling this method, as reference counts are maintained + * internally. + */ + Resource.prototype.destroy = function () { + if (!this.destroyed) { + this.destroyed = true; + this.dispose(); + this.onError.removeAll(); + this.onError = null; + this.onResize.removeAll(); + this.onResize = null; + this.onUpdate.removeAll(); + this.onUpdate = null; + } + }; + /** + * Abstract, used to auto-detect resource type + * + * @static + * @param {*} source - The source object + * @param {string} extension - The extension of source, if set + */ + Resource.test = function (_source, _extension) { + return false; + }; + return Resource; +}()); - if (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; +/** + * @interface SharedArrayBuffer + */ +/** + * Buffer resource with data of typed array. + * @class + * @extends PIXI.resources.Resource + * @memberof PIXI.resources + */ +var BufferResource = /** @class */ (function (_super) { + __extends(BufferResource, _super); + /** + * @param {Float32Array|Uint8Array|Uint32Array} source - Source buffer + * @param {object} options - Options + * @param {number} options.width - Width of the texture + * @param {number} options.height - Height of the texture + */ + function BufferResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + if (!width || !height) { + throw new Error('BufferResource width or height invalid'); + } + _this = _super.call(this, width, height) || this; + /** + * Source array + * Cannot be ClampedUint8Array because it cant be uploaded to WebGL + * + * @member {Float32Array|Uint8Array|Uint32Array} + */ + _this.data = source; + return _this; } - } - - if (this.query && - util.isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); - } - - var search = this.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; - } else if (!host) { - host = ''; - } - - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; - - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); - - return protocol + host + pathname + search + hash; -}; - -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} + /** + * Upload the texture to the GPU. + * @param {PIXI.Renderer} renderer - Upload to the renderer + * @param {PIXI.BaseTexture} baseTexture - Reference to parent texture + * @param {PIXI.GLTexture} glTexture - glTexture + * @returns {boolean} true is success + */ + BufferResource.prototype.upload = function (renderer, baseTexture, glTexture) { + var gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants.ALPHA_MODES.UNPACK); + if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, baseTexture.width, baseTexture.height, baseTexture.format, baseTexture.type, this.data); + } + else { + glTexture.width = baseTexture.width; + glTexture.height = baseTexture.height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.width, baseTexture.height, 0, baseTexture.format, glTexture.type, this.data); + } + return true; + }; + /** + * Destroy and don't use after this + * @override + */ + BufferResource.prototype.dispose = function () { + this.data = null; + }; + /** + * Used to auto-detect the type of resource. + * + * @static + * @param {*} source - The source object + * @return {boolean} `true` if + */ + BufferResource.test = function (source) { + return source instanceof Float32Array + || source instanceof Uint8Array + || source instanceof Uint32Array; + }; + return BufferResource; +}(Resource)); -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); +var defaultBufferOptions = { + scaleMode: constants.SCALE_MODES.NEAREST, + format: constants.FORMATS.RGBA, + alphaMode: constants.ALPHA_MODES.NPM, }; - -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); -} - -Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } - - var result = new Url(); - var tkeys = Object.keys(this); - for (var tk = 0; tk < tkeys.length; tk++) { - var tkey = tkeys[tk]; - result[tkey] = this[tkey]; - } - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } - - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - var rkeys = Object.keys(relative); - for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; - if (rkey !== 'protocol') - result[rkey] = relative[rkey]; - } - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; - } - - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - var keys = Object.keys(relative); - for (var v = 0; v < keys.length; v++) { - var k = keys[v]; - result[k] = relative[k]; - } - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } - - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; - } - - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..') || last === ''); - - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } - - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } - - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } - - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } - - //to support request.http - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; -}; - -Url.prototype.parseHost = function() { - var host = this.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); - } - if (host) this.hostname = host; -}; - -},{"./util":9,"punycode":3,"querystring":6}],9:[function(require,module,exports){ -'use strict'; - -module.exports = { - isString: function(arg) { - return typeof(arg) === 'string'; - }, - isObject: function(arg) { - return typeof(arg) === 'object' && arg !== null; - }, - isNull: function(arg) { - return arg === null; - }, - isNullOrUndefined: function(arg) { - return arg == null; - } -}; - -},{}],10:[function(require,module,exports){ -module.exports = { - Simple: require('./simple'), - SpatialHash: require('./spatial-hash') -} -},{"./simple":11,"./spatial-hash":12}],11:[function(require,module,exports){ -// pixi-cull.SpatialHash -// Copyright 2018 YOPEY YOPEY LLC -// David Figatner -// MIT License - -class Simple -{ - /** - * creates a simple cull - * @param {object} [options] - * @param {boolean} [options.visible=visible] parameter of the object to set (usually visible or renderable) - * @param {boolean} [options.calculatePIXI=true] calculate pixi.js bounding box automatically; if this is set to false then it uses object[options.AABB] for bounding box - * @param {string} [options.dirtyTest=true] only update spatial hash for objects with object[options.dirtyTest]=true; this has a HUGE impact on performance - * @param {string} [options.AABB=AABB] object property that holds bounding box so that object[type] = { x: number, y: number, width: number, height: number }; not needed if options.calculatePIXI=true - */ - constructor(options) - { - options = options || {} - this.visible = options.visible || 'visible' - this.calculatePIXI = typeof options.calculatePIXI !== 'undefined' ? options.calculatePIXI : true - this.dirtyTest = typeof options.dirtyTest !== 'undefined' ? options.dirtyTest : true - this.AABB = options.AABB || 'AABB' - this.lists = [[]] - } - - /** - * add an array of objects to be culled - * @param {Array} array - * @param {boolean} [staticObject] set to true if the object's position/size does not change - * @return {Array} array - */ - addList(array, staticObject) - { - this.lists.push(array) - if (staticObject) - { - array.staticObject = true - } - if (this.calculatePIXI && this.dirtyTest) - { - for (let object of array) - { - this.updateObject(object) - } - } - return array - } - - /** - * remove an array added by addList() - * @param {Array} array - * @return {Array} array - */ - removeList(array) - { - this.lists.splice(this.lists.indexOf(array), 1) - return array - } - - /** - * add an object to be culled - * @param {*} object - * @param {boolean} [staticObject] set to true if the object's position/size does not change - * @return {*} object - */ - add(object, staticObject) - { - if (staticObject) - { - object.staticObject = true - } - if (this.calculatePIXI && (this.dirtyTest || staticObject)) - { - this.updateObject(object) +/** + * A Texture stores the information that represents an image. + * All textures have a base texture, which contains information about the source. + * Therefore you can have many textures all using a single BaseTexture + * + * @class + * @extends PIXI.utils.EventEmitter + * @memberof PIXI + * @param {PIXI.resources.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] + * The current resource to use, for things that aren't Resource objects, will be converted + * into a Resource. + * @param {Object} [options] - Collection of options + * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture + * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture + * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest + * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type + * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type + * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha + * @param {number} [options.width=0] - Width of the texture + * @param {number} [options.height=0] - Height of the texture + * @param {number} [options.resolution] - Resolution of the base texture + * @param {object} [options.resourceOptions] - Optional resource options, + * see {@link PIXI.resources.autoDetectResource autoDetectResource} + */ +var BaseTexture = /** @class */ (function (_super) { + __extends(BaseTexture, _super); + function BaseTexture(resource, options) { + if (resource === void 0) { resource = null; } + if (options === void 0) { options = null; } + var _this = _super.call(this) || this; + options = options || {}; + var alphaMode = options.alphaMode, mipmap = options.mipmap, anisotropicLevel = options.anisotropicLevel, scaleMode = options.scaleMode, width = options.width, height = options.height, wrapMode = options.wrapMode, format = options.format, type = options.type, target = options.target, resolution = options.resolution, resourceOptions = options.resourceOptions; + // Convert the resource to a Resource object + if (resource && !(resource instanceof Resource)) { + resource = autoDetectResource(resource, resourceOptions); + resource.internal = true; } - this.lists[0].push(object) - return object - } - - /** - * remove an object added by add() - * @param {*} object - * @return {*} object - */ - remove(object) - { - this.lists[0].splice(this.lists[0].indexOf(object), 1) - return object - } - - /** - * cull the items in the list by setting visible parameter - * @param {object} bounds - * @param {number} bounds.x - * @param {number} bounds.y - * @param {number} bounds.width - * @param {number} bounds.height - * @param {boolean} [skipUpdate] skip updating the AABB bounding box of all objects - */ - cull(bounds, skipUpdate) - { - if (this.calculatePIXI && !skipUpdate) - { - this.updateObjects() - } - for (let list of this.lists) - { - for (let object of list) - { - const box = object[this.AABB] - object[this.visible] = - box.x + box.width > bounds.x && box.x < bounds.x + bounds.width && - box.y + box.height > bounds.y && box.y < bounds.y + bounds.height - } + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = width || 0; + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = height || 0; + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default PIXI.settings.RESOLUTION + */ + _this.resolution = resolution || settings.settings.RESOLUTION; + /** + * Mipmap mode of the texture, affects downscaled images + * + * @member {PIXI.MIPMAP_MODES} + * @default PIXI.settings.MIPMAP_TEXTURES + */ + _this.mipmap = mipmap !== undefined ? mipmap : settings.settings.MIPMAP_TEXTURES; + /** + * Anisotropic filtering level of texture + * + * @member {number} + * @default PIXI.settings.ANISOTROPIC_LEVEL + */ + _this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings.settings.ANISOTROPIC_LEVEL; + /** + * How the texture wraps + * @member {number} + */ + _this.wrapMode = wrapMode || settings.settings.WRAP_MODE; + /** + * The scale mode to apply when scaling this texture + * + * @member {PIXI.SCALE_MODES} + * @default PIXI.settings.SCALE_MODE + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : settings.settings.SCALE_MODE; + /** + * The pixel format of the texture + * + * @member {PIXI.FORMATS} + * @default PIXI.FORMATS.RGBA + */ + _this.format = format || constants.FORMATS.RGBA; + /** + * The type of resource data + * + * @member {PIXI.TYPES} + * @default PIXI.TYPES.UNSIGNED_BYTE + */ + _this.type = type || constants.TYPES.UNSIGNED_BYTE; + /** + * The target type + * + * @member {PIXI.TARGETS} + * @default PIXI.TARGETS.TEXTURE_2D + */ + _this.target = target || constants.TARGETS.TEXTURE_2D; + /** + * How to treat premultiplied alpha, see {@link PIXI.ALPHA_MODES}. + * + * @member {PIXI.ALPHA_MODES} + * @default PIXI.ALPHA_MODES.UNPACK + */ + _this.alphaMode = alphaMode !== undefined ? alphaMode : constants.ALPHA_MODES.UNPACK; + if (options.premultiplyAlpha !== undefined) { + // triggers deprecation + _this.premultiplyAlpha = options.premultiplyAlpha; } + /** + * Global unique identifier for this BaseTexture + * + * @member {number} + * @protected + */ + _this.uid = utils.uid(); + /** + * Used by automatic texture Garbage Collection, stores last GC tick when it was bound + * + * @member {number} + * @protected + */ + _this.touched = 0; + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @readonly + * @member {boolean} + * @default false + */ + _this.isPowerOfTwo = false; + _this._refreshPOT(); + /** + * The map of render context textures where this is bound + * + * @member {Object} + * @private + */ + _this._glTextures = {}; + /** + * Used by TextureSystem to only update texture to the GPU when needed. + * Please call `update()` to increment it. + * + * @readonly + * @member {number} + */ + _this.dirtyId = 0; + /** + * Used by TextureSystem to only update texture style when needed. + * + * @protected + * @member {number} + */ + _this.dirtyStyleId = 0; + /** + * Currently default cache ID. + * + * @member {string} + */ + _this.cacheId = null; + /** + * Generally speaking means when resource is loaded. + * @readonly + * @member {boolean} + */ + _this.valid = width > 0 && height > 0; + /** + * The collection of alternative cache ids, since some BaseTextures + * can have more than one ID, short name and longer full URL + * + * @member {Array} + * @readonly + */ + _this.textureCacheIds = []; + /** + * Flag if BaseTexture has been destroyed. + * + * @member {boolean} + * @readonly + */ + _this.destroyed = false; + /** + * The resource used by this BaseTexture, there can only + * be one resource per BaseTexture, but textures can share + * resources. + * + * @member {PIXI.resources.Resource} + * @readonly + */ + _this.resource = null; + /** + * Number of the texture batch, used by multi-texture renderers + * + * @member {number} + */ + _this._batchEnabled = 0; + /** + * Location inside texture batch, used by multi-texture renderers + * + * @member {number} + */ + _this._batchLocation = 0; + /** + * Whether its a part of another texture, handled by ArrayResource or CubeResource + * + * @member {PIXI.BaseTexture} + */ + _this.parentTextureArray = null; + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + * @param {ErrorEvent} event - Load error event. + */ + /** + * Fired when BaseTexture is updated. + * + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + /** + * Fired when BaseTexture is updated. + * + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + /** + * Fired when BaseTexture is destroyed. + * + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + // Set the resource + _this.setResource(resource); + return _this; } - + Object.defineProperty(BaseTexture.prototype, "realWidth", { + /** + * Pixel width of the source of this texture + * + * @readonly + * @member {number} + */ + get: function () { + return Math.ceil((this.width * this.resolution) - 1e-4); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "realHeight", { + /** + * Pixel height of the source of this texture + * + * @readonly + * @member {number} + */ + get: function () { + return Math.ceil((this.height * this.resolution) - 1e-4); + }, + enumerable: false, + configurable: true + }); /** - * update the AABB for all objects - * automatically called from update() when calculatePIXI=true and skipUpdate=false + * Changes style options of BaseTexture + * + * @param {PIXI.SCALE_MODES} [scaleMode] - Pixi scalemode + * @param {PIXI.MIPMAP_MODES} [mipmap] - enable mipmaps + * @returns {PIXI.BaseTexture} this */ - updateObjects() - { - if (this.dirtyTest) - { - for (let list of this.lists) - { - if (!list.staticObject) - { - for (let object of list) - { - if (!object.staticObject && object[this.dirty]) - { - this.updateObject(object) - object[this.dirty] = false - } - } - } - } + BaseTexture.prototype.setStyle = function (scaleMode, mipmap) { + var dirty; + if (scaleMode !== undefined && scaleMode !== this.scaleMode) { + this.scaleMode = scaleMode; + dirty = true; } - else - { - for (let list of this.lists) - { - if (!list.staticObject) - { - for (let object of list) - { - if (!object.staticObject) - { - this.updateObject(object) - } - } - } - } + if (mipmap !== undefined && mipmap !== this.mipmap) { + this.mipmap = mipmap; + dirty = true; } - } - + if (dirty) { + this.dirtyStyleId++; + } + return this; + }; /** - * update the has of an object - * automatically called from updateObjects() - * @param {*} object + * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero. + * + * @param {number} width - Visual width + * @param {number} height - Visual height + * @param {number} [resolution] - Optionally set resolution + * @returns {PIXI.BaseTexture} this */ - updateObject(object) - { - const box = object.getLocalBounds() - object[this.AABB] = object[this.AABB] || {} - object[this.AABB].x = object.x + (box.x - object.pivot.x) * object.scale.x - object[this.AABB].y = object.y + (box.y - object.pivot.y) * object.scale.y - object[this.AABB].width = box.width * object.scale.x - object[this.AABB].height = box.height * object.scale.y - } - + BaseTexture.prototype.setSize = function (width, height, resolution) { + this.resolution = resolution || this.resolution; + this.width = width; + this.height = height; + this._refreshPOT(); + this.update(); + return this; + }; /** - * returns an array of objects contained within bounding box - * @param {object} boudns bounding box to search - * @param {number} bounds.x - * @param {number} bounds.y - * @param {number} bounds.width - * @param {number} bounds.height - * @return {object[]} search results + * Sets real size of baseTexture, preserves current resolution. + * + * @param {number} realWidth - Full rendered width + * @param {number} realHeight - Full rendered height + * @param {number} [resolution] - Optionally set resolution + * @returns {PIXI.BaseTexture} this */ - query(bounds) - { - let results = [] - for (let list of this.lists) - { - for (let object of list) - { - const box = object[this.AABB] - if (box.x + box.width > bounds.x && box.x - box.width < bounds.x + bounds.width && - box.y + box.height > bounds.y && box.y - box.height < bounds.y + bounds.height) - { - results.push(object) - } - } - } - return results - } - + BaseTexture.prototype.setRealSize = function (realWidth, realHeight, resolution) { + this.resolution = resolution || this.resolution; + this.width = realWidth / this.resolution; + this.height = realHeight / this.resolution; + this._refreshPOT(); + this.update(); + return this; + }; /** - * iterates through objects contained within bounding box - * stops iterating if the callback returns true - * @param {object} bounds bounding box to search - * @param {number} bounds.x - * @param {number} bounds.y - * @param {number} bounds.width - * @param {number} bounds.height - * @param {function} callback - * @return {boolean} true if callback returned early + * Refresh check for isPowerOfTwo texture based on size + * + * @private */ - queryCallback(bounds, callback) - { - for (let list of this.lists) - { - for (let object of list) - { - const box = object[this.AABB] - if (box.x + box.width > bounds.x && box.x - box.width < bounds.x + bounds.width && - box.y + box.height > bounds.y && box.y - box.height < bounds.y + bounds.height) - { - if (callback(object)) - { - return true - } - } - } - } - return false - } - + BaseTexture.prototype._refreshPOT = function () { + this.isPowerOfTwo = utils.isPow2(this.realWidth) && utils.isPow2(this.realHeight); + }; /** - * get stats (only updated after update() is called) - * @return {SimpleStats} + * Changes resolution + * + * @param {number} resolution - res + * @returns {PIXI.BaseTexture} this */ - stats() - { - let visible = 0, count = 0 - for (let list of this.lists) - { - list.forEach(object => - { - visible += object.visible ? 1 : 0 - count++ - }) + BaseTexture.prototype.setResolution = function (resolution) { + var oldResolution = this.resolution; + if (oldResolution === resolution) { + return this; } - return { total: count, visible, culled: count - visible } - } -} - -/** - * @typedef {object} SimpleStats - * @property {number} total - * @property {number} visible - * @property {number} culled - */ - -module.exports = Simple -},{}],12:[function(require,module,exports){ -// Copyright 2018 YOPEY YOPEY LLC -// David Figatner -// MIT License - -class SpatialHash -{ + this.resolution = resolution; + if (this.valid) { + this.width = this.width * oldResolution / resolution; + this.height = this.height * oldResolution / resolution; + this.emit('update', this); + } + this._refreshPOT(); + return this; + }; /** - * creates a spatial-hash cull - * @param {object} [options] - * @param {number} [options.size=1000] cell size used to create hash (xSize = ySize) - * @param {number} [options.xSize] horizontal cell size - * @param {number} [options.ySize] vertical cell size - * @param {boolean} [options.calculatePIXI=true] calculate bounding box automatically; if this is set to false then it uses object[options.AABB] for bounding box - * @param {boolean} [options.visible=visible] parameter of the object to set (usually visible or renderable) - * @param {boolean} [options.simpleTest=true] iterate through visible buckets to check for bounds - * @param {string} [options.dirtyTest=true] only update spatial hash for objects with object[options.dirtyTest]=true; this has a HUGE impact on performance - * @param {string} [options.AABB=AABB] object property that holds bounding box so that object[type] = { x: number, y: number, width: number, height: number } - * @param {string} [options.spatial=spatial] object property that holds object's hash list - * @param {string} [options.dirty=dirty] object property for dirtyTest + * Sets the resource if it wasn't set. Throws error if resource already present + * + * @param {PIXI.resources.Resource} resource - that is managing this BaseTexture + * @returns {PIXI.BaseTexture} this */ - constructor(options) - { - options = options || {} - this.xSize = options.xSize || options.size || 1000 - this.ySize = options.ySize || options.size || 1000 - this.AABB = options.type || 'AABB' - this.spatial = options.spatial || 'spatial' - this.calculatePIXI = typeof options.calculatePIXI !== 'undefined' ? options.calculatePIXI : true - this.visibleText = typeof options.visibleTest !== 'undefined' ? options.visibleTest : true - this.simpleTest = typeof options.simpleTest !== 'undefined' ? options.simpleTest : true - this.dirtyTest = typeof options.dirtyTest !== 'undefined' ? options.dirtyTest : true - this.visible = options.visible || 'visible' - this.dirty = options.dirty || 'dirty' - this.width = this.height = 0 - this.hash = {} - this.objects = [] - this.containers = [] - } - + BaseTexture.prototype.setResource = function (resource) { + if (this.resource === resource) { + return this; + } + if (this.resource) { + throw new Error('Resource can be set only once'); + } + resource.bind(this); + this.resource = resource; + return this; + }; /** - * add an object to be culled - * side effect: adds object.spatialHashes to track existing hashes - * @param {*} object - * @param {boolean} [staticObject] set to true if the object's position/size does not change - * @return {*} object + * Invalidates the object. Texture becomes valid if width and height are greater than zero. */ - add(object, staticObject) - { - object[this.spatial] = { hashes: [] } - if (this.calculatePIXI && this.dirtyTest) - { - object[this.dirty] = true + BaseTexture.prototype.update = function () { + if (!this.valid) { + if (this.width > 0 && this.height > 0) { + this.valid = true; + this.emit('loaded', this); + this.emit('update', this); + } } - if (staticObject) - { - object.staticObject = true + else { + this.dirtyId++; + this.dirtyStyleId++; + this.emit('update', this); } - this.updateObject(object) - this.containers[0].push(object) - } - + }; /** - * remove an object added by add() - * @param {*} object - * @return {*} object + * Handle errors with resources. + * @private + * @param {ErrorEvent} event - Error event emitted. */ - remove(object) - { - this.containers[0].splice(this.list[0].indexOf(object), 1) - this.removeFromHash(object) - return object - } - + BaseTexture.prototype.onError = function (event) { + this.emit('error', this, event); + }; /** - * add an array of objects to be culled - * @param {PIXI.Container} container - * @param {boolean} [staticObject] set to true if the objects in the container's position/size do not change - * note: this only works with pixi v5.0.0rc2+ because it relies on the new container events childAdded and childRemoved + * Destroys this base texture. + * The method stops if resource doesn't want this texture to be destroyed. + * Removes texture from all caches. */ - addContainer(container, staticObject) - { - const added = function(object) - { - object[this.spatial] = { hashes: [] } - this.updateObject(object) - }.bind(this) - - const removed = function (object) - { - this.removeFromHash(object) - }.bind(this) - - for (let object of container.children) - { - object[this.spatial] = { hashes: [] } - this.updateObject(object) + BaseTexture.prototype.destroy = function () { + // remove and destroy the resource + if (this.resource) { + this.resource.unbind(this); + // only destroy resourced created internally + if (this.resource.internal) { + this.resource.destroy(); + } + this.resource = null; } - container.cull = {} - this.containers.push(container) - container.on('childAdded', added) - container.on('childRemoved', removed) - container.cull.added = added - container.cull.removed = removed - if (staticObject) - { - container.cull.static = true + if (this.cacheId) { + delete utils.BaseTextureCache[this.cacheId]; + delete utils.TextureCache[this.cacheId]; + this.cacheId = null; } - } - + // finally let the WebGL renderer know.. + this.dispose(); + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + this.destroyed = true; + }; /** - * remove an array added by addContainer() - * @param {PIXI.Container} container - * @return {PIXI.Container} container + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + * @fires PIXI.BaseTexture#dispose */ - removeContainer(container) - { - this.containers.splice(this.containers.indexOf(container), 1) - container.children.forEach(object => this.removeFromHash(object)) - container.off('added', container.cull.added) - container.off('removed', container.cull.removed) - delete container.cull - return container - } - + BaseTexture.prototype.dispose = function () { + this.emit('dispose', this); + }; /** - * update the hashes and cull the items in the list - * @param {AABB} AABB - * @param {boolean} [skipUpdate] skip updating the hashes of all objects - * @return {number} number of buckets in results + * Utility function for BaseTexture|Texture cast */ - cull(AABB, skipUpdate) - { - if (!skipUpdate) - { - this.updateObjects() - } - this.invisible() - const objects = this.query(AABB, this.simpleTest) - objects.forEach(object => object[this.visible] = true) - return this.lastBuckets - } - + BaseTexture.prototype.castToBaseTexture = function () { + return this; + }; /** - * set all objects in hash to visible=false - */ - invisible() - { - for (let container of this.containers) - { - container.children.forEach(object => object[this.visible] = false) - } - } - - /** - * update the hashes for all objects - * automatically called from update() when skipUpdate=false + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. If the + * source is an image url or an image element and not in the base texture + * cache, it will be created and loaded. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The + * source to create base texture from. + * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. + * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. + * @returns {PIXI.BaseTexture} The new base texture. */ - updateObjects() - { - if (this.dirtyTest) - { - for (let object of this.objects) - { - if (object[this.dirty]) - { - this.updateObject(object) - object[this.dirty] = false - } - } - for (let container of this.containers) - { - for (let object of container.children) - { - if (object[this.dirty]) - { - this.updateObject(object) - object[this.dirty] = false - } - } - } + BaseTexture.from = function (source, options, strict) { + if (strict === void 0) { strict = settings.settings.STRICT_TEXTURE_CACHE; } + var isFrame = typeof source === 'string'; + var cacheId = null; + if (isFrame) { + cacheId = source; } - else - { - for (let container of this.containers) - { - if (!container.cull.static) - { - container.children.forEach(object => this.updateObject(object)) - } + else { + if (!source._pixiId) { + source._pixiId = "pixiid_" + utils.uid(); } + cacheId = source._pixiId; } - } - + var baseTexture = utils.BaseTextureCache[cacheId]; + // Strict-mode rejects invalid cacheIds + if (isFrame && strict && !baseTexture) { + throw new Error("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache."); + } + if (!baseTexture) { + baseTexture = new BaseTexture(source, options); + baseTexture.cacheId = cacheId; + BaseTexture.addToCache(baseTexture, cacheId); + } + return baseTexture; + }; /** - * update the has of an object - * automatically called from updateObjects() - * @param {*} object - * @param {boolean} [force] force update for calculatePIXI + * Create a new BaseTexture with a BufferResource from a Float32Array. + * RGBA values are floats from 0 to 1. + * @static + * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data + * is provided, a new Float32Array is created. + * @param {number} width - Width of the resource + * @param {number} height - Height of the resource + * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. + * @return {PIXI.BaseTexture} The resulting new BaseTexture */ - updateObject(object) - { - let AABB - if (this.calculatePIXI) - { - const box = object.getLocalBounds() - AABB = object[this.AABB] = { - x: object.x + (box.x - object.pivot.x) * object.scale.x, - y: object.y + (box.y - object.pivot.y) * object.scale.y, - width: box.width * object.scale.x, - height: box.height * object.scale.y + BaseTexture.fromBuffer = function (buffer, width, height, options) { + buffer = buffer || new Float32Array(width * height * 4); + var resource = new BufferResource(buffer, { width: width, height: height }); + var type = buffer instanceof Float32Array ? constants.TYPES.FLOAT : constants.TYPES.UNSIGNED_BYTE; + return new BaseTexture(resource, Object.assign(defaultBufferOptions, options || { width: width, height: height, type: type })); + }; + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + BaseTexture.addToCache = function (baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + if (utils.BaseTextureCache[id]) { + // eslint-disable-next-line no-console + console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry"); } + utils.BaseTextureCache[id] = baseTexture; } - else - { - AABB = object[this.AABB] + }; + /** + * Remove a BaseTexture from the global BaseTextureCache. + * + * @static + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + BaseTexture.removeFromCache = function (baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = utils.BaseTextureCache[baseTexture]; + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + delete utils.BaseTextureCache[baseTexture]; + return baseTextureFromCache; + } } - - let spatial = object[this.spatial] - if (!spatial) - { - spatial = object[this.spatial] = { hashes: [] } + else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + baseTexture.textureCacheIds.length = 0; + return baseTexture; } - const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB) + return null; + }; + /** + * Global number of the texture batch, used by multi-texture renderers + * + * @static + * @member {number} + */ + BaseTexture._globalBatch = 0; + return BaseTexture; +}(utils.EventEmitter)); - // only remove and insert if mapping has changed - if (spatial.xStart !== xStart || spatial.yStart !== yStart || spatial.xEnd !== xEnd || spatial.yEnd !== yEnd) - { - if (spatial.hashes.length) - { - this.removeFromHash(object) - } - for (let y = yStart; y <= yEnd; y++) - { - for (let x = xStart; x <= xEnd; x++) - { - const key = x + ',' + y - this.insert(object, key) - spatial.hashes.push(key) - } - } - spatial.xStart = xStart - spatial.yStart = yStart - spatial.xEnd = xEnd - spatial.yEnd = yEnd +/** + * Resource that can manage several resource (items) inside. + * All resources need to have the same pixel size. + * Parent class for CubeResource and ArrayResource + * + * @class + * @extends PIXI.resources.Resource + * @memberof PIXI.resources + * @param {object} [options] Options to for Resource constructor + * @param {number} [options.width] - Width of the resource + * @param {number} [options.height] - Height of the resource + */ +var AbstractMultiResource = /** @class */ (function (_super) { + __extends(AbstractMultiResource, _super); + function AbstractMultiResource(length, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + _this = _super.call(this, width, height) || this; + /** + * Collection of partial baseTextures that correspond to resources + * @member {Array} + * @readonly + */ + _this.items = []; + /** + * Dirty IDs for each part + * @member {Array} + * @readonly + */ + _this.itemDirtyIds = []; + for (var i = 0; i < length; i++) { + var partTexture = new BaseTexture(); + _this.items.push(partTexture); + // -2 - first run of texture array upload + // -1 - texture item was allocated + // >=0 - texture item uploaded , in sync with items[i].dirtyId + _this.itemDirtyIds.push(-2); } + /** + * Number of elements in array + * + * @member {number} + * @readonly + */ + _this.length = length; + /** + * Promise when loading + * @member {Promise} + * @private + * @default null + */ + _this._load = null; + /** + * Bound baseTexture, there can only be one + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = null; + return _this; } - /** - * returns an array of buckets with >= minimum of objects in each bucket - * @param {number} [minimum=1] - * @return {array} array of buckets + * used from ArrayResource and CubeResource constructors + * @param {Array<*>} resources - Can be resources, image elements, canvas, etc. , + * length should be same as constructor length + * @param {object} [options] - detect options for resources + * @protected */ - getBuckets(minimum=1) - { - const hashes = [] - for (let key in this.hash) - { - const hash = this.hash[key] - if (hash.length >= minimum) - { - hashes.push(hash) + AbstractMultiResource.prototype.initFromArray = function (resources, options) { + for (var i = 0; i < this.length; i++) { + if (!resources[i]) { + continue; + } + if (resources[i].castToBaseTexture) { + this.addBaseTextureAt(resources[i].castToBaseTexture(), i); + } + else if (resources[i] instanceof Resource) { + this.addResourceAt(resources[i], i); + } + else { + this.addResourceAt(autoDetectResource(resources[i], options), i); } } - return hashes - } - + }; /** - * gets hash bounds - * @param {AABB} AABB - * @return {Bounds} - * @private + * Destroy this BaseImageResource + * @override */ - getBounds(AABB) - { - let xStart = Math.floor(AABB.x / this.xSize) - let yStart = Math.floor(AABB.y / this.ySize) - let xEnd = Math.floor((AABB.x + AABB.width) / this.xSize) - let yEnd = Math.floor((AABB.y + AABB.height) / this.ySize) - return { xStart, yStart, xEnd, yEnd } - } - + AbstractMultiResource.prototype.dispose = function () { + for (var i = 0, len = this.length; i < len; i++) { + this.items[i].destroy(); + } + this.items = null; + this.itemDirtyIds = null; + this._load = null; + }; /** - * insert object into the spatial hash - * automatically called from updateObject() - * @param {*} object - * @param {string} key + * Set a resource by ID + * + * @param {PIXI.resources.Resource} resource + * @param {number} index - Zero-based index of resource to set + * @return {PIXI.resources.ArrayResource} Instance for chaining */ - insert(object, key) - { - if (!this.hash[key]) - { - this.hash[key] = [object] + AbstractMultiResource.prototype.addResourceAt = function (resource, index) { + if (!this.items[index]) { + throw new Error("Index " + index + " is out of bounds"); } - else - { - this.hash[key].push(object) + // Inherit the first resource dimensions + if (resource.valid && !this.valid) { + this.resize(resource.width, resource.height); } - } - + this.items[index].setResource(resource); + return this; + }; /** - * removes object from the hash table - * should be called when removing an object - * automatically called from updateObject() - * @param {object} object + * Set the parent base texture + * @member {PIXI.BaseTexture} + * @override */ - removeFromHash(object) - { - const spatial = object[this.spatial] - while (spatial.hashes.length) - { - const key = spatial.hashes.pop() - const list = this.hash[key] - list.splice(list.indexOf(object), 1) + AbstractMultiResource.prototype.bind = function (baseTexture) { + if (this.baseTexture !== null) { + throw new Error('Only one base texture per TextureArray is allowed'); } - } - + _super.prototype.bind.call(this, baseTexture); + for (var i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = baseTexture; + this.items[i].on('update', baseTexture.update, baseTexture); + } + }; /** - * get all neighbors that share the same hash as object - * @param {*} object in the spatial hash - * @return {Array} of objects that are in the same hash as object + * Unset the parent base texture + * @member {PIXI.BaseTexture} + * @override */ - neighbors(object) - { - let results = [] - object[this.spatial].hashes.forEach(key => results = results.concat(this.hash[key])) - return results - } - + AbstractMultiResource.prototype.unbind = function (baseTexture) { + _super.prototype.unbind.call(this, baseTexture); + for (var i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = null; + this.items[i].off('update', baseTexture.update, baseTexture); + } + }; /** - * returns an array of objects contained within bounding box - * @param {AABB} AABB bounding box to search - * @param {boolean} [simpleTest=true] perform a simple bounds check of all items in the buckets - * @return {object[]} search results + * Load all the resources simultaneously + * @override + * @return {Promise} When load is resolved */ - query(AABB, simpleTest) - { - simpleTest = typeof simpleTest !== 'undefined' ? simpleTest : true - let buckets = 0 - let results = [] - const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB) - for (let y = yStart; y <= yEnd; y++) - { - for (let x = xStart; x <= xEnd; x++) - { - const entry = this.hash[x + ',' + y] - if (entry) - { - if (simpleTest) - { - for (let object of entry) - { - const box = object[this.AABB] - if (box.x + box.width > AABB.x && box.x < AABB.x + AABB.width && - box.y + box.height > AABB.y && box.y < AABB.y + AABB.height) - { - results.push(object) - } - } - } - else - { - results = results.concat(entry) - } - buckets++ - } - } + AbstractMultiResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; } - this.lastBuckets = buckets - return results - } + var resources = this.items.map(function (item) { return item.resource; }).filter(function (item) { return item; }); + // TODO: also implement load part-by-part strategy + var promises = resources.map(function (item) { return item.load(); }); + this._load = Promise.all(promises) + .then(function () { + var _a = _this.items[0], realWidth = _a.realWidth, realHeight = _a.realHeight; + _this.resize(realWidth, realHeight); + return Promise.resolve(_this); + }); + return this._load; + }; + return AbstractMultiResource; +}(Resource)); - /** - * iterates through objects contained within bounding box - * stops iterating if the callback returns true - * @param {AABB} AABB bounding box to search - * @param {function} callback - * @param {boolean} [simpleTest=true] perform a simple bounds check of all items in the buckets - * @return {boolean} true if callback returned early - */ - queryCallback(AABB, callback, simpleTest) - { - simpleTest = typeof simpleTest !== 'undefined' ? simpleTest : true - const { xStart, yStart, xEnd, yEnd } = this.getBounds(AABB) - for (let y = yStart; y <= yEnd; y++) - { - for (let x = xStart; x <= xEnd; x++) - { - const entry = this.hash[x + ',' + y] - if (entry) - { - for (let i = 0; i < entry.length; i++) - { - const object = entry[i] - if (simpleTest) - { - const AABB = object.AABB - if (AABB.x + AABB.width > AABB.x && AABB.x < AABB.x + AABB.width && - AABB.y + AABB.height > AABB.y && AABB.y < AABB.y + AABB.height) - { - if (callback(object)) - { - return true - } - } - } - else - { - if (callback(object)) - { - return true - } - } - } - } - } +/** + * A resource that contains a number of sources. + * + * @class + * @extends PIXI.resources.Resource + * @memberof PIXI.resources + * @param {number|Array<*>} source - Number of items in array or the collection + * of image URLs to use. Can also be resources, image elements, canvas, etc. + * @param {object} [options] - Options to apply to {@link PIXI.resources.autoDetectResource} + * @param {number} [options.width] - Width of the resource + * @param {number} [options.height] - Height of the resource + */ +var ArrayResource = /** @class */ (function (_super) { + __extends(ArrayResource, _super); + function ArrayResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + var urls; + var length; + if (Array.isArray(source)) { + urls = source; + length = source.length; } - return false + else { + length = source; + } + _this = _super.call(this, length, { width: width, height: height }) || this; + if (urls) { + _this.initFromArray(urls, options); + } + return _this; } - /** - * get stats - * @return {Stats} + * Set a baseTexture by ID, + * ArrayResource just takes resource from it, nothing more + * + * @param {PIXI.BaseTexture} baseTexture + * @param {number} index - Zero-based index of resource to set + * @return {PIXI.resources.ArrayResource} Instance for chaining */ - stats() - { - let visible = 0, count = 0 - for (let list of this.containers) - { - for (let i = 0; i < list.children.length; i++) - { - const object = list.children[i] - visible += object.visible ? 1 : 0 - count++ - } + ArrayResource.prototype.addBaseTextureAt = function (baseTexture, index) { + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); } - return { - total: count, - visible, - culled: count - visible + else { + throw new Error('ArrayResource does not support RenderTexture'); } - } - - /** - * helper function to evaluate hash table - * @return {number} the number of buckets in the hash table - * */ - getNumberOfBuckets() - { - return Object.keys(this.hash).length - } - + return this; + }; /** - * helper function to evaluate hash table - * @return {number} the average number of entries in each bucket + * Add binding + * @member {PIXI.BaseTexture} + * @override */ - getAverageSize() - { - let total = 0 - for (let key in this.hash) - { - total += this.hash[key].length - } - return total / this.getBuckets().length - } - + ArrayResource.prototype.bind = function (baseTexture) { + _super.prototype.bind.call(this, baseTexture); + baseTexture.target = constants.TARGETS.TEXTURE_2D_ARRAY; + }; /** - * helper function to evaluate the hash table - * @return {number} the largest sized bucket + * Upload the resources to the GPU. + * @param {PIXI.Renderer} renderer + * @param {PIXI.BaseTexture} texture + * @param {PIXI.GLTexture} glTexture + * @returns {boolean} whether texture was uploaded */ - getLargest() - { - let largest = 0 - for (let key in this.hash) - { - if (this.hash[key].length > largest) - { - largest = this.hash[key].length + ArrayResource.prototype.upload = function (renderer, texture, glTexture) { + var _a = this, length = _a.length, itemDirtyIds = _a.itemDirtyIds, items = _a.items; + var gl = renderer.gl; + if (glTexture.dirtyId < 0) { + gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, texture.format, this._width, this._height, length, 0, texture.format, texture.type, null); + } + for (var i = 0; i < length; i++) { + var item = items[i]; + if (itemDirtyIds[i] < item.dirtyId) { + itemDirtyIds[i] = item.dirtyId; + if (item.valid) { + gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, // xoffset + 0, // yoffset + i, // zoffset + item.resource.width, item.resource.height, 1, texture.format, texture.type, item.resource.source); + } } } - return largest - } + return true; + }; + return ArrayResource; +}(AbstractMultiResource)); +/** + * Base for all the image/canvas resources + * @class + * @extends PIXI.resources.Resource + * @memberof PIXI.resources + */ +var BaseImageResource = /** @class */ (function (_super) { + __extends(BaseImageResource, _super); /** - * gets quadrant bounds - * @return {Bounds} + * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source */ - getWorldBounds() - { - let xStart = Infinity, yStart = Infinity, xEnd = 0, yEnd = 0 - for (let key in this.hash) - { - const split = key.split(',') - let x = parseInt(split[0]) - let y = parseInt(split[1]) - xStart = x < xStart ? x : xStart - yStart = y < yStart ? y : yStart - xEnd = x > xEnd ? x : xEnd - yEnd = y > yEnd ? y : yEnd - } - return { xStart, yStart, xEnd, yEnd } - } - + function BaseImageResource(source) { + var _this = this; + var sourceAny = source; + var width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width; + var height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height; + _this = _super.call(this, width, height) || this; + /** + * The source element + * @member {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} + * @readonly + */ + _this.source = source; + /** + * If set to `true`, will force `texImage2D` over `texSubImage2D` for uploading. + * Certain types of media (e.g. video) using `texImage2D` is more performant. + * @member {boolean} + * @default false + * @private + */ + _this.noSubImage = false; + return _this; + } /** - * helper function to evalute the hash table - * @param {AABB} [AABB] bounding box to search or entire world - * @return {number} sparseness percentage (i.e., buckets with at least 1 element divided by total possible buckets) + * Set cross origin based detecting the url and the crossorigin + * @protected + * @param {HTMLElement} element - Element to apply crossOrigin + * @param {string} url - URL to check + * @param {boolean|string} [crossorigin=true] - Cross origin value to use */ - getSparseness(AABB) - { - let count = 0, total = 0 - const { xStart, yStart, xEnd, yEnd } = AABB ? this.getBounds(AABB) : this.getWorldBounds() - for (let y = yStart; y < yEnd; y++) - { - for (let x = xStart; x < xEnd; x++) - { - count += (this.hash[x + ',' + y] ? 1 : 0) - total++ - } + BaseImageResource.crossOrigin = function (element, url, crossorigin) { + if (crossorigin === undefined && url.indexOf('data:') !== 0) { + element.crossOrigin = utils.determineCrossOrigin(url); } - return count / total - } -} + else if (crossorigin !== false) { + element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + }; + /** + * Upload the texture to the GPU. + * @param {PIXI.Renderer} renderer - Upload to the renderer + * @param {PIXI.BaseTexture} baseTexture - Reference to parent texture + * @param {PIXI.GLTexture} glTexture + * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] (optional) + * @returns {boolean} true is success + */ + BaseImageResource.prototype.upload = function (renderer, baseTexture, glTexture, source) { + var gl = renderer.gl; + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + source = source || this.source; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants.ALPHA_MODES.UNPACK); + if (!this.noSubImage + && baseTexture.target === gl.TEXTURE_2D + && glTexture.width === width + && glTexture.height === height) { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, baseTexture.type, source); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, baseTexture.format, baseTexture.format, baseTexture.type, source); + } + return true; + }; + /** + * Checks if source width/height was changed, resize can cause extra baseTexture update. + * Triggers one update in any case. + */ + BaseImageResource.prototype.update = function () { + if (this.destroyed) { + return; + } + var source = this.source; + var width = source.naturalWidth || source.videoWidth || source.width; + var height = source.naturalHeight || source.videoHeight || source.height; + this.resize(width, height); + _super.prototype.update.call(this); + }; + /** + * Destroy this BaseImageResource + * @override + */ + BaseImageResource.prototype.dispose = function () { + this.source = null; + }; + return BaseImageResource; +}(Resource)); /** - * @typedef {object} Stats - * @property {number} total - * @property {number} visible - * @property {number} culled + * @interface OffscreenCanvas */ - /** - * @typedef {object} Bounds - * @property {number} xStart - * @property {number} yStart - * @property {number} xEnd - * @property {number} xEnd + * Resource type for HTMLCanvasElement. + * @class + * @extends PIXI.resources.BaseImageResource + * @memberof PIXI.resources + * @param {HTMLCanvasElement} source - Canvas element to use */ - -/** - * @typedef {object} AABB - * @property {number} x - * @property {number} y - * @property {number} width - * @property {number} height - */ - -module.exports = SpatialHash -},{}],13:[function(require,module,exports){ -const PIXI = window.PIXI = require('pixi.js') -const Viewport = require('pixi-viewport').Viewport -const Random = require('yy-random') -const forkMe = require('fork-me-github') -const FPS = require('yy-fps') - -const Cull = require('../code') - -let _application, _viewport, _dots, _div, _simple, _hash, _mode = 'simple', _stats, _fps //, _test - -const START_X = -25000 -const START_Y = -25000 -const WIDTH = 50000 -const HEIGHT = 50000 -const DOTS = 10000 -const DOTS_SIZE = 100 - -function ui() -{ - _fps = new FPS({ side: 'bottomleft' }) - _div = { - choices: document.getElementById('choices'), - visible: document.getElementById('visible'), - cull: document.getElementById('culled'), - total: document.getElementById('total'), - buckets: document.getElementById('buckets'), - hash: document.getElementById('hash'), - visibleBuckets: document.getElementById('visible-buckets'), - culledBuckets: document.getElementById('culled-buckets'), - totalBuckets: document.getElementById('total-buckets'), - simpleTest: document.getElementById('simple-test'), - dirtyTest: document.getElementById('dirty-test'), - sparseness: document.getElementById('sparseness-buckets'), - largest: document.getElementById('largest-bucket'), - average: document.getElementById('average-bucket') +var CanvasResource = /** @class */ (function (_super) { + __extends(CanvasResource, _super); + function CanvasResource() { + return _super !== null && _super.apply(this, arguments) || this; } - - _div.buckets.style.display = _mode === 'hash' ? 'block' : 'none' - - _div.choices.addEventListener('change', () => - { - _mode = _div.choices.querySelector('input[name=cull-types]:checked').value - if (_mode === 'none') - { - for (let dot of _dots.children) - { - dot.visible = true - } - } - updateCull() - _div.buckets.style.display = _mode === 'hash' ? 'block' : 'none' - if (_mode === 'hash') - { - _div.sparseness.innerHTML = Math.round(_hash.getSparseness() * 100) + '%' - _div.largest.innerHTML = _hash.getLargest() - _div.average.innerHTML = Math.round(_hash.getAverageSize() * 100) / 100 - _div.hash.style.display = 'block' - } - else - { - _div.hash.style.display = 'none' + /** + * Used to auto-detect the type of resource. + * + * @static + * @param {HTMLCanvasElement|OffscreenCanvas} source - The source object + * @return {boolean} `true` if source is HTMLCanvasElement or OffscreenCanvas + */ + CanvasResource.test = function (source) { + var OffscreenCanvas = window.OffscreenCanvas; + // Check for browsers that don't yet support OffscreenCanvas + if (OffscreenCanvas && source instanceof OffscreenCanvas) { + return true; } - }) - - _div.simpleTest.addEventListener('change', () => - { - _hash.simpleTest = _div.simpleTest.checked - updateCull() - }) - - _div.dirtyTest.addEventListener('change', () => - { - _hash.dirtyTest = _simple.dirtyTest = _div.dirtyTest.checked - }) - - document.querySelector('.instructions').style.opacity = 0; - forkMe(null, { side: 'left' }) -} - -function pixi() -{ - const view = document.querySelector('.pixi') - _application = new PIXI.Application({ width: view.offsetWidth, height: view.offsetHeight, view, transparent: true }) - _viewport = _application.stage.addChild(new Viewport()) - _viewport.drag().pinch().decelerate().wheel() - _viewport.resize(view.offsetWidth, view.offsetHeight, WIDTH, HEIGHT) - _viewport.fitWidth(5000) - const ticker = PIXI.ticker || PIXI.Ticker - ticker.shared.add(update) - // _test = _viewport.addChild(new PIXI.Graphics()) - - window.addEventListener('resize', () => { - // weird hack needed for flexbox to work correctly; probably a better way to do this - _application.renderer.resize(0, 0) - - _viewport.resize(view.offsetWidth, view.offsetHeight) - _application.renderer.resize(view.offsetWidth, view.offsetHeight) - _viewport.dirty = true - }) -} - -function dots() -{ - _dots = _viewport.addChild(new PIXI.Container()) - for (let i = 0; i < DOTS; i++) - { - const dot = _dots.addChild(new PIXI.Sprite(PIXI.Texture.WHITE)) - dot.tint = Random.color() - dot.width = dot.height = DOTS_SIZE - dot.position.set(Random.range(START_X, WIDTH), Random.range(START_Y, HEIGHT)) - } - - _simple = new Cull.Simple() - _simple.addList(_dots.children, true) - _hash = new Cull.SpatialHash() - _hash.addContainer(_dots, true) -} - -function update() -{ - if (_viewport.dirty) - { - updateCull() - _viewport.dirty = false - } - _fps.frame() -} - -function updateCull() -{ - switch (_mode) - { - case 'simple': - _simple.cull(_viewport.getVisibleBounds()) - _stats = _simple.stats() - break - - case 'hash': - const visible = _div.visibleBuckets.innerHTML = _hash.cull(_viewport.getVisibleBounds()) - const total = _div.totalBuckets.innerHTML = _hash.getBuckets().length - _div.culledBuckets.innerHTML = total - visible - _stats = _hash.stats() - break - - case 'none': - _stats = { visible: _dots.children.length, culled: 0, total: _dots.children.length } - break - } - _viewport.dirty = false - _div.visible.innerHTML = _stats.visible - _div.cull.innerHTML = _stats.culled - _div.total.innerHTML = _stats.total -} - -window.onload = () => -{ - pixi() - dots() - ui() - updateCull() -} -},{"../code":10,"fork-me-github":51,"pixi-viewport":56,"pixi.js":57,"yy-fps":69,"yy-random":70}],14:[function(require,module,exports){ -/*! - * @pixi/accessibility - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/accessibility is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var utils = require('@pixi/utils'); -var display = require('@pixi/display'); + return source instanceof HTMLCanvasElement; + }; + return CanvasResource; +}(BaseImageResource)); /** - * Default property values of accessible objects - * used by {@link PIXI.accessibility.AccessibilityManager}. - * - * @private - * @function accessibleTarget - * @memberof PIXI.accessibility - * @type {Object} - * @example - * function MyObject() {} + * Resource for a CubeTexture which contains six resources. * - * Object.assign( - * MyObject.prototype, - * PIXI.accessibility.accessibleTarget - * ); + * @class + * @extends PIXI.resources.ArrayResource + * @memberof PIXI.resources + * @param {Array} [source] - Collection of URLs or resources + * to use as the sides of the cube. + * @param {object} [options] - ImageResource options + * @param {number} [options.width] - Width of resource + * @param {number} [options.height] - Height of resource + * @param {number} [options.autoLoad=true] - Whether to auto-load resources + * @param {number} [options.linkBaseTexture=true] - In case BaseTextures are supplied, + * whether to copy them or use */ -var accessibleTarget = { +var CubeResource = /** @class */ (function (_super) { + __extends(CubeResource, _super); + function CubeResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height, autoLoad = _a.autoLoad, linkBaseTexture = _a.linkBaseTexture; + if (source && source.length !== CubeResource.SIDES) { + throw new Error("Invalid length. Got " + source.length + ", expected 6"); + } + _this = _super.call(this, 6, { width: width, height: height }) || this; + for (var i = 0; i < CubeResource.SIDES; i++) { + _this.items[i].target = constants.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i; + } + /** + * In case BaseTextures are supplied, whether to use same resource or bind baseTexture itself + * @member {boolean} + * @protected + */ + _this.linkBaseTexture = linkBaseTexture !== false; + if (source) { + _this.initFromArray(source, options); + } + if (autoLoad !== false) { + _this.load(); + } + return _this; + } /** - * Flag for if the object is accessible. If true AccessibilityManager will overlay a - * shadow div with attributes set + * Add binding * - * @member {boolean} - * @memberof PIXI.DisplayObject# + * @override + * @param {PIXI.BaseTexture} baseTexture - parent base texture */ - accessible: false, - + CubeResource.prototype.bind = function (baseTexture) { + _super.prototype.bind.call(this, baseTexture); + baseTexture.target = constants.TARGETS.TEXTURE_CUBE_MAP; + }; + CubeResource.prototype.addBaseTextureAt = function (baseTexture, index, linkBaseTexture) { + if (linkBaseTexture === undefined) { + linkBaseTexture = this.linkBaseTexture; + } + if (!this.items[index]) { + throw new Error("Index " + index + " is out of bounds"); + } + if (!this.linkBaseTexture + || baseTexture.parentTextureArray + || Object.keys(baseTexture._glTextures).length > 0) { + // copy mode + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); + } + else { + throw new Error("CubeResource does not support copying of renderTexture."); + } + } + else { + // link mode, the difficult one! + baseTexture.target = constants.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index; + baseTexture.parentTextureArray = this.baseTexture; + this.items[index] = baseTexture; + } + if (baseTexture.valid && !this.valid) { + this.resize(baseTexture.realWidth, baseTexture.realHeight); + } + this.items[index] = baseTexture; + return this; + }; /** - * Sets the title attribute of the shadow div - * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * Upload the resource * - * @member {?string} - * @memberof PIXI.DisplayObject# + * @returns {boolean} true is success */ - accessibleTitle: null, - + CubeResource.prototype.upload = function (renderer, _baseTexture, glTexture) { + var dirty = this.itemDirtyIds; + for (var i = 0; i < CubeResource.SIDES; i++) { + var side = this.items[i]; + if (dirty[i] < side.dirtyId) { + if (side.valid && side.resource) { + side.resource.upload(renderer, side, glTexture); + dirty[i] = side.dirtyId; + } + else if (dirty[i] < -1) { + // either item is not valid yet, either its a renderTexture + // allocate the memory + renderer.gl.texImage2D(side.target, 0, glTexture.internalFormat, _baseTexture.realWidth, _baseTexture.realHeight, 0, _baseTexture.format, glTexture.type, null); + dirty[i] = -1; + } + } + } + return true; + }; /** - * Sets the aria-label attribute of the shadow div + * Used to auto-detect the type of resource. * - * @member {string} - * @memberof PIXI.DisplayObject# + * @static + * @param {object} source - The source object + * @return {boolean} `true` if source is an array of 6 elements */ - accessibleHint: null, - + CubeResource.test = function (source) { + return Array.isArray(source) && source.length === CubeResource.SIDES; + }; /** + * Number of texture sides to store for CubeResources + * + * @name PIXI.resources.CubeResource.SIDES + * @static * @member {number} - * @memberof PIXI.DisplayObject# - * @private - * @todo Needs docs. - */ - tabIndex: 0, - - /** - * @member {boolean} - * @memberof PIXI.DisplayObject# - * @todo Needs docs. + * @default 6 */ - _accessibleActive: false, + CubeResource.SIDES = 6; + return CubeResource; +}(AbstractMultiResource)); +/** + * Resource type for HTMLImageElement. + * @class + * @extends PIXI.resources.BaseImageResource + * @memberof PIXI.resources + */ +var ImageResource = /** @class */ (function (_super) { + __extends(ImageResource, _super); /** - * @member {boolean} - * @memberof PIXI.DisplayObject# - * @todo Needs docs. + * @param {HTMLImageElement|string} source - image source or URL + * @param {object} [options] + * @param {boolean} [options.autoLoad=true] - start loading process + * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - whether its required to create + * a bitmap before upload + * @param {boolean} [options.crossorigin=true] - Load image using cross origin + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Premultiply image alpha in bitmap */ - _accessibleDiv: false, - + function ImageResource(source, options) { + var _this = this; + options = options || {}; + if (!(source instanceof HTMLImageElement)) { + var imageElement = new Image(); + BaseImageResource.crossOrigin(imageElement, source, options.crossorigin); + imageElement.src = source; + source = imageElement; + } + _this = _super.call(this, source) || this; + // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height + // to non-zero values before its loading completes if images are in a cache. + // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images. + // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968). + if (!source.complete && !!_this._width && !!_this._height) { + _this._width = 0; + _this._height = 0; + } + /** + * URL of the image source + * @member {string} + */ + _this.url = source.src; + /** + * When process is completed + * @member {Promise} + * @private + */ + _this._process = null; + /** + * If the image should be disposed after upload + * @member {boolean} + * @default false + */ + _this.preserveBitmap = false; + /** + * If capable, convert the image using createImageBitmap API + * @member {boolean} + * @default PIXI.settings.CREATE_IMAGE_BITMAP + */ + _this.createBitmap = (options.createBitmap !== undefined + ? options.createBitmap : settings.settings.CREATE_IMAGE_BITMAP) && !!window.createImageBitmap; + /** + * Controls texture alphaMode field + * Copies from options + * Default is `null`, copies option from baseTexture + * + * @member {PIXI.ALPHA_MODES|null} + * @readonly + */ + _this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null; + if (options.premultiplyAlpha !== undefined) { + // triggers deprecation + _this.premultiplyAlpha = options.premultiplyAlpha; + } + /** + * The ImageBitmap element created for HTMLImageElement + * @member {ImageBitmap} + * @default null + */ + _this.bitmap = null; + /** + * Promise when loading + * @member {Promise} + * @private + * @default null + */ + _this._load = null; + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } /** - * Specify the type of div the accessible layer is. Screen readers treat the element differently - * depending on this type. Defaults to button. + * returns a promise when image will be loaded and processed * - * @member {string} - * @memberof PIXI.DisplayObject# - * @default 'button' + * @param {boolean} [createBitmap] - whether process image into bitmap + * @returns {Promise} */ - accessibleType: 'button', - + ImageResource.prototype.load = function (createBitmap) { + var _this = this; + if (this._load) { + return this._load; + } + if (createBitmap !== undefined) { + this.createBitmap = createBitmap; + } + this._load = new Promise(function (resolve, reject) { + var source = _this.source; + _this.url = source.src; + var completed = function () { + if (_this.destroyed) { + return; + } + source.onload = null; + source.onerror = null; + _this.resize(source.width, source.height); + _this._load = null; + if (_this.createBitmap) { + resolve(_this.process()); + } + else { + resolve(_this); + } + }; + if (source.complete && source.src) { + completed(); + } + else { + source.onload = completed; + source.onerror = function (event) { + // Avoids Promise freezing when resource broken + reject(event); + _this.onError.emit(event); + }; + } + }); + return this._load; + }; /** - * Specify the pointer-events the accessible div will use - * Defaults to auto. + * Called when we need to convert image into BitmapImage. + * Can be called multiple times, real promise is cached inside. * - * @member {string} - * @memberof PIXI.DisplayObject# - * @default 'auto' + * @returns {Promise} cached promise to fill that bitmap */ - accessiblePointerEvents: 'auto', - + ImageResource.prototype.process = function () { + var _this = this; + var source = this.source; + if (this._process !== null) { + return this._process; + } + if (this.bitmap !== null || !window.createImageBitmap) { + return Promise.resolve(this); + } + this._process = window.createImageBitmap(source, 0, 0, source.width, source.height, { + premultiplyAlpha: this.alphaMode === constants.ALPHA_MODES.UNPACK ? 'premultiply' : 'none', + }) + .then(function (bitmap) { + if (_this.destroyed) { + return Promise.reject(); + } + _this.bitmap = bitmap; + _this.update(); + _this._process = null; + return Promise.resolve(_this); + }); + return this._process; + }; /** - * Setting to false will prevent any children inside this container to - * be accessible. Defaults to true. + * Upload the image resource to GPU. * - * @member {boolean} - * @memberof PIXI.DisplayObject# - * @default true + * @param {PIXI.Renderer} renderer - Renderer to upload to + * @param {PIXI.BaseTexture} baseTexture - BaseTexture for this resource + * @param {PIXI.GLTexture} glTexture - GLTexture to use + * @returns {boolean} true is success */ - accessibleChildren: true, -}; - -// add some extra variables to the container.. -display.DisplayObject.mixin(accessibleTarget); - -var KEY_CODE_TAB = 9; - -var DIV_TOUCH_SIZE = 100; -var DIV_TOUCH_POS_X = 0; -var DIV_TOUCH_POS_Y = 0; -var DIV_TOUCH_ZINDEX = 2; - -var DIV_HOOK_SIZE = 1; -var DIV_HOOK_POS_X = -1000; -var DIV_HOOK_POS_Y = -1000; -var DIV_HOOK_ZINDEX = 2; + ImageResource.prototype.upload = function (renderer, baseTexture, glTexture) { + if (typeof this.alphaMode === 'number') { + // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it + baseTexture.alphaMode = this.alphaMode; + } + if (!this.createBitmap) { + return _super.prototype.upload.call(this, renderer, baseTexture, glTexture); + } + if (!this.bitmap) { + // yeah, ignore the output + this.process(); + if (!this.bitmap) { + return false; + } + } + _super.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap); + if (!this.preserveBitmap) { + // checks if there are other renderers that possibly need this bitmap + var flag = true; + var glTextures = baseTexture._glTextures; + for (var key in glTextures) { + var otherTex = glTextures[key]; + if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) { + flag = false; + break; + } + } + if (flag) { + if (this.bitmap.close) { + this.bitmap.close(); + } + this.bitmap = null; + } + } + return true; + }; + /** + * Destroys this texture + * @override + */ + ImageResource.prototype.dispose = function () { + this.source.onload = null; + this.source.onerror = null; + _super.prototype.dispose.call(this); + if (this.bitmap) { + this.bitmap.close(); + this.bitmap = null; + } + this._process = null; + this._load = null; + }; + /** + * Used to auto-detect the type of resource. + * + * @static + * @param {string|HTMLImageElement} source - The source object + * @return {boolean} `true` if source is string or HTMLImageElement + */ + ImageResource.test = function (source) { + return typeof source === 'string' || source instanceof HTMLImageElement; + }; + return ImageResource; +}(BaseImageResource)); /** - * The Accessibility manager recreates the ability to tab and have content read by screen readers. - * This is very important as it can possibly help people with disabilities access PixiJS content. - * - * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the - * events as if the mouse was being used, minimizing the effort required to implement. - * - * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility` - * + * Resource type for SVG elements and graphics. * @class - * @memberof PIXI.accessibility - */ -var AccessibilityManager = function AccessibilityManager(renderer) -{ + * @extends PIXI.resources.BaseImageResource + * @memberof PIXI.resources + * @param {string} source - Base64 encoded SVG element or URL for SVG file. + * @param {object} [options] - Options to use + * @param {number} [options.scale=1] - Scale to apply to SVG. Overridden by... + * @param {number} [options.width] - Rasterize SVG this wide. Aspect ratio preserved if height not specified. + * @param {number} [options.height] - Rasterize SVG this high. Aspect ratio preserved if width not specified. + * @param {boolean} [options.autoLoad=true] - Start loading right away. + */ +var SVGResource = /** @class */ (function (_super) { + __extends(SVGResource, _super); + function SVGResource(sourceBase64, options) { + var _this = this; + options = options || {}; + _this = _super.call(this, document.createElement('canvas')) || this; + _this._width = 0; + _this._height = 0; + /** + * Base64 encoded SVG element or URL for SVG file + * @readonly + * @member {string} + */ + _this.svg = sourceBase64; + /** + * The source scale to apply when rasterizing on load + * @readonly + * @member {number} + */ + _this.scale = options.scale || 1; + /** + * A width override for rasterization on load + * @readonly + * @member {number} + */ + _this._overrideWidth = options.width; + /** + * A height override for rasterization on load + * @readonly + * @member {number} + */ + _this._overrideHeight = options.height; + /** + * Call when completely loaded + * @private + * @member {function} + */ + _this._resolve = null; + /** + * Cross origin value to use + * @private + * @member {boolean|string} + */ + _this._crossorigin = options.crossorigin; + /** + * Promise when loading + * @member {Promise} + * @private + * @default null + */ + _this._load = null; + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + SVGResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + this._load = new Promise(function (resolve) { + // Save this until after load is finished + _this._resolve = function () { + _this.resize(_this.source.width, _this.source.height); + resolve(_this); + }; + // Convert SVG inline string to data-uri + if ((/^\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + return SVGResource; +}(BaseImageResource)); +/** + * Resource type for HTMLVideoElement. + * @class + * @extends PIXI.resources.BaseImageResource + * @memberof PIXI.resources + * @param {HTMLVideoElement|object|string|Array} source - Video element to use. + * @param {object} [options] - Options to use + * @param {boolean} [options.autoLoad=true] - Start loading the video immediately + * @param {boolean} [options.autoPlay=true] - Start playing video immediately + * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video. + * Leave at 0 to update at every render. + * @param {boolean} [options.crossorigin=true] - Load image using cross origin + */ +var VideoResource = /** @class */ (function (_super) { + __extends(VideoResource, _super); + function VideoResource(source, options) { + var _this = this; + options = options || {}; + if (!(source instanceof HTMLVideoElement)) { + var videoElement = document.createElement('video'); + // workaround for https://github.com/pixijs/pixi.js/issues/5996 + videoElement.setAttribute('preload', 'auto'); + videoElement.setAttribute('webkit-playsinline', ''); + videoElement.setAttribute('playsinline', ''); + if (typeof source === 'string') { + source = [source]; + } + var firstSrc = source[0].src || source[0]; + BaseImageResource.crossOrigin(videoElement, firstSrc, options.crossorigin); + // array of objects or strings + for (var i = 0; i < source.length; ++i) { + var sourceElement = document.createElement('source'); + var _a = source[i], src = _a.src, mime = _a.mime; + src = src || source[i]; + var baseSrc = src.split('?').shift().toLowerCase(); + var ext = baseSrc.substr(baseSrc.lastIndexOf('.') + 1); + mime = mime || VideoResource.MIME_TYPES[ext] || "video/" + ext; + sourceElement.src = src; + sourceElement.type = mime; + videoElement.appendChild(sourceElement); + } + // Override the source + source = videoElement; + } + _this = _super.call(this, source) || this; + _this.noSubImage = true; + /** + * `true` to use PIXI.Ticker.shared to auto update the base texture. + * + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = true; + /** + * `true` if the instance is currently connected to PIXI.Ticker.shared to auto update the base texture. + * + * @type {boolean} + * @default false + * @private + */ + _this._isConnectedToTicker = false; + _this._updateFPS = options.updateFPS || 0; + _this._msToNextUpdate = 0; + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = options.autoPlay !== false; + /** + * Promise when loading + * @member {Promise} + * @private + * @default null + */ + _this._load = null; + /** + * Callback when completed with load. + * @member {function} + * @private + */ + _this._resolve = null; + // Bind for listeners + _this._onCanPlay = _this._onCanPlay.bind(_this); + _this._onError = _this._onError.bind(_this); + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Trigger updating of the texture + * + * @param {number} [deltaTime=0] - time delta since last tick + */ + VideoResource.prototype.update = function (_deltaTime) { + if (_deltaTime === void 0) { _deltaTime = 0; } + if (!this.destroyed) { + // account for if video has had its playbackRate changed + var elapsedMS = ticker.Ticker.shared.elapsedMS * this.source.playbackRate; + this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS); + if (!this._updateFPS || this._msToNextUpdate <= 0) { + _super.prototype.update.call(this); + this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0; + } + } + }; + /** + * Start preloading the video resource. + * + * @protected + * @return {Promise} Handle the validate event + */ + VideoResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + var source = this.source; + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) + && source.width && source.height) { + source.complete = true; + } + source.addEventListener('play', this._onPlayStart.bind(this)); + source.addEventListener('pause', this._onPlayStop.bind(this)); + if (!this._isSourceReady()) { + source.addEventListener('canplay', this._onCanPlay); + source.addEventListener('canplaythrough', this._onCanPlay); + source.addEventListener('error', this._onError, true); + } + else { + this._onCanPlay(); + } + this._load = new Promise(function (resolve) { + if (_this.valid) { + resolve(_this); + } + else { + _this._resolve = resolve; + source.load(); + } + }); + return this._load; + }; /** - * This is a tick used to check if an object is no longer being rendered. + * Handle video error events. * - * @type {Number} * @private */ - this.renderId = 0; - + VideoResource.prototype._onError = function (event) { + this.source.removeEventListener('error', this._onError, true); + this.onError.emit(event); + }; /** - * Setting this to true will visually show the divs. + * Returns true if the underlying source is playing. * - * @type {boolean} + * @private + * @return {boolean} True if playing. */ - this.debug = false; - + VideoResource.prototype._isSourcePlaying = function () { + var source = this.source; + return (source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2); + }; /** - * The renderer this accessibility manager works for. + * Returns true if the underlying source is ready for playing. * - * @member {PIXI.AbstractRenderer} + * @private + * @return {boolean} True if ready. */ - this.renderer = renderer; - + VideoResource.prototype._isSourceReady = function () { + var source = this.source; + return source.readyState === 3 || source.readyState === 4; + }; /** - * The array of currently active accessible items. + * Runs the update loop when the video is ready to play * - * @member {Array<*>} * @private */ - this.children = []; - + VideoResource.prototype._onPlayStart = function () { + // Just in case the video has not received its can play even yet.. + if (!this.valid) { + this._onCanPlay(); + } + if (this.autoUpdate && !this._isConnectedToTicker) { + ticker.Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + }; /** - * pre-bind the functions + * Fired when a pause event is triggered, stops the update loop * - * @type {Function} * @private */ - this._onKeyDown = this._onKeyDown.bind(this); - + VideoResource.prototype._onPlayStop = function () { + if (this._isConnectedToTicker) { + ticker.Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + }; /** - * pre-bind the functions + * Fired when the video is loaded and ready to play * - * @type {Function} * @private */ - this._onMouseMove = this._onMouseMove.bind(this); - + VideoResource.prototype._onCanPlay = function () { + var source = this.source; + source.removeEventListener('canplay', this._onCanPlay); + source.removeEventListener('canplaythrough', this._onCanPlay); + var valid = this.valid; + this.resize(source.videoWidth, source.videoHeight); + // prevent multiple loaded dispatches.. + if (!valid && this._resolve) { + this._resolve(this); + this._resolve = null; + } + if (this._isSourcePlaying()) { + this._onPlayStart(); + } + else if (this.autoPlay) { + source.play(); + } + }; /** - * A flag - * @type {boolean} + * Destroys this texture + * @override + */ + VideoResource.prototype.dispose = function () { + if (this._isConnectedToTicker) { + ticker.Ticker.shared.remove(this.update, this); + } + var source = this.source; + if (source) { + source.removeEventListener('error', this._onError, true); + source.pause(); + source.src = ''; + source.load(); + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(VideoResource.prototype, "autoUpdate", { + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + get: function () { + return this._autoUpdate; + }, + set: function (value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + ticker.Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) { + ticker.Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(VideoResource.prototype, "updateFPS", { + /** + * How many times a second to update the texture from the video. Leave at 0 to update at every render. + * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient. + * + * @member {number} + */ + get: function () { + return this._updateFPS; + }, + set: function (value) { + if (value !== this._updateFPS) { + this._updateFPS = value; + } + }, + enumerable: false, + configurable: true + }); + /** + * Used to auto-detect the type of resource. + * + * @static + * @param {*} source - The source object + * @param {string} extension - The extension of source, if set + * @return {boolean} `true` if video source + */ + VideoResource.test = function (source, extension) { + return (source instanceof HTMLVideoElement) + || VideoResource.TYPES.indexOf(extension) > -1; + }; + /** + * List of common video file extensions supported by VideoResource. + * @constant + * @member {Array} + * @static * @readonly */ - this.isActive = false; - + VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov']; /** - * A flag - * @type {boolean} + * Map of video MIME types that can't be directly derived from file extensions. + * @constant + * @member {object} + * @static * @readonly */ - this.isMobileAccessibility = false; - - // let listen for tab.. once pressed we can fire up and show the accessibility layer - window.addEventListener('keydown', this._onKeyDown, false); -}; + VideoResource.MIME_TYPES = { + ogv: 'video/ogg', + mov: 'video/quicktime', + m4v: 'video/mp4', + }; + return VideoResource; +}(BaseImageResource)); /** - * Creates the touch hooks. - * - * @private + * Resource type for ImageBitmap. + * @class + * @extends PIXI.resources.BaseImageResource + * @memberof PIXI.resources + * @param {ImageBitmap} source - Image element to use */ -AccessibilityManager.prototype.createTouchHook = function createTouchHook () -{ - var this$1 = this; - - var hookDiv = document.createElement('button'); - - hookDiv.style.width = DIV_HOOK_SIZE + "px"; - hookDiv.style.height = DIV_HOOK_SIZE + "px"; - hookDiv.style.position = 'absolute'; - hookDiv.style.top = DIV_HOOK_POS_X + "px"; - hookDiv.style.left = DIV_HOOK_POS_Y + "px"; - hookDiv.style.zIndex = DIV_HOOK_ZINDEX; - hookDiv.style.backgroundColor = '#FF0000'; - hookDiv.title = 'HOOK DIV'; - - hookDiv.addEventListener('focus', function () { - this$1.isMobileAccessibility = true; - this$1.activate(); - this$1.destroyTouchHook(); - }); +var ImageBitmapResource = /** @class */ (function (_super) { + __extends(ImageBitmapResource, _super); + function ImageBitmapResource() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Used to auto-detect the type of resource. + * + * @static + * @param {ImageBitmap} source - The source object + * @return {boolean} `true` if source is an ImageBitmap + */ + ImageBitmapResource.test = function (source) { + return !!window.createImageBitmap && source instanceof ImageBitmap; + }; + return ImageBitmapResource; +}(BaseImageResource)); - document.body.appendChild(hookDiv); - this._hookDiv = hookDiv; -}; +INSTALLED.push(ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource); -/** - * Destroys the touch hooks. - * - * @private - */ -AccessibilityManager.prototype.destroyTouchHook = function destroyTouchHook () -{ - if (!this._hookDiv) - { - return; - } - document.body.removeChild(this._hookDiv); - this._hookDiv = null; -}; +var index = ({ + Resource: Resource, + BaseImageResource: BaseImageResource, + INSTALLED: INSTALLED, + autoDetectResource: autoDetectResource, + AbstractMultiResource: AbstractMultiResource, + ArrayResource: ArrayResource, + BufferResource: BufferResource, + CanvasResource: CanvasResource, + CubeResource: CubeResource, + ImageResource: ImageResource, + SVGResource: SVGResource, + VideoResource: VideoResource, + ImageBitmapResource: ImageBitmapResource +}); /** - * Activating will cause the Accessibility layer to be shown. - * This is called when a user presses the tab key. + * System is a base class used for extending systems used by the {@link PIXI.Renderer} * - * @private + * @see PIXI.Renderer#addSystem + * @class + * @memberof PIXI */ -AccessibilityManager.prototype.activate = function activate () -{ - if (this.isActive) - { - return; - } - - this.isActive = true; - - window.document.addEventListener('mousemove', this._onMouseMove, true); - window.removeEventListener('keydown', this._onKeyDown, false); - - this.renderer.on('postrender', this.update, this); - - if (this.renderer.view.parentNode) - { - this.renderer.view.parentNode.appendChild(this.div); +var System = /** @class */ (function () { + /** + * @param {PIXI.Renderer} renderer - The renderer this manager works for. + */ + function System(renderer) { + /** + * The renderer this manager works for. + * + * @member {PIXI.Renderer} + */ + this.renderer = renderer; } -}; + /** + * Generic destroy methods to be overridden by the subclass + */ + System.prototype.destroy = function () { + this.renderer = null; + }; + return System; +}()); /** - * Deactivating will cause the Accessibility layer to be hidden. - * This is called when a user moves the mouse. - * - * @private + * Resource type for DepthTexture. + * @class + * @extends PIXI.resources.BufferResource + * @memberof PIXI.resources */ -AccessibilityManager.prototype.deactivate = function deactivate () -{ - if (!this.isActive || this.isMobileAccessibility) - { - return; +var DepthResource = /** @class */ (function (_super) { + __extends(DepthResource, _super); + function DepthResource() { + return _super !== null && _super.apply(this, arguments) || this; } - - this.isActive = false; - - window.document.removeEventListener('mousemove', this._onMouseMove, true); - window.addEventListener('keydown', this._onKeyDown, false); - - this.renderer.off('postrender', this.update); - - if (this.div.parentNode) - { - this.div.parentNode.removeChild(this.div); - } -}; + /** + * Upload the texture to the GPU. + * @param {PIXI.Renderer} renderer - Upload to the renderer + * @param {PIXI.BaseTexture} baseTexture - Reference to parent texture + * @param {PIXI.GLTexture} glTexture - glTexture + * @returns {boolean} true is success + */ + DepthResource.prototype.upload = function (renderer, baseTexture, glTexture) { + var gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants.ALPHA_MODES.UNPACK); + if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, baseTexture.width, baseTexture.height, baseTexture.format, baseTexture.type, this.data); + } + else { + glTexture.width = baseTexture.width; + glTexture.height = baseTexture.height; + gl.texImage2D(baseTexture.target, 0, + // gl.DEPTH_COMPONENT16 Needed for depth to render properly in webgl2.0 + renderer.context.webGLVersion === 1 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, baseTexture.width, baseTexture.height, 0, baseTexture.format, baseTexture.type, this.data); + } + return true; + }; + return DepthResource; +}(BufferResource)); /** - * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * Frame buffer used by the BaseRenderTexture * - * @private - * @param {PIXI.Container} displayObject - The DisplayObject to check. - */ -AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects (displayObject) -{ - if (!displayObject.visible || !displayObject.accessibleChildren) - { - return; - } - - if (displayObject.accessible && displayObject.interactive) - { - if (!displayObject._accessibleActive) - { - this.addChild(displayObject); - } - - displayObject.renderId = this.renderId; - } - - var children = displayObject.children; - - for (var i = 0; i < children.length; i++) - { - this.updateAccessibleObjects(children[i]); - } -}; - -/** - * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. - * - * @private - */ -AccessibilityManager.prototype.update = function update () -{ - if (!this.renderer.renderingToScreen) - { - return; - } - - // update children... - this.updateAccessibleObjects(this.renderer._lastObjectRendered); - - var rect = this.renderer.view.getBoundingClientRect(); - var sx = rect.width / this.renderer.width; - var sy = rect.height / this.renderer.height; - - var div = this.div; - - div.style.left = (rect.left) + "px"; - div.style.top = (rect.top) + "px"; - div.style.width = (this.renderer.width) + "px"; - div.style.height = (this.renderer.height) + "px"; - - for (var i = 0; i < this.children.length; i++) - { - var child = this.children[i]; - - if (child.renderId !== this.renderId) - { - child._accessibleActive = false; - - utils.removeItems(this.children, i, 1); - this.div.removeChild(child._accessibleDiv); - this.pool.push(child._accessibleDiv); - child._accessibleDiv = null; - - i--; - - if (this.children.length === 0) - { - this.deactivate(); - } - } - else - { - // map div to display.. - div = child._accessibleDiv; - var hitArea = child.hitArea; - var wt = child.worldTransform; - - if (child.hitArea) - { - div.style.left = ((wt.tx + (hitArea.x * wt.a)) * sx) + "px"; - div.style.top = ((wt.ty + (hitArea.y * wt.d)) * sy) + "px"; - - div.style.width = (hitArea.width * wt.a * sx) + "px"; - div.style.height = (hitArea.height * wt.d * sy) + "px"; - } - else - { - hitArea = child.getBounds(); - - this.capHitArea(hitArea); - - div.style.left = (hitArea.x * sx) + "px"; - div.style.top = (hitArea.y * sy) + "px"; - - div.style.width = (hitArea.width * sx) + "px"; - div.style.height = (hitArea.height * sy) + "px"; - - // update button titles and hints if they exist and they've changed - if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) - { - div.title = child.accessibleTitle; - } - if (div.getAttribute('aria-label') !== child.accessibleHint - && child.accessibleHint !== null) - { - div.setAttribute('aria-label', child.accessibleHint); - } - } - - // the title or index may have changed, if so lets update it! - if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) - { - div.title = child.accessibleTitle; - div.tabIndex = child.tabIndex; - if (this.debug) { this.updateDebugHTML(div); } - } - } - } - - // increment the render id.. - this.renderId++; -}; - -/** - * private function that will visually add the information to the - * accessability div - * - * @param {HTMLDivElement} div - */ -AccessibilityManager.prototype.updateDebugHTML = function updateDebugHTML (div) -{ - div.innerHTML = "type: " + (div.type) + "
title : " + (div.title) + "
tabIndex: " + (div.tabIndex); -}; - -/** - * Adjust the hit area based on the bounds of a display object - * - * @param {PIXI.Rectangle} hitArea - Bounds of the child + * @class + * @memberof PIXI */ -AccessibilityManager.prototype.capHitArea = function capHitArea (hitArea) -{ - if (hitArea.x < 0) - { - hitArea.width += hitArea.x; - hitArea.x = 0; - } - - if (hitArea.y < 0) - { - hitArea.height += hitArea.y; - hitArea.y = 0; - } - - if (hitArea.x + hitArea.width > this.renderer.width) - { - hitArea.width = this.renderer.width - hitArea.x; - } - - if (hitArea.y + hitArea.height > this.renderer.height) - { - hitArea.height = this.renderer.height - hitArea.y; +var Framebuffer = /** @class */ (function () { + /** + * @param {number} width - Width of the frame buffer + * @param {number} height - Height of the frame buffer + */ + function Framebuffer(width, height) { + /** + * Width of framebuffer in pixels + * @member {number} + */ + this.width = Math.ceil(width || 100); + /** + * Height of framebuffer in pixels + * @member {number} + */ + this.height = Math.ceil(height || 100); + this.stencil = false; + this.depth = false; + this.dirtyId = 0; + this.dirtyFormat = 0; + this.dirtySize = 0; + this.depthTexture = null; + this.colorTextures = []; + this.glFramebuffers = {}; + this.disposeRunner = new runner.Runner('disposeFramebuffer'); + /** + * Desired number of samples for antialiasing. 0 means AA should not be used. + * + * Experimental WebGL2 feature, allows to use antialiasing in individual renderTextures. + * Antialiasing is the same as for main buffer with renderer `antialias:true` options. + * Seriously affects GPU memory consumption and GPU performance. + * + *```js + * renderTexture.framebuffer.multisample = PIXI.MSAA_QUALITY.HIGH; + * //... + * renderer.render(renderTexture, myContainer); + * renderer.framebuffer.blit(); // copies data from MSAA framebuffer to texture + * ``` + * + * @member {PIXI.MSAA_QUALITY} + * @default PIXI.MSAA_QUALITY.NONE + */ + this.multisample = constants.MSAA_QUALITY.NONE; } -}; - -/** - * Adds a DisplayObject to the accessibility manager - * - * @private - * @param {PIXI.DisplayObject} displayObject - The child to make accessible. - */ -AccessibilityManager.prototype.addChild = function addChild (displayObject) -{ - //this.activate(); - - var div = this.pool.pop(); - - if (!div) - { - div = document.createElement('button'); - - div.style.width = DIV_TOUCH_SIZE + "px"; - div.style.height = DIV_TOUCH_SIZE + "px"; - div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent'; - div.style.position = 'absolute'; - div.style.zIndex = DIV_TOUCH_ZINDEX; - div.style.borderStyle = 'none'; - - // ARIA attributes ensure that button title and hint updates are announced properly - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) - { - // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. - div.setAttribute('aria-live', 'off'); - } - else - { - div.setAttribute('aria-live', 'polite'); + Object.defineProperty(Framebuffer.prototype, "colorTexture", { + /** + * Reference to the colorTexture. + * + * @member {PIXI.BaseTexture[]} + * @readonly + */ + get: function () { + return this.colorTextures[0]; + }, + enumerable: false, + configurable: true + }); + /** + * Add texture to the colorTexture array + * + * @param {number} [index=0] - Index of the array to add the texture to + * @param {PIXI.BaseTexture} [texture] - Texture to add to the array + */ + Framebuffer.prototype.addColorTexture = function (index, texture) { + if (index === void 0) { index = 0; } + // TODO add some validation to the texture - same width / height etc? + this.colorTextures[index] = texture || new BaseTexture(null, { + scaleMode: constants.SCALE_MODES.NEAREST, + resolution: 1, + mipmap: constants.MIPMAP_MODES.OFF, + width: this.width, + height: this.height, + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Add a depth texture to the frame buffer + * + * @param {PIXI.BaseTexture} [texture] - Texture to add + */ + Framebuffer.prototype.addDepthTexture = function (texture) { + /* eslint-disable max-len */ + this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { + scaleMode: constants.SCALE_MODES.NEAREST, + resolution: 1, + width: this.width, + height: this.height, + mipmap: constants.MIPMAP_MODES.OFF, + format: constants.FORMATS.DEPTH_COMPONENT, + type: constants.TYPES.UNSIGNED_SHORT, + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Enable depth on the frame buffer + */ + Framebuffer.prototype.enableDepth = function () { + this.depth = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Enable stencil on the frame buffer + */ + Framebuffer.prototype.enableStencil = function () { + this.stencil = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Resize the frame buffer + * + * @param {number} width - Width of the frame buffer to resize to + * @param {number} height - Height of the frame buffer to resize to + */ + Framebuffer.prototype.resize = function (width, height) { + width = Math.ceil(width); + height = Math.ceil(height); + if (width === this.width && height === this.height) + { return; } + this.width = width; + this.height = height; + this.dirtyId++; + this.dirtySize++; + for (var i = 0; i < this.colorTextures.length; i++) { + var texture = this.colorTextures[i]; + var resolution = texture.resolution; + // take into acount the fact the texture may have a different resolution.. + texture.setSize(width / resolution, height / resolution); } - - if (navigator.userAgent.match(/rv:.*Gecko\//)) - { - // FireFox needs this to announce only the new button name - div.setAttribute('aria-relevant', 'additions'); + if (this.depthTexture) { + var resolution = this.depthTexture.resolution; + this.depthTexture.setSize(width / resolution, height / resolution); } - else - { - // required by IE, other browsers don't much care - div.setAttribute('aria-relevant', 'text'); + }; + /** + * Disposes WebGL resources that are connected to this geometry + */ + Framebuffer.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** + * Destroys and removes the depth texture added to this framebuffer. + */ + Framebuffer.prototype.destroyDepthTexture = function () { + if (this.depthTexture) { + this.depthTexture.destroy(); + this.depthTexture = null; + ++this.dirtyId; + ++this.dirtyFormat; } - - div.addEventListener('click', this._onClick.bind(this)); - div.addEventListener('focus', this._onFocus.bind(this)); - div.addEventListener('focusout', this._onFocusOut.bind(this)); - } - - // set pointer events - div.style.pointerEvents = displayObject.accessiblePointerEvents; - // set the type, this defaults to button! - div.type = displayObject.accessibleType; - - if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) - { - div.title = displayObject.accessibleTitle; - } - else if (!displayObject.accessibleHint - || displayObject.accessibleHint === null) - { - div.title = "displayObject " + (displayObject.tabIndex); - } - - if (displayObject.accessibleHint - && displayObject.accessibleHint !== null) - { - div.setAttribute('aria-label', displayObject.accessibleHint); - } - - if (this.debug) { this.updateDebugHTML(div); } - - displayObject._accessibleActive = true; - displayObject._accessibleDiv = div; - div.displayObject = displayObject; - - this.children.push(displayObject); - this.div.appendChild(displayObject._accessibleDiv); - displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; -}; - -/** - * Maps the div button press to pixi's InteractionManager (click) - * - * @private - * @param {MouseEvent} e - The click event. - */ -AccessibilityManager.prototype._onClick = function _onClick (e) -{ - var interactionManager = this.renderer.plugins.interaction; - - interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); - interactionManager.dispatchEvent(e.target.displayObject, 'pointertap', interactionManager.eventData); - interactionManager.dispatchEvent(e.target.displayObject, 'tap', interactionManager.eventData); -}; - -/** - * Maps the div focus events to pixi's InteractionManager (mouseover) - * - * @private - * @param {FocusEvent} e - The focus event. - */ -AccessibilityManager.prototype._onFocus = function _onFocus (e) -{ - if (!e.target.getAttribute('aria-live', 'off')) - { - e.target.setAttribute('aria-live', 'assertive'); - } - var interactionManager = this.renderer.plugins.interaction; - - interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); -}; + }; + return Framebuffer; +}()); /** - * Maps the div focus events to pixi's InteractionManager (mouseout) + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. * - * @private - * @param {FocusEvent} e - The focusout event. - */ -AccessibilityManager.prototype._onFocusOut = function _onFocusOut (e) -{ - if (!e.target.getAttribute('aria-live', 'off')) - { - e.target.setAttribute('aria-live', 'polite'); - } - var interactionManager = this.renderer.plugins.interaction; - - interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); -}; - -/** - * Is called when a key is pressed + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. * - * @private - * @param {KeyboardEvent} e - The keydown event. - */ -AccessibilityManager.prototype._onKeyDown = function _onKeyDown (e) -{ - if (e.keyCode !== KEY_CODE_TAB) - { - return; - } - - this.activate(); -}; - -/** - * Is called when the mouse moves across the renderer element + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: * - * @private - * @param {MouseEvent} e - The mouse event. - */ -AccessibilityManager.prototype._onMouseMove = function _onMouseMove (e) -{ - if (e.movementX === 0 && e.movementY === 0) - { - return; - } - - this.deactivate(); -}; - -/** - * Destroys the accessibility manager + * ```js + * let renderer = PIXI.autoDetectRenderer(); + * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 }); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * let sprite = PIXI.Sprite.from("spinObj_01.png"); * - */ -AccessibilityManager.prototype.destroy = function destroy () -{ - this.destroyTouchHook(); - this.div = null; - - for (var i = 0; i < this.children.length; i++) - { - this.children[i].div = null; - } - - window.document.removeEventListener('mousemove', this._onMouseMove, true); - window.removeEventListener('keydown', this._onKeyDown); - - this.pool = null; - this.children = null; - this.renderer = null; -}; - -/** - * This namespace contains an accessibility plugin for allowing interaction via the keyboard. + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; * - * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. - * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. - * @namespace PIXI.accessibility - */ - -exports.AccessibilityManager = AccessibilityManager; -exports.accessibleTarget = accessibleTarget; - - -},{"@pixi/display":18,"@pixi/utils":47}],15:[function(require,module,exports){ -/*! - * @pixi/app - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * renderer.render(sprite, renderTexture); + * ``` * - * @pixi/app is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var display = require('@pixi/display'); -var core = require('@pixi/core'); - -/** - * Convenience class to create a new PIXI application. + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform * - * This class automatically creates the renderer, ticker and root container. + * ```js * - * @example - * // Create the application - * const app = new PIXI.Application(); + * sprite.setTransform() * - * // Add the view to the DOM - * document.body.appendChild(app.view); + * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 }); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); * - * // ex, add display objects - * app.stage.addChild(PIXI.Sprite.from('something.png')); + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` * * @class + * @extends PIXI.BaseTexture * @memberof PIXI */ -var Application = function Application(options) -{ - var this$1 = this; - - // The default options - options = Object.assign({ - forceCanvas: false, - }, options); - +var BaseRenderTexture = /** @class */ (function (_super) { + __extends(BaseRenderTexture, _super); /** - * WebGL renderer if available, otherwise CanvasRenderer. - * @member {PIXI.Renderer|PIXI.CanvasRenderer} + * @param {object} [options] + * @param {number} [options.width=100] - The width of the base render texture. + * @param {number} [options.height=100] - The height of the base render texture. + * @param {PIXI.SCALE_MODES} [options.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the texture being generated. */ - this.renderer = core.autoDetectRenderer(options); - + function BaseRenderTexture(options) { + var _this = this; + if (typeof options === 'number') { + /* eslint-disable prefer-rest-params */ + // Backward compatibility of signature + var width_1 = arguments[0]; + var height_1 = arguments[1]; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + options = { width: width_1, height: height_1, scaleMode: scaleMode, resolution: resolution }; + /* eslint-enable prefer-rest-params */ + } + _this = _super.call(this, null, options) || this; + var _a = options || {}, width = _a.width, height = _a.height; + // Set defaults + _this.mipmap = 0; + _this.width = Math.ceil(width) || 100; + _this.height = Math.ceil(height) || 100; + _this.valid = true; + _this.clearColor = [0, 0, 0, 0]; + _this.framebuffer = new Framebuffer(_this.width * _this.resolution, _this.height * _this.resolution) + .addColorTexture(0, _this); + // TODO - could this be added the systems? + /** + * The data structure for the stencil masks. + * + * @member {PIXI.MaskData[]} + */ + _this.maskStack = []; + /** + * The data structure for the filters. + * + * @member {Object[]} + */ + _this.filterStack = [{}]; + return _this; + } /** - * The root display container that's rendered. - * @member {PIXI.Container} + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. */ - this.stage = new display.Container(); - - // install plugins here - Application._plugins.forEach(function (plugin) { - plugin.init.call(this$1, options); - }); -}; - -var prototypeAccessors = { view: { configurable: true },screen: { configurable: true } }; - -/** - * Register a middleware plugin for the application - * @static - * @param {PIXI.Application.Plugin} plugin - Plugin being installed - */ -Application.registerPlugin = function registerPlugin (plugin) -{ - Application._plugins.push(plugin); -}; - -/** - * Render the current stage. - */ -Application.prototype.render = function render () -{ - this.renderer.render(this.stage); -}; - -/** - * Reference to the renderer's canvas element. - * @member {HTMLCanvasElement} - * @readonly - */ -prototypeAccessors.view.get = function () -{ - return this.renderer.view; -}; - -/** - * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen. - * @member {PIXI.Rectangle} - * @readonly - */ -prototypeAccessors.screen.get = function () -{ - return this.renderer.screen; -}; - -/** - * Destroy and don't use after this. - * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. - * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy - * method called as well. 'stageOptions' will be passed on to those calls. - * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set - * to true. Should it destroy the texture of the child sprite - * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set - * to true. Should it destroy the base texture of the child sprite - */ -Application.prototype.destroy = function destroy (removeView, stageOptions) -{ - var this$1 = this; - - // Destroy plugins in the opposite order - // which they were constructed - var plugins = Application._plugins.slice(0); - - plugins.reverse(); - plugins.forEach(function (plugin) { - plugin.destroy.call(this$1); - }); - - this.stage.destroy(stageOptions); - this.stage = null; - - this.renderer.destroy(removeView); - this.renderer = null; - - this._options = null; -}; - -Object.defineProperties( Application.prototype, prototypeAccessors ); - -/** - * @memberof PIXI.Application - * @typedef {object} Plugin - * @property {function} init - Called when Application is constructed, scoped to Application instance. - * Passes in `options` as the only argument, which are Application constructor options. - * @property {function} destroy - Called when destroying Application, scoped to Application instance - */ - -/** - * Collection of installed plugins. - * @static - * @private - * @type {PIXI.Application.Plugin[]} - */ -Application._plugins = []; - -/** - * Middleware for for Application's resize functionality - * @private - * @class - */ -var ResizePlugin = function ResizePlugin () {}; - -ResizePlugin.init = function init (options) -{ - var this$1 = this; - + BaseRenderTexture.prototype.resize = function (width, height) { + width = Math.ceil(width); + height = Math.ceil(height); + this.framebuffer.resize(width * this.resolution, height * this.resolution); + }; /** - * The element or window to resize the application to. - * @type {Window|HTMLElement} - * @name resizeTo - * @memberof PIXI.Application# + * Frees the texture and framebuffer from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + * @fires PIXI.BaseTexture#dispose */ - Object.defineProperty(this, 'resizeTo', - { - set: function set(dom) - { - window.removeEventListener('resize', this.resize); - this._resizeTo = dom; - if (dom) - { - window.addEventListener('resize', this.resize); - this.resize(); - } - }, - get: function get() - { - return this._resizeTo; - }, - }); - + BaseRenderTexture.prototype.dispose = function () { + this.framebuffer.dispose(); + _super.prototype.dispose.call(this); + }; /** - * If `resizeTo` is set, calling this function - * will resize to the width and height of that element. - * @method PIXI.Application#resize + * Destroys this texture. */ - this.resize = function () { - if (this$1._resizeTo) - { - // Resize to the window - if (this$1._resizeTo === window) - { - this$1.renderer.resize( - window.innerWidth, - window.innerHeight - ); - } - // Resize to other HTML entities - else - { - this$1.renderer.resize( - this$1._resizeTo.clientWidth, - this$1._resizeTo.clientHeight - ); - } - } + BaseRenderTexture.prototype.destroy = function () { + _super.prototype.destroy.call(this); + this.framebuffer.destroyDepthTexture(); + this.framebuffer = null; }; - - // On resize - this._resizeTo = null; - this.resizeTo = options.resizeTo || null; -}; + return BaseRenderTexture; +}(BaseTexture)); /** - * Clean up the ticker, scoped to application - * @static - * @private - */ -ResizePlugin.destroy = function destroy () -{ - this.resizeTo = null; - this.resize = null; -}; - -Application.registerPlugin(ResizePlugin); - -exports.Application = Application; - - -},{"@pixi/core":17,"@pixi/display":18}],16:[function(require,module,exports){ -/*! - * @pixi/constants - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * Stores a texture's frame in UV coordinates, in + * which everything lies in the rectangle `[(0,0), (1,0), + * (1,1), (0,1)]`. * - * @pixi/constants is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license + * | Corner | Coordinates | + * |--------------|-------------| + * | Top-Left | `(x0,y0)` | + * | Top-Right | `(x1,y1)` | + * | Bottom-Right | `(x2,y2)` | + * | Bottom-Left | `(x3,y3)` | + * + * @class + * @protected + * @memberof PIXI */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); +var TextureUvs = /** @class */ (function () { + function TextureUvs() { + /** + * X-component of top-left corner `(x0,y0)`. + * + * @member {number} + */ + this.x0 = 0; + /** + * Y-component of top-left corner `(x0,y0)`. + * + * @member {number} + */ + this.y0 = 0; + /** + * X-component of top-right corner `(x1,y1)`. + * + * @member {number} + */ + this.x1 = 1; + /** + * Y-component of top-right corner `(x1,y1)`. + * + * @member {number} + */ + this.y1 = 0; + /** + * X-component of bottom-right corner `(x2,y2)`. + * + * @member {number} + */ + this.x2 = 1; + /** + * Y-component of bottom-right corner `(x2,y2)`. + * + * @member {number} + */ + this.y2 = 1; + /** + * X-component of bottom-left corner `(x3,y3)`. + * + * @member {number} + */ + this.x3 = 0; + /** + * Y-component of bottom-right corner `(x3,y3)`. + * + * @member {number} + */ + this.y3 = 1; + this.uvsFloat32 = new Float32Array(8); + } + /** + * Sets the texture Uvs based on the given frame information. + * + * @protected + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.groupD8} + */ + TextureUvs.prototype.set = function (frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + // coordinates of center + var cX = (frame.x / tw) + w2; + var cY = (frame.y / th) + h2; + rotate = math.groupD8.add(rotate, math.groupD8.NW); // NW is top-left corner + this.x0 = cX + (w2 * math.groupD8.uX(rotate)); + this.y0 = cY + (h2 * math.groupD8.uY(rotate)); + rotate = math.groupD8.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + (w2 * math.groupD8.uX(rotate)); + this.y1 = cY + (h2 * math.groupD8.uY(rotate)); + rotate = math.groupD8.add(rotate, 2); + this.x2 = cX + (w2 * math.groupD8.uX(rotate)); + this.y2 = cY + (h2 * math.groupD8.uY(rotate)); + rotate = math.groupD8.add(rotate, 2); + this.x3 = cX + (w2 * math.groupD8.uX(rotate)); + this.y3 = cY + (h2 * math.groupD8.uY(rotate)); + } + else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + this.uvsFloat32[0] = this.x0; + this.uvsFloat32[1] = this.y0; + this.uvsFloat32[2] = this.x1; + this.uvsFloat32[3] = this.y1; + this.uvsFloat32[4] = this.x2; + this.uvsFloat32[5] = this.y2; + this.uvsFloat32[6] = this.x3; + this.uvsFloat32[7] = this.y3; + }; + return TextureUvs; +}()); +var DEFAULT_UVS = new TextureUvs(); /** - * Different types of environments for WebGL. + * A texture stores the information that represents an image or part of an image. * - * @static - * @memberof PIXI - * @name ENV - * @enum {number} - * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility - * with older / less advanced devices. If you experience unexplained flickering prefer this environment. - * @property {number} WEBGL - Version 1 of WebGL - * @property {number} WEBGL2 - Version 2 of WebGL - */ -(function (ENV) { - ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; - ENV[ENV["WEBGL"] = 1] = "WEBGL"; - ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; -})(exports.ENV || (exports.ENV = {})); -(function (RENDERER_TYPE) { - RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; - RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; - RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; -})(exports.RENDERER_TYPE || (exports.RENDERER_TYPE = {})); -(function (BLEND_MODES) { - BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; - BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; - BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; - BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; - BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; - BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; - BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; - BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; - BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; - BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; - BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; - BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; - BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; - BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; - BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; - BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; - BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; - BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; - BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; - BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; - BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; - BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; - BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; - BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; - BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; - BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; - BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; - BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; - BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; - BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; - BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; - BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; -})(exports.BLEND_MODES || (exports.BLEND_MODES = {})); -(function (DRAW_MODES) { - DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; - DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; - DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; - DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; - DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; - DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; - DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; -})(exports.DRAW_MODES || (exports.DRAW_MODES = {})); -(function (FORMATS) { - FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; - FORMATS[FORMATS["RGB"] = 6407] = "RGB"; - FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; - FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; - FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; - FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; - FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; -})(exports.FORMATS || (exports.FORMATS = {})); -(function (TARGETS) { - TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; - TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; -})(exports.TARGETS || (exports.TARGETS = {})); -(function (TYPES) { - TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; - TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; - TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; - TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; - TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; - TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; - TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; -})(exports.TYPES || (exports.TYPES = {})); -(function (SCALE_MODES) { - SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; - SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; -})(exports.SCALE_MODES || (exports.SCALE_MODES = {})); -(function (WRAP_MODES) { - WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; - WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; - WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; -})(exports.WRAP_MODES || (exports.WRAP_MODES = {})); -(function (MIPMAP_MODES) { - MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; - MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; - MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; -})(exports.MIPMAP_MODES || (exports.MIPMAP_MODES = {})); -(function (ALPHA_MODES) { - ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; - ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; - ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; - ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; - ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; - ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; -})(exports.ALPHA_MODES || (exports.ALPHA_MODES = {})); -(function (GC_MODES) { - GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; - GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; -})(exports.GC_MODES || (exports.GC_MODES = {})); -(function (PRECISION) { - PRECISION["LOW"] = "lowp"; - PRECISION["MEDIUM"] = "mediump"; - PRECISION["HIGH"] = "highp"; -})(exports.PRECISION || (exports.PRECISION = {})); -(function (MASK_TYPES) { - MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; - MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; - MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; - MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; -})(exports.MASK_TYPES || (exports.MASK_TYPES = {})); - - -},{}],17:[function(require,module,exports){ -/*! - * @pixi/core - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/core is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var runner = require('@pixi/runner'); -var utils = require('@pixi/utils'); -var constants = require('@pixi/constants'); -var settings = require('@pixi/settings'); -var ticker = require('@pixi/ticker'); -var math = require('@pixi/math'); -var display = require('@pixi/display'); - -/** - * Base resource class for textures that manages validation and uploading, depending on its type. - * - * Uploading of a base texture to the GPU is required. - * - * @class - * @memberof PIXI.resources - */ -var Resource = function Resource(width, height) -{ - if ( width === void 0 ) width = 0; - if ( height === void 0 ) height = 0; - - /** - * Internal width of the resource - * @member {number} - * @protected - */ - this._width = width; - - /** - * Internal height of the resource - * @member {number} - * @protected - */ - this._height = height; - - /** - * If resource has been destroyed - * @member {boolean} - * @readonly - * @default false - */ - this.destroyed = false; - - /** - * `true` if resource is created by BaseTexture - * useful for doing cleanup with BaseTexture destroy - * and not cleaning up resources that were created - * externally. - * @member {boolean} - * @protected - */ - this.internal = false; - - /** - * Mini-runner for handling resize events - * - * @member {Runner} - * @private - */ - this.onResize = new runner.Runner('setRealSize', 2); - - /** - * Mini-runner for handling update events - * - * @member {Runner} - * @private - */ - this.onUpdate = new runner.Runner('update'); - - /** - * Handle internal errors, such as loading errors - * - * @member {Runner} - * @private - */ - this.onError = new runner.Runner('onError', 1); -}; - -var prototypeAccessors = { valid: { configurable: true },width: { configurable: true },height: { configurable: true } }; - -/** - * Bind to a parent BaseTexture - * - * @param {PIXI.BaseTexture} baseTexture - Parent texture - */ -Resource.prototype.bind = function bind (baseTexture) -{ - this.onResize.add(baseTexture); - this.onUpdate.add(baseTexture); - this.onError.add(baseTexture); - - // Call a resize immediate if we already - // have the width and height of the resource - if (this._width || this._height) - { - this.onResize.run(this._width, this._height); - } -}; - -/** - * Unbind to a parent BaseTexture - * - * @param {PIXI.BaseTexture} baseTexture - Parent texture - */ -Resource.prototype.unbind = function unbind (baseTexture) -{ - this.onResize.remove(baseTexture); - this.onUpdate.remove(baseTexture); - this.onError.remove(baseTexture); -}; - -/** - * Trigger a resize event - * @param {number} width X dimension - * @param {number} height Y dimension - */ -Resource.prototype.resize = function resize (width, height) -{ - if (width !== this._width || height !== this._height) - { - this._width = width; - this._height = height; - this.onResize.run(width, height); - } -}; - -/** - * Has been validated - * @readonly - * @member {boolean} - */ -prototypeAccessors.valid.get = function () -{ - return !!this._width && !!this._height; -}; - -/** - * Has been updated trigger event - */ -Resource.prototype.update = function update () -{ - if (!this.destroyed) - { - this.onUpdate.run(); - } -}; - -/** - * This can be overridden to start preloading a resource - * or do any other prepare step. - * @protected - * @return {Promise} Handle the validate event - */ -Resource.prototype.load = function load () -{ - return Promise.resolve(); -}; - -/** - * The width of the resource. + * It cannot be added to the display list directly; instead use it as the texture for a Sprite. + * If no frame is provided for a texture, then the whole image is used. * - * @member {number} - * @readonly - */ -prototypeAccessors.width.get = function () -{ - return this._width; -}; - -/** - * The height of the resource. + * You can directly create a texture from an image and then reuse it multiple times like this : * - * @member {number} - * @readonly - */ -prototypeAccessors.height.get = function () -{ - return this._height; -}; - -/** - * Uploads the texture or returns false if it cant for some reason. Override this. + * ```js + * let texture = PIXI.Texture.from('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` * - * @param {PIXI.Renderer} renderer - yeah, renderer! - * @param {PIXI.BaseTexture} baseTexture - the texture - * @param {PIXI.GLTexture} glTexture - texture instance for this webgl context - * @returns {boolean} true is success - */ -Resource.prototype.upload = function upload (renderer, baseTexture, glTexture) // eslint-disable-line no-unused-vars -{ - return false; -}; - -/** - * Set the style, optional to override + * If you didnt pass the texture frame to constructor, it enables `noFrame` mode: + * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture. * - * @param {PIXI.Renderer} renderer - yeah, renderer! - * @param {PIXI.BaseTexture} baseTexture - the texture - * @param {PIXI.GLTexture} glTexture - texture instance for this webgl context - * @returns {boolean} `true` is success - */ -Resource.prototype.style = function style (renderer, baseTexture, glTexture) // eslint-disable-line no-unused-vars -{ - return false; -}; - -/** - * Clean up anything, this happens when destroying is ready. + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.from('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. * - * @protected - */ -Resource.prototype.dispose = function dispose () -{ - // override -}; - -/** - * Call when destroying resource, unbind any BaseTexture object - * before calling this method, as reference counts are maintained - * internally. - */ -Resource.prototype.destroy = function destroy () -{ - if (!this.destroyed) - { - this.destroyed = true; - this.dispose(); - this.onError.removeAll(); - this.onError = null; - this.onResize.removeAll(); - this.onResize = null; - this.onUpdate.removeAll(); - this.onUpdate = null; - } -}; - -Object.defineProperties( Resource.prototype, prototypeAccessors ); - -/** - * Base for all the image/canvas resources * @class - * @extends PIXI.resources.Resource - * @memberof PIXI.resources + * @extends PIXI.utils.EventEmitter + * @memberof PIXI */ -var BaseImageResource = /*@__PURE__*/(function (Resource) { - function BaseImageResource(source) - { - var width = source.naturalWidth || source.videoWidth || source.width; - var height = source.naturalHeight || source.videoHeight || source.height; - - Resource.call(this, width, height); - - /** - * The source element - * @member {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} - * @readonly - */ - this.source = source; - +var Texture = /** @class */ (function (_super) { + __extends(Texture, _super); + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8} + * @param {PIXI.IPointData} [anchor] - Default anchor point used for sprite placement / rotation + */ + function Texture(baseTexture, frame, orig, trim, rotate, anchor) { + var _this = _super.call(this) || this; /** - * If set to `true`, will force `texImage2D` over `texSubImage2D` for uploading. - * Certain types of media (e.g. video) using `texImage2D` is more performant. + * Does this Texture have any frame data assigned to it? + * + * This mode is enabled automatically if no frame was passed inside constructor. + * + * In this mode texture is subscribed to baseTexture events, and fires `update` on any change. + * + * Beware, after loading or resize of baseTexture event can fired two times! + * If you want more control, subscribe on baseTexture itself. + * + * ```js + * texture.on('update', () => {}); + * ``` + * + * Any assignment of `frame` switches off `noFrame` mode. + * * @member {boolean} - * @default false - * @private */ - this.noSubImage = false; - } - - if ( Resource ) BaseImageResource.__proto__ = Resource; - BaseImageResource.prototype = Object.create( Resource && Resource.prototype ); - BaseImageResource.prototype.constructor = BaseImageResource; - - /** - * Set cross origin based detecting the url and the crossorigin - * @protected - * @param {HTMLElement} element - Element to apply crossOrigin - * @param {string} url - URL to check - * @param {boolean|string} [crossorigin=true] - Cross origin value to use - */ - BaseImageResource.crossOrigin = function crossOrigin (element, url, crossorigin) - { - if (crossorigin === undefined && url.indexOf('data:') !== 0) - { - element.crossOrigin = utils.determineCrossOrigin(url); - } - else if (crossorigin !== false) - { - element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; - } - }; - - /** - * Upload the texture to the GPU. - * @param {PIXI.Renderer} renderer Upload to the renderer - * @param {PIXI.BaseTexture} baseTexture Reference to parent texture - * @param {PIXI.GLTexture} glTexture - * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] (optional) - * @returns {boolean} true is success - */ - BaseImageResource.prototype.upload = function upload (renderer, baseTexture, glTexture, source) - { - var gl = renderer.gl; - var width = baseTexture.realWidth; - var height = baseTexture.realHeight; - - source = source || this.source; - - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants.ALPHA_MODES.UNPACK); - - if (!this.noSubImage - && baseTexture.target === gl.TEXTURE_2D - && glTexture.width === width - && glTexture.height === height) - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, baseTexture.type, source); - } - else - { - glTexture.width = width; - glTexture.height = height; - - gl.texImage2D(baseTexture.target, 0, baseTexture.format, baseTexture.format, baseTexture.type, source); - } - - return true; - }; - - /** - * Checks if source width/height was changed, resize can cause extra baseTexture update. - * Triggers one update in any case. - */ - BaseImageResource.prototype.update = function update () - { - if (this.destroyed) - { - return; - } - - var width = this.source.naturalWidth || this.source.videoWidth || this.source.width; - var height = this.source.naturalHeight || this.source.videoHeight || this.source.height; - - this.resize(width, height); - - Resource.prototype.update.call(this); - }; - - /** - * Destroy this BaseImageResource - * @override - * @param {PIXI.BaseTexture} [fromTexture] Optional base texture - * @return {boolean} Destroy was successful - */ - BaseImageResource.prototype.dispose = function dispose () - { - this.source = null; - }; - - return BaseImageResource; -}(Resource)); - -/** - * Resource type for HTMLImageElement. - * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - */ -var ImageResource = /*@__PURE__*/(function (BaseImageResource) { - function ImageResource(source, options) - { - options = options || {}; - - if (!(source instanceof HTMLImageElement)) - { - var imageElement = new Image(); - - BaseImageResource.crossOrigin(imageElement, source, options.crossorigin); - - imageElement.src = source; - source = imageElement; + _this.noFrame = false; + if (!frame) { + _this.noFrame = true; + frame = new math.Rectangle(0, 0, 1, 1); } - - BaseImageResource.call(this, source); - - // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height - // to non-zero values before its loading completes if images are in a cache. - // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images. - // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968). - if (!source.complete && !!this._width && !!this._height) - { - this._width = 0; - this._height = 0; + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; } - /** - * URL of the image source - * @member {string} + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} */ - this.url = source.src; - + _this.baseTexture = baseTexture; /** - * When process is completed - * @member {Promise} - * @private + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} */ - this._process = null; - + _this._frame = frame; /** - * If the image should be disposed after upload - * @member {boolean} - * @default false + * This is the trimmed area of original texture, before it was put in atlas + * Please call `updateUvs()` after you change coordinates of `trim` manually. + * + * @member {PIXI.Rectangle} */ - this.preserveBitmap = false; - + _this.trim = trim; /** - * If capable, convert the image using createImageBitmap API + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * * @member {boolean} - * @default PIXI.settings.CREATE_IMAGE_BITMAP */ - this.createBitmap = (options.createBitmap !== undefined - ? options.createBitmap : settings.settings.CREATE_IMAGE_BITMAP) && !!window.createImageBitmap; - + _this.valid = false; /** - * Controls texture alphaMode field - * Copies from options - * Default is `null`, copies option from baseTexture + * The WebGL UV data cache. Can be used as quad UV * - * @member {PIXI.ALPHA_MODES|null} - * @readonly + * @member {PIXI.TextureUvs} + * @protected */ - this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null; - - if (options.premultiplyAlpha !== undefined) - { - // triggers deprecation - this.premultiplyAlpha = options.premultiplyAlpha; + _this._uvs = DEFAULT_UVS; + /** + * Default TextureMatrix instance for this texture + * By default that object is not created because its heavy + * + * @member {PIXI.TextureMatrix} + */ + _this.uvMatrix = null; + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + _this._rotate = Number(rotate || 0); + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } + else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); } - /** - * The ImageBitmap element created for HTMLImageElement - * @member {ImageBitmap} - * @default null + * Anchor point that is used as default if sprite is created with this texture. + * Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point. + * @member {PIXI.Point} + * @default {0,0} */ - this.bitmap = null; - + _this.defaultAnchor = anchor ? new math.Point(anchor.x, anchor.y) : new math.Point(0, 0); /** - * Promise when loading - * @member {Promise} - * @private - * @default null + * Update ID is observed by sprites and TextureMatrix instances. + * Call updateUvs() to increment it. + * + * @member {number} + * @protected */ - this._load = null; - - if (options.autoLoad !== false) - { - this.load(); + _this._updateID = 0; + /** + * The ids under which this Texture has been added to the texture cache. This is + * automatically set as long as Texture.addToCache is used, but may not be set if a + * Texture is added directly to the TextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + if (!baseTexture.valid) { + baseTexture.once('loaded', _this.onBaseTextureUpdated, _this); + } + else if (_this.noFrame) { + // if there is no frame we should monitor for any base texture changes.. + if (baseTexture.valid) { + _this.onBaseTextureUpdated(baseTexture); + } } + else { + _this.frame = frame; + } + if (_this.noFrame) { + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + return _this; } - - if ( BaseImageResource ) ImageResource.__proto__ = BaseImageResource; - ImageResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); - ImageResource.prototype.constructor = ImageResource; - /** - * returns a promise when image will be loaded and processed + * Updates this texture on the gpu. + * + * Calls the TextureResource update. + * + * If you adjusted `frame` manually, please call `updateUvs()` instead. * - * @param {boolean} [createBitmap=true] whether process image into bitmap - * @returns {Promise} */ - ImageResource.prototype.load = function load (createBitmap) - { - var this$1 = this; - - if (createBitmap !== undefined) - { - this.createBitmap = createBitmap; - } - - if (this._load) - { - return this._load; + Texture.prototype.update = function () { + if (this.baseTexture.resource) { + this.baseTexture.resource.update(); } - - this._load = new Promise(function (resolve) { - this$1.url = this$1.source.src; - var ref = this$1; - var source = ref.source; - - var completed = function () { - if (this$1.destroyed) - { - return; - } - source.onload = null; - source.onerror = null; - - this$1.resize(source.width, source.height); - this$1._load = null; - - if (this$1.createBitmap) - { - resolve(this$1.process()); - } - else - { - resolve(this$1); - } - }; - - if (source.complete && source.src) - { - completed(); - } - else - { - source.onload = completed; - source.onerror = function (event) { return this$1.onError.run(event); }; - } - }); - - return this._load; }; - /** - * Called when we need to convert image into BitmapImage. - * Can be called multiple times, real promise is cached inside. + * Called when the base texture is updated * - * @returns {Promise} cached promise to fill that bitmap + * @protected + * @param {PIXI.BaseTexture} baseTexture - The base texture. */ - ImageResource.prototype.process = function process () - { - var this$1 = this; - - if (this._process !== null) - { - return this._process; + Texture.prototype.onBaseTextureUpdated = function (baseTexture) { + if (this.noFrame) { + if (!this.baseTexture.valid) { + return; + } + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + this.valid = true; + this.updateUvs(); } - if (this.bitmap !== null || !window.createImageBitmap) - { - return Promise.resolve(this); + else { + // TODO this code looks confusing.. boo to abusing getters and setters! + // if user gave us frame that has bigger size than resized texture it can be a problem + this.frame = this._frame; } - - this._process = window.createImageBitmap(this.source, - 0, 0, this.source.width, this.source.height, - { - premultiplyAlpha: this.premultiplyAlpha === constants.ALPHA_MODES.UNPACK ? 'premultiply' : 'none', - }) - .then(function (bitmap) { - if (this$1.destroyed) - { - return Promise.reject(); + this.emit('update', this); + }; + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well + */ + Texture.prototype.destroy = function (destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + var resource = this.baseTexture; + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (resource && resource.url && utils.TextureCache[resource.url]) { + Texture.removeFromCache(resource.url); } - this$1.bitmap = bitmap; - this$1.update(); - this$1._process = null; - - return Promise.resolve(this$1); - }); - - return this._process; + this.baseTexture.destroy(); + } + this.baseTexture.off('loaded', this.onBaseTextureUpdated, this); + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture = null; + } + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + this.valid = false; + Texture.removeFromCache(this); + this.textureCacheIds = null; }; - /** - * Upload the image resource to GPU. + * Creates a new texture object that acts the same as this one. * - * @param {PIXI.Renderer} renderer - Renderer to upload to - * @param {PIXI.BaseTexture} baseTexture - BaseTexture for this resource - * @param {PIXI.GLTexture} glTexture - GLTexture to use - * @returns {boolean} true is success + * @return {PIXI.Texture} The new texture */ - ImageResource.prototype.upload = function upload (renderer, baseTexture, glTexture) - { - if (typeof this.alphaMode === 'number') - { - // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it - - baseTexture.alphaMode = this.alphaMode; + Texture.prototype.clone = function () { + return new Texture(this.baseTexture, this.frame.clone(), this.orig.clone(), this.trim && this.trim.clone(), this.rotate, this.defaultAnchor); + }; + /** + * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. + * Call it after changing the frame + */ + Texture.prototype.updateUvs = function () { + if (this._uvs === DEFAULT_UVS) { + this._uvs = new TextureUvs(); } - - if (!this.createBitmap) - { - return BaseImageResource.prototype.upload.call(this, renderer, baseTexture, glTexture); + this._uvs.set(this._frame, this.baseTexture, this.rotate); + this._updateID++; + }; + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source + * Source to create texture from + * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. + * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. + * @return {PIXI.Texture} The newly created texture + */ + Texture.from = function (source, options, strict) { + if (options === void 0) { options = {}; } + if (strict === void 0) { strict = settings.settings.STRICT_TEXTURE_CACHE; } + var isFrame = typeof source === 'string'; + var cacheId = null; + if (isFrame) { + cacheId = source; } - if (!this.bitmap) - { - // yeah, ignore the output - this.process(); - if (!this.bitmap) - { - return false; + else { + if (!source._pixiId) { + source._pixiId = "pixiid_" + utils.uid(); } + cacheId = source._pixiId; } - - BaseImageResource.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap); - - if (!this.preserveBitmap) - { - // checks if there are other renderers that possibly need this bitmap - - var flag = true; - - for (var key in baseTexture._glTextures) - { - var otherTex = baseTexture._glTextures[key]; - - if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) - { - flag = false; - break; - } - } - - if (flag) - { - if (this.bitmap.close) - { - this.bitmap.close(); - } - - this.bitmap = null; + var texture = utils.TextureCache[cacheId]; + // Strict-mode rejects invalid cacheIds + if (isFrame && strict && !texture) { + throw new Error("The cacheId \"" + cacheId + "\" does not exist in TextureCache."); + } + if (!texture) { + if (!options.resolution) { + options.resolution = utils.getResolutionOfUrl(source); } + texture = new Texture(new BaseTexture(source, options)); + texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); + Texture.addToCache(texture, cacheId); } - - return true; + // lets assume its a base texture! + return texture; }; - /** - * Destroys this texture - * @override + * Useful for loading textures via URLs. Use instead of `Texture.from` because + * it does a better job of handling failed URLs more effectively. This also ignores + * `PIXI.settings.STRICT_TEXTURE_CACHE`. Works for Videos, SVGs, Images. + * @param {string} url The remote URL to load. + * @param {object} [options] Optional options to include + * @return {Promise} A Promise that resolves to a Texture. */ - ImageResource.prototype.dispose = function dispose () - { - this.source.onload = null; - this.source.onerror = null; - - BaseImageResource.prototype.dispose.call(this); - - if (this.bitmap) - { - this.bitmap.close(); - this.bitmap = null; + Texture.fromURL = function (url, options) { + var resourceOptions = Object.assign({ autoLoad: false }, options === null || options === void 0 ? void 0 : options.resourceOptions); + var texture = Texture.from(url, Object.assign({ resourceOptions: resourceOptions }, options), false); + var resource = texture.baseTexture.resource; + // The texture was already loaded + if (texture.baseTexture.valid) { + return Promise.resolve(texture); } - this._process = null; - this._load = null; + // Manually load the texture, this should allow users to handle load errors + return resource.load().then(function () { return Promise.resolve(texture); }); }; - - return ImageResource; -}(BaseImageResource)); - -/** - * Collection of installed resource types, class must extend {@link PIXI.resources.Resource}. - * @example - * class CustomResource extends PIXI.resources.Resource { - * // MUST have source, options constructor signature - * // for auto-detected resources to be created. - * constructor(source, options) { - * super(); - * } - * upload(renderer, baseTexture, glTexture) { - * // upload with GL - * return true; - * } - * // used to auto-detect resource - * static test(source, extension) { - * return extension === 'xyz'|| source instanceof SomeClass; - * } - * } - * // Install the new resource type - * PIXI.resources.INSTALLED.push(CustomResource); - * - * @name PIXI.resources.INSTALLED - * @type {Array<*>} - * @static - * @readonly - */ -var INSTALLED = []; - -/** - * Create a resource element from a single source element. This - * auto-detects which type of resource to create. All resources that - * are auto-detectable must have a static `test` method and a constructor - * with the arguments `(source, options?)`. Currently, the supported - * resources for auto-detection include: - * - {@link PIXI.resources.ImageResource} - * - {@link PIXI.resources.CanvasResource} - * - {@link PIXI.resources.VideoResource} - * - {@link PIXI.resources.SVGResource} - * - {@link PIXI.resources.BufferResource} - * @static - * @function PIXI.resources.autoDetectResource - * @param {string|*} source - Resource source, this can be the URL to the resource, - * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri - * or any other resource that can be auto-detected. If not resource is - * detected, it's assumed to be an ImageResource. - * @param {object} [options] - Pass-through options to use for Resource - * @param {number} [options.width] - Width of BufferResource or SVG rasterization - * @param {number} [options.height] - Height of BufferResource or SVG rasterization - * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading - * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height - * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object - * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin - * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately - * @param {number} [options.updateFPS=0] - Video option to update how many times a second the - * texture should be updated from the video. Leave at 0 to update at every render - * @return {PIXI.resources.Resource} The created resource. - */ -function autoDetectResource(source, options) -{ - if (!source) - { - return null; - } - - var extension = ''; - - if (typeof source === 'string') - { - // search for file extension: period, 3-4 chars, then ?, # or EOL - var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source); - - if (result) - { - extension = result[1].toLowerCase(); - } - } - - for (var i = INSTALLED.length - 1; i >= 0; --i) - { - var ResourcePlugin = INSTALLED[i]; - - if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) - { - return new ResourcePlugin(source, options); - } - } - - // When in doubt: probably an image - // might be appropriate to throw an error or return null - return new ImageResource(source, options); -} - -/** - * @interface SharedArrayBuffer - */ - -/** - * Buffer resource with data of typed array. - * @class - * @extends PIXI.resources.Resource - * @memberof PIXI.resources - */ -var BufferResource = /*@__PURE__*/(function (Resource) { - function BufferResource(source, options) - { - var ref = options || {}; - var width = ref.width; - var height = ref.height; - - if (!width || !height) - { - throw new Error('BufferResource width or height invalid'); - } - - Resource.call(this, width, height); - - /** - * Source array - * Cannot be ClampedUint8Array because it cant be uploaded to WebGL - * - * @member {Float32Array|Uint8Array|Uint32Array} - */ - this.data = source; - } - - if ( Resource ) BufferResource.__proto__ = Resource; - BufferResource.prototype = Object.create( Resource && Resource.prototype ); - BufferResource.prototype.constructor = BufferResource; - /** - * Upload the texture to the GPU. - * @param {PIXI.Renderer} renderer Upload to the renderer - * @param {PIXI.BaseTexture} baseTexture Reference to parent texture - * @param {PIXI.GLTexture} glTexture glTexture - * @returns {boolean} true is success + * Create a new Texture with a BufferResource from a Float32Array. + * RGBA values are floats from 0 to 1. + * @static + * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data + * is provided, a new Float32Array is created. + * @param {number} width - Width of the resource + * @param {number} height - Height of the resource + * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. + * @return {PIXI.Texture} The resulting new BaseTexture */ - BufferResource.prototype.upload = function upload (renderer, baseTexture, glTexture) - { - var gl = renderer.gl; - - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants.ALPHA_MODES.UNPACK); - - if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height) - { - gl.texSubImage2D( - baseTexture.target, - 0, - 0, - 0, - baseTexture.width, - baseTexture.height, - baseTexture.format, - baseTexture.type, - this.data - ); + Texture.fromBuffer = function (buffer, width, height, options) { + return new Texture(BaseTexture.fromBuffer(buffer, width, height, options)); + }; + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readable name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + Texture.fromLoader = function (source, imageUrl, name) { + var resource = new ImageResource(source); + resource.url = imageUrl; + var baseTexture = new BaseTexture(resource, { + scaleMode: settings.settings.SCALE_MODE, + resolution: utils.getResolutionOfUrl(imageUrl), + }); + var texture = new Texture(baseTexture); + // No name, use imageUrl instead + if (!name) { + name = imageUrl; } - else - { - glTexture.width = baseTexture.width; - glTexture.height = baseTexture.height; - - gl.texImage2D( - baseTexture.target, - 0, - glTexture.internalFormat, - baseTexture.width, - baseTexture.height, - 0, - baseTexture.format, - glTexture.type, - this.data - ); + // lets also add the frame to pixi's global cache for 'fromLoader' function + BaseTexture.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + // also add references by url if they are different. + if (name !== imageUrl) { + BaseTexture.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); } - - return true; + return texture; }; - /** - * Destroy and don't use after this - * @override + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the Texture will be stored against. */ - BufferResource.prototype.dispose = function dispose () - { - this.data = null; + Texture.addToCache = function (texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + if (utils.TextureCache[id]) { + // eslint-disable-next-line no-console + console.warn("Texture added to the cache with an id [" + id + "] that already had an entry"); + } + utils.TextureCache[id] = texture; + } }; - /** - * Used to auto-detect the type of resource. + * Remove a Texture from the global TextureCache. * * @static - * @param {*} source - The source object - * @return {boolean} `true` if + * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself + * @return {PIXI.Texture|null} The Texture that was removed */ - BufferResource.test = function test (source) - { - return source instanceof Float32Array - || source instanceof Uint8Array - || source instanceof Uint32Array; - }; - - return BufferResource; -}(Resource)); - -var defaultBufferOptions = { - scaleMode: constants.SCALE_MODES.NEAREST, - format: constants.FORMATS.RGBA, - alphaMode: constants.ALPHA_MODES.NPM, -}; - -/** - * A Texture stores the information that represents an image. - * All textures have a base texture, which contains information about the source. - * Therefore you can have many textures all using a single BaseTexture - * - * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI - * @param {PIXI.resources.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] - * The current resource to use, for things that aren't Resource objects, will be converted - * into a Resource. - * @param {Object} [options] - Collection of options - * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture - * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture - * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures - * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest - * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type - * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type - * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target - * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha - * @param {number} [options.width=0] - Width of the texture - * @param {number} [options.height=0] - Height of the texture - * @param {number} [options.resolution] - Resolution of the base texture - * @param {object} [options.resourceOptions] - Optional resource options, - * see {@link PIXI.resources.autoDetectResource autoDetectResource} - */ -var BaseTexture = /*@__PURE__*/(function (EventEmitter) { - function BaseTexture(resource, options) - { - if ( resource === void 0 ) resource = null; - if ( options === void 0 ) options = null; - - EventEmitter.call(this); - - options = options || {}; - - var alphaMode = options.alphaMode; - var mipmap = options.mipmap; - var anisotropicLevel = options.anisotropicLevel; - var scaleMode = options.scaleMode; - var width = options.width; - var height = options.height; - var wrapMode = options.wrapMode; - var format = options.format; - var type = options.type; - var target = options.target; - var resolution = options.resolution; - var resourceOptions = options.resourceOptions; - - // Convert the resource to a Resource object - if (resource && !(resource instanceof Resource)) - { - resource = autoDetectResource(resource, resourceOptions); - resource.internal = true; + Texture.removeFromCache = function (texture) { + if (typeof texture === 'string') { + var textureFromCache = utils.TextureCache[texture]; + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + delete utils.TextureCache[texture]; + return textureFromCache; + } } - + else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + // Check that texture matches the one being passed in before deleting it from the cache. + if (utils.TextureCache[texture.textureCacheIds[i]] === texture) { + delete utils.TextureCache[texture.textureCacheIds[i]]; + } + } + texture.textureCacheIds.length = 0; + return texture; + } + return null; + }; + Object.defineProperty(Texture.prototype, "resolution", { /** - * The width of the base texture set when the image has loaded + * Returns resolution of baseTexture * - * @readonly * @member {number} - */ - this.width = width || 0; - - /** - * The height of the base texture set when the image has loaded - * * @readonly - * @member {number} - */ - this.height = height || 0; - - /** - * The resolution / device pixel ratio of the texture - * - * @member {number} - * @default PIXI.settings.RESOLUTION */ - this.resolution = resolution || settings.settings.RESOLUTION; - + get: function () { + return this.baseTexture.resolution; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "frame", { /** - * Mipmap mode of the texture, affects downscaled images + * The frame specifies the region of the base texture that this texture uses. + * Please call `updateUvs()` after you change coordinates of `frame` manually. * - * @member {PIXI.MIPMAP_MODES} - * @default PIXI.settings.MIPMAP_TEXTURES + * @member {PIXI.Rectangle} */ - this.mipmap = mipmap !== undefined ? mipmap : settings.settings.MIPMAP_TEXTURES; - + get: function () { + return this._frame; + }, + set: function (frame) { + this._frame = frame; + this.noFrame = false; + var x = frame.x, y = frame.y, width = frame.width, height = frame.height; + var xNotFit = x + width > this.baseTexture.width; + var yNotFit = y + height > this.baseTexture.height; + if (xNotFit || yNotFit) { + var relationship = xNotFit && yNotFit ? 'and' : 'or'; + var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + this.baseTexture.width; + var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + this.baseTexture.height; + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + + (errorX + " " + relationship + " " + errorY)); + } + this.valid = width && height && this.baseTexture.valid; + if (!this.trim && !this.rotate) { + this.orig = frame; + } + if (this.valid) { + this.updateUvs(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "rotate", { /** - * Anisotropic filtering level of texture + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.groupD8} for explanation * * @member {number} - * @default PIXI.settings.ANISOTROPIC_LEVEL - */ - this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings.settings.ANISOTROPIC_LEVEL; - - /** - * How the texture wraps - * @member {number} - */ - this.wrapMode = wrapMode || settings.settings.WRAP_MODE; - - /** - * The scale mode to apply when scaling this texture - * - * @member {PIXI.SCALE_MODES} - * @default PIXI.settings.SCALE_MODE */ - this.scaleMode = scaleMode !== undefined ? scaleMode : settings.settings.SCALE_MODE; - + get: function () { + return this._rotate; + }, + set: function (rotate) { + this._rotate = rotate; + if (this.valid) { + this.updateUvs(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "width", { /** - * The pixel format of the texture + * The width of the Texture in pixels. * - * @member {PIXI.FORMATS} - * @default PIXI.FORMATS.RGBA + * @member {number} */ - this.format = format || constants.FORMATS.RGBA; - + get: function () { + return this.orig.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "height", { /** - * The type of resource data + * The height of the Texture in pixels. * - * @member {PIXI.TYPES} - * @default PIXI.TYPES.UNSIGNED_BYTE + * @member {number} */ - this.type = type || constants.TYPES.UNSIGNED_BYTE; - - /** - * The target type - * - * @member {PIXI.TARGETS} - * @default PIXI.TARGETS.TEXTURE_2D - */ - this.target = target || constants.TARGETS.TEXTURE_2D; - - /** - * How to treat premultiplied alpha, see {@link PIXI.ALPHA_MODES}. - * - * @member {PIXI.ALPHA_MODES} - * @default PIXI.ALPHA_MODES.UNPACK - */ - this.alphaMode = alphaMode !== undefined ? alphaMode : constants.ALPHA_MODES.UNPACK; + get: function () { + return this.orig.height; + }, + enumerable: false, + configurable: true + }); + /** + * Utility function for BaseTexture|Texture cast + */ + Texture.prototype.castToBaseTexture = function () { + return this.baseTexture; + }; + return Texture; +}(utils.EventEmitter)); +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + canvas.width = 16; + canvas.height = 16; + var context = canvas.getContext('2d'); + context.fillStyle = 'white'; + context.fillRect(0, 0, 16, 16); + return new Texture(new BaseTexture(new CanvasResource(canvas))); +} +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() { }; + tex.on = function _emptyOn() { }; + tex.once = function _emptyOnce() { }; + tex.emit = function _emptyEmit() { }; +} +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + * @member {PIXI.Texture} + */ +Texture.EMPTY = new Texture(new BaseTexture()); +removeAllHandlers(Texture.EMPTY); +removeAllHandlers(Texture.EMPTY.baseTexture); +/** + * A white texture of 16x16 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + * @member {PIXI.Texture} + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); +removeAllHandlers(Texture.WHITE.baseTexture); - if (options.premultiplyAlpha !== undefined) - { - // triggers deprecation - this.premultiplyAlpha = options.premultiplyAlpha; +/** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * __Hint-2__: The actual memory allocation will happen on first render. + * You shouldn't create renderTextures each frame just to delete them after, try to reuse them. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(); + * let renderTexture = PIXI.RenderTexture.create({ width: 800, height: 600 }); + * let sprite = PIXI.Sprite.from("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = /** @class */ (function (_super) { + __extends(RenderTexture, _super); + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The base texture object that this texture uses + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + var _this = this; + // support for legacy.. + var _legacyRenderer = null; + if (!(baseRenderTexture instanceof BaseRenderTexture)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + // we have an old render texture.. + console.warn("Please use RenderTexture.create(" + width + ", " + height + ") instead of the ctor directly."); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + frame = null; + baseRenderTexture = new BaseRenderTexture({ + width: width, + height: height, + scaleMode: scaleMode, + resolution: resolution, + }); } - /** - * Global unique identifier for this BaseTexture - * - * @member {string} - * @protected - */ - this.uid = utils.uid(); - - /** - * Used by automatic texture Garbage Collection, stores last GC tick when it was bound + * The base texture object that this texture uses * - * @member {number} - * @protected + * @member {PIXI.BaseTexture} */ - this.touched = 0; - + _this = _super.call(this, baseRenderTexture, frame) || this; + _this.legacyRenderer = _legacyRenderer; /** - * Whether or not the texture is a power of two, try to use power of two textures as much - * as you can + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. * - * @readonly * @member {boolean} - * @default false - */ - this.isPowerOfTwo = false; - this._refreshPOT(); - - /** - * The map of render context textures where this is bound - * - * @member {Object} - * @private */ - this._glTextures = {}; - + _this.valid = true; /** - * Used by TextureSystem to only update texture to the GPU when needed. - * Please call `update()` to increment it. + * Stores `sourceFrame` when this texture is inside current filter stack. + * You can read it inside filters. * * @readonly - * @member {number} + * @member {PIXI.Rectangle} */ - this.dirtyId = 0; - + _this.filterFrame = null; /** - * Used by TextureSystem to only update texture style when needed. - * + * The key for pooled texture of FilterSystem * @protected - * @member {number} - */ - this.dirtyStyleId = 0; - - /** - * Currently default cache ID. - * * @member {string} */ - this.cacheId = null; - - /** - * Generally speaking means when resource is loaded. - * @readonly - * @member {boolean} - */ - this.valid = width > 0 && height > 0; - - /** - * The collection of alternative cache ids, since some BaseTextures - * can have more than one ID, short name and longer full URL - * - * @member {Array} - * @readonly - */ - this.textureCacheIds = []; - - /** - * Flag if BaseTexture has been destroyed. - * - * @member {boolean} - * @readonly - */ - this.destroyed = false; - + _this.filterPoolKey = null; + _this.updateUvs(); + return _this; + } + Object.defineProperty(RenderTexture.prototype, "framebuffer", { /** - * The resource used by this BaseTexture, there can only - * be one resource per BaseTexture, but textures can share - * resources. - * - * @member {PIXI.resources.Resource} + * Shortcut to `this.baseTexture.framebuffer`, saves baseTexture cast. + * @member {PIXI.Framebuffer} * @readonly */ - this.resource = null; - - /** - * Number of the texture batch, used by multi-texture renderers - * - * @member {number} - */ - this._batchEnabled = 0; - - /** - * Location inside texture batch, used by multi-texture renderers - * - * @member {number} - */ - this._batchLocation = 0; - - /** - * Fired when a not-immediately-available source finishes loading. - * - * @protected - * @event PIXI.BaseTexture#loaded - * @param {PIXI.BaseTexture} baseTexture - Resource loaded. - */ - - /** - * Fired when a not-immediately-available source fails to load. - * - * @protected - * @event PIXI.BaseTexture#error - * @param {PIXI.BaseTexture} baseTexture - Resource errored. - * @param {ErrorEvent} event - Load error event. - */ - - /** - * Fired when BaseTexture is updated. - * - * @protected - * @event PIXI.BaseTexture#loaded - * @param {PIXI.BaseTexture} baseTexture - Resource loaded. - */ - - /** - * Fired when BaseTexture is updated. - * - * @protected - * @event PIXI.BaseTexture#update - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. - */ - - /** - * Fired when BaseTexture is destroyed. - * - * @protected - * @event PIXI.BaseTexture#dispose - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. - */ - - // Set the resource - this.setResource(resource); - } - - if ( EventEmitter ) BaseTexture.__proto__ = EventEmitter; - BaseTexture.prototype = Object.create( EventEmitter && EventEmitter.prototype ); - BaseTexture.prototype.constructor = BaseTexture; - - var prototypeAccessors = { realWidth: { configurable: true },realHeight: { configurable: true } }; - + get: function () { + return this.baseTexture.framebuffer; + }, + enumerable: false, + configurable: true + }); /** - * Pixel width of the source of this texture + * Resizes the RenderTexture. * - * @readonly - * @member {number} + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} [resizeBaseTexture=true] - Should the baseTexture.width and height values be resized as well? */ - prototypeAccessors.realWidth.get = function () - { - return Math.ceil((this.width * this.resolution) - 1e-4); + RenderTexture.prototype.resize = function (width, height, resizeBaseTexture) { + if (resizeBaseTexture === void 0) { resizeBaseTexture = true; } + width = Math.ceil(width); + height = Math.ceil(height); + // TODO - could be not required.. + this.valid = (width > 0 && height > 0); + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + if (resizeBaseTexture) { + this.baseTexture.resize(width, height); + } + this.updateUvs(); }; - /** - * Pixel height of the source of this texture + * Changes the resolution of baseTexture, but does not change framebuffer size. * - * @readonly - * @member {number} + * @param {number} resolution - The new resolution to apply to RenderTexture */ - prototypeAccessors.realHeight.get = function () - { - return Math.ceil((this.height * this.resolution) - 1e-4); + RenderTexture.prototype.setResolution = function (resolution) { + var baseTexture = this.baseTexture; + if (baseTexture.resolution === resolution) { + return; + } + baseTexture.setResolution(resolution); + this.resize(baseTexture.width, baseTexture.height, false); }; - /** - * Changes style options of BaseTexture + * A short hand way of creating a render texture. * - * @param {PIXI.SCALE_MODES} [scaleMode] - Pixi scalemode - * @param {PIXI.MIPMAP_MODES} [mipmap] - enable mipmaps - * @returns {PIXI.BaseTexture} this + * @param {object} [options] - Options + * @param {number} [options.width=100] - The width of the render texture + * @param {number} [options.height=100] - The height of the render texture + * @param {number} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture */ - BaseTexture.prototype.setStyle = function setStyle (scaleMode, mipmap) - { - var dirty; - - if (scaleMode !== undefined && scaleMode !== this.scaleMode) - { - this.scaleMode = scaleMode; - dirty = true; - } - - if (mipmap !== undefined && mipmap !== this.mipmap) - { - this.mipmap = mipmap; - dirty = true; - } - - if (dirty) - { - this.dirtyStyleId++; + RenderTexture.create = function (options) { + // fallback, old-style: create(width, height, scaleMode, resolution) + if (typeof options === 'number') { + /* eslint-disable prefer-rest-params */ + options = { + width: options, + height: arguments[1], + scaleMode: arguments[2], + resolution: arguments[3], + }; + /* eslint-enable prefer-rest-params */ } - - return this; + return new RenderTexture(new BaseRenderTexture(options)); }; + return RenderTexture; +}(Texture)); +/** + * Experimental! + * + * Texture pool, used by FilterSystem and plugins + * Stores collection of temporary pow2 or screen-sized renderTextures + * + * If you use custom RenderTexturePool for your filters, you can use methods + * `getFilterTexture` and `returnFilterTexture` same as in + * + * @class + * @memberof PIXI + */ +var RenderTexturePool = /** @class */ (function () { /** - * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero. + * @param {object} [textureOptions] - options that will be passed to BaseRenderTexture constructor + * @param {PIXI.SCALE_MODES} [textureOptions.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values. + */ + function RenderTexturePool(textureOptions) { + this.texturePool = {}; + this.textureOptions = textureOptions || {}; + /** + * Allow renderTextures of the same size as screen, not just pow2 + * + * Automatically sets to true after `setScreenSize` + * + * @member {boolean} + * @default false + */ + this.enableFullScreen = false; + this._pixelsWidth = 0; + this._pixelsHeight = 0; + } + /** + * creates of texture with params that were specified in pool constructor * - * @param {number} width Visual width - * @param {number} height Visual height - * @param {number} [resolution] Optionally set resolution - * @returns {PIXI.BaseTexture} this + * @param {number} realWidth - width of texture in pixels + * @param {number} realHeight - height of texture in pixels + * @returns {RenderTexture} */ - BaseTexture.prototype.setSize = function setSize (width, height, resolution) - { - this.resolution = resolution || this.resolution; - this.width = width; - this.height = height; - this._refreshPOT(); - this.update(); - - return this; + RenderTexturePool.prototype.createTexture = function (realWidth, realHeight) { + var baseRenderTexture = new BaseRenderTexture(Object.assign({ + width: realWidth, + height: realHeight, + resolution: 1, + }, this.textureOptions)); + return new RenderTexture(baseRenderTexture); }; - /** - * Sets real size of baseTexture, preserves current resolution. + * Gets a Power-of-Two render texture or fullScreen texture * - * @param {number} realWidth Full rendered width - * @param {number} realHeight Full rendered height - * @param {number} [resolution] Optionally set resolution - * @returns {PIXI.BaseTexture} this + * @protected + * @param {number} minWidth - The minimum width of the render texture in real pixels. + * @param {number} minHeight - The minimum height of the render texture in real pixels. + * @param {number} [resolution=1] - The resolution of the render texture. + * @return {PIXI.RenderTexture} The new render texture. */ - BaseTexture.prototype.setRealSize = function setRealSize (realWidth, realHeight, resolution) - { - this.resolution = resolution || this.resolution; - this.width = realWidth / this.resolution; - this.height = realHeight / this.resolution; - this._refreshPOT(); - this.update(); - - return this; + RenderTexturePool.prototype.getOptimalTexture = function (minWidth, minHeight, resolution) { + if (resolution === void 0) { resolution = 1; } + var key = RenderTexturePool.SCREEN_KEY; + minWidth *= resolution; + minHeight *= resolution; + if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) { + minWidth = utils.nextPow2(minWidth); + minHeight = utils.nextPow2(minHeight); + key = ((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF); + } + if (!this.texturePool[key]) { + this.texturePool[key] = []; + } + var renderTexture = this.texturePool[key].pop(); + if (!renderTexture) { + renderTexture = this.createTexture(minWidth, minHeight); + } + renderTexture.filterPoolKey = key; + renderTexture.setResolution(resolution); + return renderTexture; }; - /** - * Refresh check for isPowerOfTwo texture based on size + * Gets extra texture of the same size as input renderTexture * - * @private + * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)` + * + * @param {PIXI.RenderTexture} input - renderTexture from which size and resolution will be copied + * @param {number} [resolution] - override resolution of the renderTexture + * It overrides, it does not multiply + * @returns {PIXI.RenderTexture} */ - BaseTexture.prototype._refreshPOT = function _refreshPOT () - { - this.isPowerOfTwo = utils.isPow2(this.realWidth) && utils.isPow2(this.realHeight); + RenderTexturePool.prototype.getFilterTexture = function (input, resolution) { + var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; }; - /** - * Changes resolution - * - * @param {number} [resolution] res - * @returns {PIXI.BaseTexture} this + * Place a render texture back into the pool. + * @param {PIXI.RenderTexture} renderTexture - The renderTexture to free */ - BaseTexture.prototype.setResolution = function setResolution (resolution) - { - var oldResolution = this.resolution; - - if (oldResolution === resolution) - { - return this; - } - - this.resolution = resolution; - - if (this.valid) - { - this.width = this.width * oldResolution / resolution; - this.height = this.height * oldResolution / resolution; - this.emit('update', this); - } - - this._refreshPOT(); - - return this; + RenderTexturePool.prototype.returnTexture = function (renderTexture) { + var key = renderTexture.filterPoolKey; + renderTexture.filterFrame = null; + this.texturePool[key].push(renderTexture); }; - /** - * Sets the resource if it wasn't set. Throws error if resource already present + * Alias for returnTexture, to be compliant with FilterSystem interface + * @param {PIXI.RenderTexture} renderTexture - The renderTexture to free + */ + RenderTexturePool.prototype.returnFilterTexture = function (renderTexture) { + this.returnTexture(renderTexture); + }; + /** + * Clears the pool * - * @param {PIXI.resources.Resource} resource - that is managing this BaseTexture - * @returns {PIXI.BaseTexture} this + * @param {boolean} [destroyTextures=true] - destroy all stored textures */ - BaseTexture.prototype.setResource = function setResource (resource) - { - if (this.resource === resource) - { - return this; - } - - if (this.resource) - { - throw new Error('Resource can be set only once'); + RenderTexturePool.prototype.clear = function (destroyTextures) { + destroyTextures = destroyTextures !== false; + if (destroyTextures) { + for (var i in this.texturePool) { + var textures = this.texturePool[i]; + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } } - - resource.bind(this); - - this.resource = resource; - - return this; + this.texturePool = {}; }; - /** - * Invalidates the object. Texture becomes valid if width and height are greater than zero. + * If screen size was changed, drops all screen-sized textures, + * sets new screen size, sets `enableFullScreen` to true + * + * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen` + * + * @param {PIXI.ISize} size - Initial size of screen */ - BaseTexture.prototype.update = function update () - { - if (!this.valid) - { - if (this.width > 0 && this.height > 0) - { - this.valid = true; - this.emit('loaded', this); - this.emit('update', this); - } + RenderTexturePool.prototype.setScreenSize = function (size) { + if (size.width === this._pixelsWidth + && size.height === this._pixelsHeight) { + return; } - else - { - this.dirtyId++; - this.dirtyStyleId++; - this.emit('update', this); + var screenKey = RenderTexturePool.SCREEN_KEY; + var textures = this.texturePool[screenKey]; + this.enableFullScreen = size.width > 0 && size.height > 0; + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } } + this.texturePool[screenKey] = []; + this._pixelsWidth = size.width; + this._pixelsHeight = size.height; }; - /** - * Handle errors with resources. - * @private - * @param {ErrorEvent} event - Error event emitted. + * Key that is used to store fullscreen renderTextures in a pool + * + * @static + * @const {string} */ - BaseTexture.prototype.onError = function onError (event) - { - this.emit('error', this, event); - }; + RenderTexturePool.SCREEN_KEY = 'screen'; + return RenderTexturePool; +}()); +/* eslint-disable max-len */ +/** + * Holds the information for a single attribute structure required to render geometry. + * + * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer} + * This can include anything from positions, uvs, normals, colors etc. + * + * @class + * @memberof PIXI + */ +var Attribute = /** @class */ (function () { /** - * Destroys this base texture. - * The method stops if resource doesn't want this texture to be destroyed. - * Removes texture from all caches. + * @param {string} buffer - the id of the buffer that this attribute will look for + * @param {Number} [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2. + * @param {Boolean} [normalized=false] - should the data be normalized. + * @param {Number} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available + * @param {Number} [stride=0] - How far apart (in floats) the start of each value is. (used for interleaving data) + * @param {Number} [start=0] - How far into the array to start reading values (used for interleaving data) */ - BaseTexture.prototype.destroy = function destroy () - { - // remove and destroy the resource - if (this.resource) - { - this.resource.unbind(this); - // only destroy resourced created internally - if (this.resource.internal) - { - this.resource.destroy(); - } - this.resource = null; - } - - if (this.cacheId) - { - delete utils.BaseTextureCache[this.cacheId]; - delete utils.TextureCache[this.cacheId]; - - this.cacheId = null; - } - - // finally let the WebGL renderer know.. - this.dispose(); - - BaseTexture.removeFromCache(this); - this.textureCacheIds = null; - - this.destroyed = true; - }; - + function Attribute(buffer, size, normalized, type, stride, start, instance) { + if (size === void 0) { size = 0; } + if (normalized === void 0) { normalized = false; } + if (type === void 0) { type = 5126; } + this.buffer = buffer; + this.size = size; + this.normalized = normalized; + this.type = type; + this.stride = stride; + this.start = start; + this.instance = instance; + } /** - * Frees the texture from WebGL memory without destroying this texture object. - * This means you can still use the texture later which will upload it to GPU - * memory again. - * - * @fires PIXI.BaseTexture#dispose + * Destroys the Attribute. */ - BaseTexture.prototype.dispose = function dispose () - { - this.emit('dispose', this); + Attribute.prototype.destroy = function () { + this.buffer = null; }; - /** - * Helper function that creates a base texture based on the source you provide. - * The source can be - image url, image element, canvas element. If the - * source is an image url or an image element and not in the base texture - * cache, it will be created and loaded. + * Helper function that creates an Attribute based on the information provided * * @static - * @param {string|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The - * source to create base texture from. - * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. - * @param {boolean} [strict] Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. - * @returns {PIXI.BaseTexture} The new base texture. + * @param {string} buffer - the id of the buffer that this attribute will look for + * @param {Number} [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 + * @param {Boolean} [normalized=false] - should the data be normalized. + * @param {Number} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available + * @param {Number} [stride=0] - How far apart (in floats) the start of each value is. (used for interleaving data) + * + * @returns {PIXI.Attribute} A new {@link PIXI.Attribute} based on the information provided */ - BaseTexture.from = function from (source, options, strict) - { - if ( strict === void 0 ) strict = settings.settings.STRICT_TEXTURE_CACHE; + Attribute.from = function (buffer, size, normalized, type, stride) { + return new Attribute(buffer, size, normalized, type, stride); + }; + return Attribute; +}()); - var isFrame = typeof source === 'string'; - var cacheId = null; - - if (isFrame) - { - cacheId = source; - } - else - { - if (!source._pixiId) - { - source._pixiId = "pixiid_" + (utils.uid()); - } - - cacheId = source._pixiId; - } - - var baseTexture = utils.BaseTextureCache[cacheId]; - - // Strict-mode rejects invalid cacheIds - if (isFrame && strict && !baseTexture) - { - throw new Error(("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache.")); - } - - if (!baseTexture) - { - baseTexture = new BaseTexture(source, options); - baseTexture.cacheId = cacheId; - BaseTexture.addToCache(baseTexture, cacheId); - } - - return baseTexture; +var UID = 0; +/** + * A wrapper for data so that it can be used and uploaded by WebGL + * + * @class + * @memberof PIXI + */ +var Buffer = /** @class */ (function () { + /** + * @param {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} data - the data to store in the buffer. + * @param {boolean} [_static=true] - `true` for static buffer + * @param {boolean} [index=false] - `true` for index buffer + */ + function Buffer(data, _static, index) { + if (_static === void 0) { _static = true; } + if (index === void 0) { index = false; } + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer | ArrayBufferView} + */ + this.data = (data || new Float32Array(1)); + /** + * A map of renderer IDs to webgl buffer + * + * @private + * @member {object} + */ + this._glBuffers = {}; + this._updateID = 0; + this.index = index; + this.static = _static; + this.id = UID++; + this.disposeRunner = new runner.Runner('disposeBuffer'); + } + // TODO could explore flagging only a partial upload? + /** + * flags this buffer as requiring an upload to the GPU + * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView} [data] - the data to update in the buffer. + */ + Buffer.prototype.update = function (data) { + this.data = data || this.data; + this._updateID++; }; - /** - * Create a new BaseTexture with a BufferResource from a Float32Array. - * RGBA values are floats from 0 to 1. - * @static - * @param {Float32Array|Uint8Array} buffer The optional array to use, if no data - * is provided, a new Float32Array is created. - * @param {number} width - Width of the resource - * @param {number} height - Height of the resource - * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. - * @return {PIXI.BaseTexture} The resulting new BaseTexture + * disposes WebGL resources that are connected to this geometry */ - BaseTexture.fromBuffer = function fromBuffer (buffer, width, height, options) - { - buffer = buffer || new Float32Array(width * height * 4); - - var resource = new BufferResource(buffer, { width: width, height: height }); - var type = buffer instanceof Float32Array ? constants.TYPES.FLOAT : constants.TYPES.UNSIGNED_BYTE; - - return new BaseTexture(resource, Object.assign(defaultBufferOptions, options || { width: width, height: height, type: type })); + Buffer.prototype.dispose = function () { + this.disposeRunner.emit(this, false); }; - /** - * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. - * - * @static - * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. - * @param {string} id - The id that the BaseTexture will be stored against. + * Destroys the buffer */ - BaseTexture.addToCache = function addToCache (baseTexture, id) - { - if (id) - { - if (baseTexture.textureCacheIds.indexOf(id) === -1) - { - baseTexture.textureCacheIds.push(id); - } - - if (utils.BaseTextureCache[id]) - { - // eslint-disable-next-line no-console - console.warn(("BaseTexture added to the cache with an id [" + id + "] that already had an entry")); - } - - utils.BaseTextureCache[id] = baseTexture; - } + Buffer.prototype.destroy = function () { + this.dispose(); + this.data = null; }; - /** - * Remove a BaseTexture from the global BaseTextureCache. + * Helper function that creates a buffer based on an array or TypedArray * * @static - * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. - * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. + * @param {ArrayBufferView | number[]} data - the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array. + * @return {PIXI.Buffer} A new Buffer based on the data provided. */ - BaseTexture.removeFromCache = function removeFromCache (baseTexture) - { - if (typeof baseTexture === 'string') - { - var baseTextureFromCache = utils.BaseTextureCache[baseTexture]; - - if (baseTextureFromCache) - { - var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); - - if (index > -1) - { - baseTextureFromCache.textureCacheIds.splice(index, 1); - } - - delete utils.BaseTextureCache[baseTexture]; - - return baseTextureFromCache; - } - } - else if (baseTexture && baseTexture.textureCacheIds) - { - for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) - { - delete utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; - } - - baseTexture.textureCacheIds.length = 0; - - return baseTexture; + Buffer.from = function (data) { + if (data instanceof Array) { + data = new Float32Array(data); } - - return null; + return new Buffer(data); }; + return Buffer; +}()); - Object.defineProperties( BaseTexture.prototype, prototypeAccessors ); +function getBufferType(array) { + if (array.BYTES_PER_ELEMENT === 4) { + if (array instanceof Float32Array) { + return 'Float32Array'; + } + else if (array instanceof Uint32Array) { + return 'Uint32Array'; + } + return 'Int32Array'; + } + else if (array.BYTES_PER_ELEMENT === 2) { + if (array instanceof Uint16Array) { + return 'Uint16Array'; + } + } + else if (array.BYTES_PER_ELEMENT === 1) { + if (array instanceof Uint8Array) { + return 'Uint8Array'; + } + } + // TODO map out the rest of the array elements! + return null; +} - return BaseTexture; -}(utils.EventEmitter)); +/* eslint-disable object-shorthand */ +var map = { + Float32Array: Float32Array, + Uint32Array: Uint32Array, + Int32Array: Int32Array, + Uint8Array: Uint8Array, +}; +function interleaveTypedArrays(arrays, sizes) { + var outSize = 0; + var stride = 0; + var views = {}; + for (var i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + var buffer = new ArrayBuffer(outSize * 4); + var out = null; + var littleOffset = 0; + for (var i = 0; i < arrays.length; i++) { + var size = sizes[i]; + var array = arrays[i]; + var type = getBufferType(array); + if (!views[type]) { + views[type] = new map[type](buffer); + } + out = views[type]; + for (var j = 0; j < array.length; j++) { + var indexStart = ((j / size | 0) * stride) + littleOffset; + var index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); +} +var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +var UID$1 = 0; +/* eslint-disable object-shorthand */ +var map$1 = { + Float32Array: Float32Array, + Uint32Array: Uint32Array, + Int32Array: Int32Array, + Uint8Array: Uint8Array, + Uint16Array: Uint16Array, +}; +/* eslint-disable max-len */ /** - * Global number of the texture batch, used by multi-texture renderers + * The Geometry represents a model. It consists of two components: + * - GeometryStyle - The structure of the model such as the attributes layout + * - GeometryData - the data of the model - this consists of buffers. + * This can include anything from positions, uvs, normals, colors etc. * - * @static - * @member {number} - */ -BaseTexture._globalBatch = 0; - -/** - * A resource that contains a number of sources. + * Geometry can be defined without passing in a style or data if required (thats how I prefer!) + * + * ```js + * let geometry = new PIXI.Geometry(); + * + * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); + * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2) + * geometry.addIndex([0,1,2,1,3,2]) * + * ``` * @class - * @extends PIXI.resources.Resource - * @memberof PIXI.resources - * @param {number|Array<*>} source - Number of items in array or the collection - * of image URLs to use. Can also be resources, image elements, canvas, etc. - * @param {object} [options] Options to apply to {@link PIXI.resources.autoDetectResource} - * @param {number} [options.width] - Width of the resource - * @param {number} [options.height] - Height of the resource + * @memberof PIXI */ -var ArrayResource = /*@__PURE__*/(function (Resource) { - function ArrayResource(source, options) - { - options = options || {}; - - var urls; - var length = source; - - if (Array.isArray(source)) - { - urls = source; - length = source.length; - } - - Resource.call(this, options.width, options.height); - - /** - * Collection of resources. - * @member {Array} - * @readonly - */ - this.items = []; - +var Geometry = /** @class */ (function () { + /** + * @param {PIXI.Buffer[]} [buffers] - an array of buffers. optional. + * @param {object} [attributes] - of the geometry, optional structure of the attributes layout + */ + function Geometry(buffers, attributes) { + if (buffers === void 0) { buffers = []; } + if (attributes === void 0) { attributes = {}; } + this.buffers = buffers; + this.indexBuffer = null; + this.attributes = attributes; /** - * Dirty IDs for each part - * @member {Array} - * @readonly + * A map of renderer IDs to webgl VAOs + * + * @protected + * @type {object} */ - this.itemDirtyIds = []; - - for (var i = 0; i < length; i++) - { - var partTexture = new BaseTexture(); - - this.items.push(partTexture); - this.itemDirtyIds.push(-1); - } - + this.glVertexArrayObjects = {}; + this.id = UID$1++; + this.instanced = false; /** - * Number of elements in array - * + * Number of instances in this geometry, pass it to `GeometrySystem.draw()` * @member {number} - * @readonly + * @default 1 */ - this.length = length; - + this.instanceCount = 1; + this.disposeRunner = new runner.Runner('disposeGeometry'); /** - * Promise when loading - * @member {Promise} - * @private - * @default null + * Count of existing (not destroyed) meshes that reference this geometry + * @member {number} */ - this._load = null; - - if (urls) - { - for (var i$1 = 0; i$1 < length; i$1++) - { - this.addResourceAt(autoDetectResource(urls[i$1], options), i$1); + this.refCount = 0; + } + /** + * + * Adds an attribute to the geometry + * Note: `stride` and `start` should be `undefined` if you dont know them, not 0! + * + * @param {String} id - the name of the attribute (matching up to a shader) + * @param {PIXI.Buffer|number[]} [buffer] - the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it. + * @param {Number} [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 + * @param {Boolean} [normalized=false] - should the data be normalized. + * @param {Number} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {PIXI.TYPES} to see the ones available + * @param {Number} [stride] - How far apart (in floats) the start of each value is. (used for interleaving data) + * @param {Number} [start] - How far into the array to start reading values (used for interleaving data) + * @param {boolean} [instance=false] - Instancing flag + * + * @return {PIXI.Geometry} returns self, useful for chaining. + */ + Geometry.prototype.addAttribute = function (id, buffer, size, normalized, type, stride, start, instance) { + if (size === void 0) { size = 0; } + if (normalized === void 0) { normalized = false; } + if (instance === void 0) { instance = false; } + if (!buffer) { + throw new Error('You must pass a buffer when creating an attribute'); + } + // check if this is a buffer! + if (!(buffer instanceof Buffer)) { + // its an array! + if (buffer instanceof Array) { + buffer = new Float32Array(buffer); + } + buffer = new Buffer(buffer); + } + var ids = id.split('|'); + if (ids.length > 1) { + for (var i = 0; i < ids.length; i++) { + this.addAttribute(ids[i], buffer, size, normalized, type); } + return this; } - } - - if ( Resource ) ArrayResource.__proto__ = Resource; - ArrayResource.prototype = Object.create( Resource && Resource.prototype ); - ArrayResource.prototype.constructor = ArrayResource; - + var bufferIndex = this.buffers.indexOf(buffer); + if (bufferIndex === -1) { + this.buffers.push(buffer); + bufferIndex = this.buffers.length - 1; + } + this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance); + // assuming that if there is instanced data then this will be drawn with instancing! + this.instanced = this.instanced || instance; + return this; + }; /** - * Destroy this BaseImageResource - * @override + * returns the requested attribute + * + * @param {String} id - the name of the attribute required + * @return {PIXI.Attribute} the attribute requested. */ - ArrayResource.prototype.dispose = function dispose () - { - for (var i = 0, len = this.length; i < len; i++) - { - this.items[i].destroy(); - } - this.items = null; - this.itemDirtyIds = null; - this._load = null; + Geometry.prototype.getAttribute = function (id) { + return this.attributes[id]; }; - /** - * Set a resource by ID + * returns the requested buffer * - * @param {PIXI.resources.Resource} resource - * @param {number} index - Zero-based index of resource to set - * @return {PIXI.resources.ArrayResource} Instance for chaining + * @param {String} id - the name of the buffer required + * @return {PIXI.Buffer} the buffer requested. */ - ArrayResource.prototype.addResourceAt = function addResourceAt (resource, index) - { - var baseTexture = this.items[index]; - - if (!baseTexture) - { - throw new Error(("Index " + index + " is out of bounds")); + Geometry.prototype.getBuffer = function (id) { + return this.buffers[this.getAttribute(id).buffer]; + }; + /** + * + * Adds an index buffer to the geometry + * The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer. + * + * @param {PIXI.Buffer|number[]} [buffer] - the buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it. + * @return {PIXI.Geometry} returns self, useful for chaining. + */ + Geometry.prototype.addIndex = function (buffer) { + if (!(buffer instanceof Buffer)) { + // its an array! + if (buffer instanceof Array) { + buffer = new Uint16Array(buffer); + } + buffer = new Buffer(buffer); } - - // Inherit the first resource dimensions - if (resource.valid && !this.valid) - { - this.resize(resource.width, resource.height); + buffer.index = true; + this.indexBuffer = buffer; + if (this.buffers.indexOf(buffer) === -1) { + this.buffers.push(buffer); } - - this.items[index].setResource(resource); - return this; }; - /** - * Set the parent base texture - * @member {PIXI.BaseTexture} - * @override + * returns the index buffer + * + * @return {PIXI.Buffer} the index buffer. */ - ArrayResource.prototype.bind = function bind (baseTexture) - { - Resource.prototype.bind.call(this, baseTexture); - - baseTexture.target = constants.TARGETS.TEXTURE_2D_ARRAY; - - for (var i = 0; i < this.length; i++) - { - this.items[i].on('update', baseTexture.update, baseTexture); - } + Geometry.prototype.getIndex = function () { + return this.indexBuffer; }; - /** - * Unset the parent base texture - * @member {PIXI.BaseTexture} - * @override + * this function modifies the structure so that all current attributes become interleaved into a single buffer + * This can be useful if your model remains static as it offers a little performance boost + * + * @return {PIXI.Geometry} returns self, useful for chaining. */ - ArrayResource.prototype.unbind = function unbind (baseTexture) - { - Resource.prototype.unbind.call(this, baseTexture); - - for (var i = 0; i < this.length; i++) - { - this.items[i].off('update', baseTexture.update, baseTexture); + Geometry.prototype.interleave = function () { + // a simple check to see if buffers are already interleaved.. + if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer)) + { return this; } + // assume already that no buffers are interleaved + var arrays = []; + var sizes = []; + var interleavedBuffer = new Buffer(); + var i; + for (i in this.attributes) { + var attribute = this.attributes[i]; + var buffer = this.buffers[attribute.buffer]; + arrays.push(buffer.data); + sizes.push((attribute.size * byteSizeMap[attribute.type]) / 4); + attribute.buffer = 0; + } + interleavedBuffer.data = interleaveTypedArrays(arrays, sizes); + for (i = 0; i < this.buffers.length; i++) { + if (this.buffers[i] !== this.indexBuffer) { + this.buffers[i].destroy(); + } + } + this.buffers = [interleavedBuffer]; + if (this.indexBuffer) { + this.buffers.push(this.indexBuffer); } + return this; + }; + Geometry.prototype.getSize = function () { + for (var i in this.attributes) { + var attribute = this.attributes[i]; + var buffer = this.buffers[attribute.buffer]; + return buffer.data.length / ((attribute.stride / 4) || attribute.size); + } + return 0; }; - /** - * Load all the resources simultaneously - * @override - * @return {Promise} When load is resolved + * disposes WebGL resources that are connected to this geometry */ - ArrayResource.prototype.load = function load () - { - var this$1 = this; - - if (this._load) - { - return this._load; - } - - var resources = this.items.map(function (item) { return item.resource; }); - - // TODO: also implement load part-by-part strategy - var promises = resources.map(function (item) { return item.load(); }); - - this._load = Promise.all(promises) - .then(function () { - var ref = resources[0]; - var width = ref.width; - var height = ref.height; - - this$1.resize(width, height); - - return Promise.resolve(this$1); - } - ); - - return this._load; + Geometry.prototype.dispose = function () { + this.disposeRunner.emit(this, false); }; - /** - * Upload the resources to the GPU. - * @param {PIXI.Renderer} renderer - * @param {PIXI.BaseTexture} texture - * @param {PIXI.GLTexture} glTexture - * @returns {boolean} whether texture was uploaded + * Destroys the geometry. */ - ArrayResource.prototype.upload = function upload (renderer, texture, glTexture) - { - var ref = this; - var length = ref.length; - var itemDirtyIds = ref.itemDirtyIds; - var items = ref.items; - var gl = renderer.gl; - - if (glTexture.dirtyId < 0) - { - gl.texImage3D( - gl.TEXTURE_2D_ARRAY, - 0, - texture.format, - this._width, - this._height, - length, - 0, - texture.format, - texture.type, - null - ); - } - - for (var i = 0; i < length; i++) - { - var item = items[i]; - - if (itemDirtyIds[i] < item.dirtyId) - { - itemDirtyIds[i] = item.dirtyId; - if (item.valid) - { - gl.texSubImage3D( - gl.TEXTURE_2D_ARRAY, - 0, - 0, // xoffset - 0, // yoffset - i, // zoffset - item.resource.width, - item.resource.height, - 1, - texture.format, - texture.type, - item.resource.source - ); + Geometry.prototype.destroy = function () { + this.dispose(); + this.buffers = null; + this.indexBuffer = null; + this.attributes = null; + }; + /** + * returns a clone of the geometry + * + * @returns {PIXI.Geometry} a new clone of this geometry + */ + Geometry.prototype.clone = function () { + var geometry = new Geometry(); + for (var i = 0; i < this.buffers.length; i++) { + geometry.buffers[i] = new Buffer(this.buffers[i].data.slice(0)); + } + for (var i in this.attributes) { + var attrib = this.attributes[i]; + geometry.attributes[i] = new Attribute(attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance); + } + if (this.indexBuffer) { + geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)]; + geometry.indexBuffer.index = true; + } + return geometry; + }; + /** + * merges an array of geometries into a new single one + * geometry attribute styles must match for this operation to work + * + * @param {PIXI.Geometry[]} geometries - array of geometries to merge + * @returns {PIXI.Geometry} shiny new geometry! + */ + Geometry.merge = function (geometries) { + // todo add a geometry check! + // also a size check.. cant be too big!] + var geometryOut = new Geometry(); + var arrays = []; + var sizes = []; + var offsets = []; + var geometry; + // pass one.. get sizes.. + for (var i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (var j = 0; j < geometry.buffers.length; j++) { + sizes[j] = sizes[j] || 0; + sizes[j] += geometry.buffers[j].data.length; + offsets[j] = 0; + } + } + // build the correct size arrays.. + for (var i = 0; i < geometry.buffers.length; i++) { + // TODO types! + arrays[i] = new map$1[getBufferType(geometry.buffers[i].data)](sizes[i]); + geometryOut.buffers[i] = new Buffer(arrays[i]); + } + // pass to set data.. + for (var i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (var j = 0; j < geometry.buffers.length; j++) { + arrays[j].set(geometry.buffers[j].data, offsets[j]); + offsets[j] += geometry.buffers[j].data.length; + } + } + geometryOut.attributes = geometry.attributes; + if (geometry.indexBuffer) { + geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)]; + geometryOut.indexBuffer.index = true; + var offset = 0; + var stride = 0; + var offset2 = 0; + var bufferIndexToCount = 0; + // get a buffer + for (var i = 0; i < geometry.buffers.length; i++) { + if (geometry.buffers[i] !== geometry.indexBuffer) { + bufferIndexToCount = i; + break; } } + // figure out the stride of one buffer.. + for (var i in geometry.attributes) { + var attribute = geometry.attributes[i]; + if ((attribute.buffer | 0) === bufferIndexToCount) { + stride += ((attribute.size * byteSizeMap[attribute.type]) / 4); + } + } + // time to off set all indexes.. + for (var i = 0; i < geometries.length; i++) { + var indexBufferData = geometries[i].indexBuffer.data; + for (var j = 0; j < indexBufferData.length; j++) { + geometryOut.indexBuffer.data[j + offset2] += offset; + } + offset += geometry.buffers[bufferIndexToCount].data.length / (stride); + offset2 += indexBufferData.length; + } } - - return true; + return geometryOut; }; - - return ArrayResource; -}(Resource)); - -/** - * @interface OffscreenCanvas - */ + return Geometry; +}()); /** - * Resource type for HTMLCanvasElement. + * Helper class to create a quad + * * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - * @param {HTMLCanvasElement} source - Canvas element to use + * @memberof PIXI */ -var CanvasResource = /*@__PURE__*/(function (BaseImageResource) { - function CanvasResource () { - BaseImageResource.apply(this, arguments); +var Quad = /** @class */ (function (_super) { + __extends(Quad, _super); + function Quad() { + var _this = _super.call(this) || this; + _this.addAttribute('aVertexPosition', new Float32Array([ + 0, 0, + 1, 0, + 1, 1, + 0, 1 ])) + .addIndex([0, 1, 3, 2]); + return _this; } - - if ( BaseImageResource ) CanvasResource.__proto__ = BaseImageResource; - CanvasResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); - CanvasResource.prototype.constructor = CanvasResource; - - CanvasResource.test = function test (source) - { - var OffscreenCanvas = window.OffscreenCanvas; - - // Check for browsers that don't yet support OffscreenCanvas - if (OffscreenCanvas && source instanceof OffscreenCanvas) - { - return true; - } - - return source instanceof HTMLCanvasElement; - }; - - return CanvasResource; -}(BaseImageResource)); + return Quad; +}(Geometry)); /** - * Resource for a CubeTexture which contains six resources. + * Helper class to create a quad with uvs like in v4 * * @class - * @extends PIXI.resources.ArrayResource - * @memberof PIXI.resources - * @param {Array} [source] Collection of URLs or resources - * to use as the sides of the cube. - * @param {object} [options] - ImageResource options - * @param {number} [options.width] - Width of resource - * @param {number} [options.height] - Height of resource + * @memberof PIXI + * @extends PIXI.Geometry */ -var CubeResource = /*@__PURE__*/(function (ArrayResource) { - function CubeResource(source, options) - { - options = options || {}; - - ArrayResource.call(this, source, options); - - if (this.length !== CubeResource.SIDES) - { - throw new Error(("Invalid length. Got " + (this.length) + ", expected 6")); - } - - for (var i = 0; i < CubeResource.SIDES; i++) - { - this.items[i].target = constants.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i; - } - - if (options.autoLoad !== false) - { - this.load(); - } +var QuadUv = /** @class */ (function (_super) { + __extends(QuadUv, _super); + function QuadUv() { + var _this = _super.call(this) || this; + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = new Float32Array([ + -1, -1, + 1, -1, + 1, 1, + -1, 1 ]); + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + _this.uvs = new Float32Array([ + 0, 0, + 1, 0, + 1, 1, + 0, 1 ]); + _this.vertexBuffer = new Buffer(_this.vertices); + _this.uvBuffer = new Buffer(_this.uvs); + _this.addAttribute('aVertexPosition', _this.vertexBuffer) + .addAttribute('aTextureCoord', _this.uvBuffer) + .addIndex([0, 1, 2, 0, 2, 3]); + return _this; } - - if ( ArrayResource ) CubeResource.__proto__ = ArrayResource; - CubeResource.prototype = Object.create( ArrayResource && ArrayResource.prototype ); - CubeResource.prototype.constructor = CubeResource; - /** - * Add binding + * Maps two Rectangle to the quad. * - * @override - * @param {PIXI.BaseTexture} baseTexture - parent base texture + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. */ - CubeResource.prototype.bind = function bind (baseTexture) - { - ArrayResource.prototype.bind.call(this, baseTexture); - - baseTexture.target = constants.TARGETS.TEXTURE_CUBE_MAP; + QuadUv.prototype.map = function (targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + this.uvs[0] = x; + this.uvs[1] = y; + this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width); + this.uvs[3] = y; + this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width); + this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height); + this.uvs[6] = x; + this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height); + x = destinationFrame.x; + y = destinationFrame.y; + this.vertices[0] = x; + this.vertices[1] = y; + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + this.invalidate(); + return this; }; - /** - * Upload the resource - * - * @returns {boolean} true is success + * legacy upload method, just marks buffers dirty + * @returns {PIXI.QuadUv} Returns itself. */ - CubeResource.prototype.upload = function upload (renderer, baseTexture, glTexture) - { - var dirty = this.itemDirtyIds; - - for (var i = 0; i < CubeResource.SIDES; i++) - { - var side = this.items[i]; - - if (dirty[i] < side.dirtyId) - { - dirty[i] = side.dirtyId; - if (side.valid) - { - side.resource.upload(renderer, side, glTexture); - } - } - } - - return true; + QuadUv.prototype.invalidate = function () { + this.vertexBuffer._updateID++; + this.uvBuffer._updateID++; + return this; }; + return QuadUv; +}(Geometry)); - return CubeResource; -}(ArrayResource)); - +var UID$2 = 0; /** - * Number of texture sides to store for CubeResources + * Uniform group holds uniform map and some ID's for work * - * @name PIXI.resources.CubeResource.SIDES - * @static - * @member {number} - * @default 6 - */ -CubeResource.SIDES = 6; - -/** - * Resource type for SVG elements and graphics. * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - * @param {string} source - Base64 encoded SVG element or URL for SVG file. - * @param {object} [options] - Options to use - * @param {number} [options.scale=1] Scale to apply to SVG. Overridden by... - * @param {number} [options.width] Rasterize SVG this wide. Aspect ratio preserved if height not specified. - * @param {number} [options.height] Rasterize SVG this high. Aspect ratio preserved if width not specified. - * @param {boolean} [options.autoLoad=true] Start loading right away. + * @memberof PIXI */ -var SVGResource = /*@__PURE__*/(function (BaseImageResource) { - function SVGResource(source, options) - { - options = options || {}; - - BaseImageResource.call(this, document.createElement('canvas')); - this._width = 0; - this._height = 0; - +var UniformGroup = /** @class */ (function () { + /** + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + * @param {boolean} [_static] - Uniforms wont be changed after creation + */ + function UniformGroup(uniforms, _static) { /** - * Base64 encoded SVG element or URL for SVG file + * uniform values + * @member {object} * @readonly - * @member {string} */ - this.svg = source; - + this.uniforms = uniforms; /** - * The source scale to apply when rasterizing on load + * Its a group and not a single uniforms + * @member {boolean} * @readonly + * @default true + */ + this.group = true; + // lets generate this when the shader ? + this.syncUniforms = {}; + /** + * dirty version + * @protected * @member {number} */ - this.scale = options.scale || 1; - + this.dirtyId = 0; /** - * A width override for rasterization on load - * @readonly + * unique id + * @protected * @member {number} */ - this._overrideWidth = options.width; + this.id = UID$2++; + /** + * Uniforms wont be changed after creation + * @member {boolean} + */ + this.static = !!_static; + } + UniformGroup.prototype.update = function () { + this.dirtyId++; + }; + UniformGroup.prototype.add = function (name, uniforms, _static) { + this.uniforms[name] = new UniformGroup(uniforms, _static); + }; + UniformGroup.from = function (uniforms, _static) { + return new UniformGroup(uniforms, _static); + }; + return UniformGroup; +}()); +/** + * System plugin to the renderer to manage filter states. + * + * @class + * @private + */ +var FilterState = /** @class */ (function () { + function FilterState() { + this.renderTexture = null; /** - * A height override for rasterization on load - * @readonly + * Target of the filters + * We store for case when custom filter wants to know the element it was applied on + * @member {PIXI.DisplayObject} + * @private + */ + this.target = null; + /** + * Compatibility with PixiJS v4 filters + * @member {boolean} + * @default false + * @private + */ + this.legacy = false; + /** + * Resolution of filters * @member {number} + * @default 1 + * @private */ - this._overrideHeight = options.height; - + this.resolution = 1; + // next three fields are created only for root + // re-assigned for everything else /** - * Call when completely loaded + * Source frame + * @member {PIXI.Rectangle} * @private - * @member {function} */ - this._resolve = null; - + this.sourceFrame = new math.Rectangle(); /** - * Cross origin value to use + * Destination frame + * @member {PIXI.Rectangle} * @private - * @member {boolean|string} */ - this._crossorigin = options.crossorigin; - + this.destinationFrame = new math.Rectangle(); /** - * Promise when loading - * @member {Promise} + * Collection of filters + * @member {PIXI.Filter[]} * @private - * @default null */ - this._load = null; - - if (options.autoLoad !== false) - { - this.load(); - } + this.filters = []; } - - if ( BaseImageResource ) SVGResource.__proto__ = BaseImageResource; - SVGResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); - SVGResource.prototype.constructor = SVGResource; - - SVGResource.prototype.load = function load () - { - var this$1 = this; - - if (this._load) - { - return this._load; - } - - this._load = new Promise(function (resolve) { - // Save this until after load is finished - this$1._resolve = function () { - this$1.resize(this$1.source.width, this$1.source.height); - resolve(this$1); - }; - - // Convert SVG inline string to data-uri - if ((/^\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len - -/** - * Resource type for HTMLVideoElement. * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - * @param {HTMLVideoElement|object|string|Array} source - Video element to use. - * @param {object} [options] - Options to use - * @param {boolean} [options.autoLoad=true] - Start loading the video immediately - * @param {boolean} [options.autoPlay=true] - Start playing video immediately - * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video. - * Leave at 0 to update at every render. - * @param {boolean} [options.crossorigin=true] - Load image using cross origin + * @memberof PIXI.systems + * @extends PIXI.System */ -var VideoResource = /*@__PURE__*/(function (BaseImageResource) { - function VideoResource(source, options) - { - options = options || {}; - - if (!(source instanceof HTMLVideoElement)) - { - var videoElement = document.createElement('video'); - - // workaround for https://github.com/pixijs/pixi.js/issues/5996 - videoElement.setAttribute('preload', 'auto'); - videoElement.setAttribute('webkit-playsinline', ''); - videoElement.setAttribute('playsinline', ''); - - if (typeof source === 'string') - { - source = [source]; - } - - BaseImageResource.crossOrigin(videoElement, (source[0].src || source[0]), options.crossorigin); - - // array of objects or strings - for (var i = 0; i < source.length; ++i) - { - var sourceElement = document.createElement('source'); - - var ref = source[i]; - var src = ref.src; - var mime = ref.mime; - - src = src || source[i]; - - var baseSrc = src.split('?').shift().toLowerCase(); - var ext = baseSrc.substr(baseSrc.lastIndexOf('.') + 1); - - mime = mime || ("video/" + ext); - - sourceElement.src = src; - sourceElement.type = mime; - - videoElement.appendChild(sourceElement); - } - - // Override the source - source = videoElement; - } - - BaseImageResource.call(this, source); - - this.noSubImage = true; - this._autoUpdate = true; - this._isAutoUpdating = false; - this._updateFPS = options.updateFPS || 0; - this._msToNextUpdate = 0; - +var FilterSystem = /** @class */ (function (_super) { + __extends(FilterSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function FilterSystem(renderer) { + var _this = _super.call(this, renderer) || this; /** - * When set to true will automatically play videos used by this texture once - * they are loaded. If false, it will not modify the playing state. - * - * @member {boolean} - * @default true + * List of filters for the FilterSystem + * @member {Object[]} + * @readonly */ - this.autoPlay = options.autoPlay !== false; - + _this.defaultFilterStack = [{}]; /** - * Promise when loading - * @member {Promise} - * @private - * @default null + * stores a bunch of PO2 textures used for filtering + * @member {Object} */ - this._load = null; - + _this.texturePool = new RenderTexturePool(); + _this.texturePool.setScreenSize(renderer.view); /** - * Callback when completed with load. - * @member {function} - * @private + * a pool for storing filter states, save us creating new ones each tick + * @member {Object[]} */ - this._resolve = null; - - // Bind for listeners - this._onCanPlay = this._onCanPlay.bind(this); - this._onError = this._onError.bind(this); - - if (options.autoLoad !== false) - { - this.load(); - } + _this.statePool = []; + /** + * A very simple geometry used when drawing a filter effect to the screen + * @member {PIXI.Quad} + */ + _this.quad = new Quad(); + /** + * Quad UVs + * @member {PIXI.QuadUv} + */ + _this.quadUv = new QuadUv(); + /** + * Temporary rect for maths + * @type {PIXI.Rectangle} + */ + _this.tempRect = new math.Rectangle(); + /** + * Active state + * @member {object} + */ + _this.activeState = {}; + /** + * This uniform group is attached to filter uniforms when used + * @member {PIXI.UniformGroup} + * @property {PIXI.Rectangle} outputFrame + * @property {Float32Array} inputSize + * @property {Float32Array} inputPixel + * @property {Float32Array} inputClamp + * @property {Number} resolution + * @property {Float32Array} filterArea + * @property {Fload32Array} filterClamp + */ + _this.globalUniforms = new UniformGroup({ + outputFrame: _this.tempRect, + inputSize: new Float32Array(4), + inputPixel: new Float32Array(4), + inputClamp: new Float32Array(4), + resolution: 1, + // legacy variables + filterArea: new Float32Array(4), + filterClamp: new Float32Array(4), + }, true); + /** + * Whether to clear output renderTexture in AUTO/BLIT mode. See {@link PIXI.CLEAR_MODES} + * @member {boolean} + */ + _this.forceClear = false; + /** + * Old padding behavior is to use the max amount instead of sum padding. + * Use this flag if you need the old behavior. + * @member {boolean} + * @default false + */ + _this.useMaxPadding = false; + return _this; } - - if ( BaseImageResource ) VideoResource.__proto__ = BaseImageResource; - VideoResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); - VideoResource.prototype.constructor = VideoResource; - - var prototypeAccessors = { autoUpdate: { configurable: true },updateFPS: { configurable: true } }; - /** - * Trigger updating of the texture + * Adds a new filter to the System. * - * @param {number} [deltaTime=0] - time delta since last tick + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. */ - VideoResource.prototype.update = function update (deltaTime) - { - if ( deltaTime === void 0 ) deltaTime = 0; - - if (!this.destroyed) - { - // account for if video has had its playbackRate changed - var elapsedMS = ticker.Ticker.shared.elapsedMS * this.source.playbackRate; - - this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS); - if (!this._updateFPS || this._msToNextUpdate <= 0) - { - BaseImageResource.prototype.update.call(this, deltaTime); - this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0; - } + FilterSystem.prototype.push = function (target, filters) { + var renderer = this.renderer; + var filterStack = this.defaultFilterStack; + var state = this.statePool.pop() || new FilterState(); + var resolution = filters[0].resolution; + var padding = filters[0].padding; + var autoFit = filters[0].autoFit; + var legacy = filters[0].legacy; + for (var i = 1; i < filters.length; i++) { + var filter = filters[i]; + // lets use the lowest resolution.. + resolution = Math.min(resolution, filter.resolution); + // figure out the padding required for filters + padding = this.useMaxPadding + // old behavior: use largest amount of padding! + ? Math.max(padding, filter.padding) + // new behavior: sum the padding + : padding + filter.padding; + // only auto fit if all filters are autofit + autoFit = autoFit || filter.autoFit; + legacy = legacy || filter.legacy; } + if (filterStack.length === 1) { + this.defaultFilterStack[0].renderTexture = renderer.renderTexture.current; + } + filterStack.push(state); + state.resolution = resolution; + state.legacy = legacy; + state.target = target; + state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true)); + state.sourceFrame.pad(padding); + if (autoFit) { + state.sourceFrame.fit(this.renderer.renderTexture.sourceFrame); + } + // round to whole number based on resolution + state.sourceFrame.ceil(resolution); + state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution); + state.filters = filters; + state.destinationFrame.width = state.renderTexture.width; + state.destinationFrame.height = state.renderTexture.height; + var destinationFrame = this.tempRect; + destinationFrame.width = state.sourceFrame.width; + destinationFrame.height = state.sourceFrame.height; + state.renderTexture.filterFrame = state.sourceFrame; + renderer.renderTexture.bind(state.renderTexture, state.sourceFrame, destinationFrame); + renderer.renderTexture.clear(); }; - /** - * Start preloading the video resource. + * Pops off the filter and applies it. * - * @protected - * @return {Promise} Handle the validate event */ - VideoResource.prototype.load = function load () - { - var this$1 = this; - - if (this._load) - { - return this._load; - } - - var source = this.source; - - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) - && source.width && source.height) - { - source.complete = true; + FilterSystem.prototype.pop = function () { + var filterStack = this.defaultFilterStack; + var state = filterStack.pop(); + var filters = state.filters; + this.activeState = state; + var globalUniforms = this.globalUniforms.uniforms; + globalUniforms.outputFrame = state.sourceFrame; + globalUniforms.resolution = state.resolution; + var inputSize = globalUniforms.inputSize; + var inputPixel = globalUniforms.inputPixel; + var inputClamp = globalUniforms.inputClamp; + inputSize[0] = state.destinationFrame.width; + inputSize[1] = state.destinationFrame.height; + inputSize[2] = 1.0 / inputSize[0]; + inputSize[3] = 1.0 / inputSize[1]; + inputPixel[0] = inputSize[0] * state.resolution; + inputPixel[1] = inputSize[1] * state.resolution; + inputPixel[2] = 1.0 / inputPixel[0]; + inputPixel[3] = 1.0 / inputPixel[1]; + inputClamp[0] = 0.5 * inputPixel[2]; + inputClamp[1] = 0.5 * inputPixel[3]; + inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]); + inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]); + // only update the rect if its legacy.. + if (state.legacy) { + var filterArea = globalUniforms.filterArea; + filterArea[0] = state.destinationFrame.width; + filterArea[1] = state.destinationFrame.height; + filterArea[2] = state.sourceFrame.x; + filterArea[3] = state.sourceFrame.y; + globalUniforms.filterClamp = globalUniforms.inputClamp; } - - source.addEventListener('play', this._onPlayStart.bind(this)); - source.addEventListener('pause', this._onPlayStop.bind(this)); - - if (!this._isSourceReady()) - { - source.addEventListener('canplay', this._onCanPlay); - source.addEventListener('canplaythrough', this._onCanPlay); - source.addEventListener('error', this._onError, true); + this.globalUniforms.update(); + var lastState = filterStack[filterStack.length - 1]; + if (state.renderTexture.framebuffer.multisample > 1) { + this.renderer.framebuffer.blit(); } - else - { - this._onCanPlay(); + if (filters.length === 1) { + filters[0].apply(this, state.renderTexture, lastState.renderTexture, constants.CLEAR_MODES.BLEND, state); + this.returnFilterTexture(state.renderTexture); } - - this._load = new Promise(function (resolve) { - if (this$1.valid) - { - resolve(this$1); - } - else - { - this$1._resolve = resolve; - - source.load(); + else { + var flip = state.renderTexture; + var flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); + flop.filterFrame = flip.filterFrame; + var i = 0; + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, constants.CLEAR_MODES.CLEAR, state); + var t = flip; + flip = flop; + flop = t; } - }); - - return this._load; + filters[i].apply(this, flip, lastState.renderTexture, constants.CLEAR_MODES.BLEND, state); + this.returnFilterTexture(flip); + this.returnFilterTexture(flop); + } + state.clear(); + this.statePool.push(state); }; - /** - * Handle video error events. - * - * @private + * Binds a renderTexture with corresponding `filterFrame`, clears it if mode corresponds. + * @param {PIXI.RenderTexture} filterTexture - renderTexture to bind, should belong to filter pool or filter stack + * @param {PIXI.CLEAR_MODES} [clearMode] - clearMode, by default its CLEAR/YES. See {@link PIXI.CLEAR_MODES} */ - VideoResource.prototype._onError = function _onError () - { - this.source.removeEventListener('error', this._onError, true); - this.onError.run(event); + FilterSystem.prototype.bindAndClear = function (filterTexture, clearMode) { + if (clearMode === void 0) { clearMode = constants.CLEAR_MODES.CLEAR; } + if (filterTexture && filterTexture.filterFrame) { + var destinationFrame = this.tempRect; + destinationFrame.width = filterTexture.filterFrame.width; + destinationFrame.height = filterTexture.filterFrame.height; + this.renderer.renderTexture.bind(filterTexture, filterTexture.filterFrame, destinationFrame); + } + else { + this.renderer.renderTexture.bind(filterTexture); + } + // TODO: remove in next major version + if (typeof clearMode === 'boolean') { + clearMode = clearMode ? constants.CLEAR_MODES.CLEAR : constants.CLEAR_MODES.BLEND; + // get deprecation function from utils + utils.deprecation('5.2.1', 'Use CLEAR_MODES when using clear applyFilter option'); + } + if (clearMode === constants.CLEAR_MODES.CLEAR + || (clearMode === constants.CLEAR_MODES.BLIT && this.forceClear)) { + this.renderer.renderTexture.clear(); + } }; - /** - * Returns true if the underlying source is playing. + * Draws a filter. * - * @private - * @return {boolean} True if playing. + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTexture} input - The input render target. + * @param {PIXI.RenderTexture} output - The target to output to. + * @param {PIXI.CLEAR_MODES} [clearMode] - Should the output be cleared before rendering to it */ - VideoResource.prototype._isSourcePlaying = function _isSourcePlaying () - { - var source = this.source; - - return (source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2); + FilterSystem.prototype.applyFilter = function (filter, input, output, clearMode) { + var renderer = this.renderer; + this.bindAndClear(output, clearMode); + // set the uniforms.. + filter.uniforms.uSampler = input; + filter.uniforms.filterGlobals = this.globalUniforms; + // TODO make it so that the order of this does not matter.. + // because it does at the moment cos of global uniforms. + // they need to get resynced + renderer.state.set(filter.state); + renderer.shader.bind(filter); + if (filter.legacy) { + this.quadUv.map(input._frame, input.filterFrame); + renderer.geometry.bind(this.quadUv); + renderer.geometry.draw(constants.DRAW_MODES.TRIANGLES); + } + else { + renderer.geometry.bind(this.quad); + renderer.geometry.draw(constants.DRAW_MODES.TRIANGLE_STRIP); + } }; - /** - * Returns true if the underlying source is ready for playing. + * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_. * - * @private - * @return {boolean} True if ready. + * Use `outputMatrix * vTextureCoord` in the shader. + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. */ - VideoResource.prototype._isSourceReady = function _isSourceReady () - { - return this.source.readyState === 3 || this.source.readyState === 4; + FilterSystem.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) { + var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; + var orig = sprite._texture.orig; + var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y); + var worldTransform = sprite.worldTransform.copyTo(math.Matrix.TEMP_MATRIX); + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + return mappedMatrix; }; - /** - * Runs the update loop when the video is ready to play - * - * @private + * Destroys this Filter System. */ - VideoResource.prototype._onPlayStart = function _onPlayStart () - { - // Just in case the video has not received its can play even yet.. - if (!this.valid) - { - this._onCanPlay(); - } - - if (!this._isAutoUpdating && this.autoUpdate) - { - ticker.Ticker.shared.add(this.update, this); - this._isAutoUpdating = true; - } + FilterSystem.prototype.destroy = function () { + // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem + this.texturePool.clear(false); }; - /** - * Fired when a pause event is triggered, stops the update loop + * Gets a Power-of-Two render texture or fullScreen texture * - * @private + * @protected + * @param {number} minWidth - The minimum width of the render texture in real pixels. + * @param {number} minHeight - The minimum height of the render texture in real pixels. + * @param {number} [resolution=1] - The resolution of the render texture. + * @return {PIXI.RenderTexture} The new render texture. */ - VideoResource.prototype._onPlayStop = function _onPlayStop () - { - if (this._isAutoUpdating) - { - ticker.Ticker.shared.remove(this.update, this); - this._isAutoUpdating = false; - } + FilterSystem.prototype.getOptimalFilterTexture = function (minWidth, minHeight, resolution) { + if (resolution === void 0) { resolution = 1; } + return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution); }; - /** - * Fired when the video is loaded and ready to play + * Gets extra render texture to use inside current filter + * To be compliant with older filters, you can use params in any order * - * @private - */ - VideoResource.prototype._onCanPlay = function _onCanPlay () - { - var ref = this; - var source = ref.source; - - source.removeEventListener('canplay', this._onCanPlay); - source.removeEventListener('canplaythrough', this._onCanPlay); - - var valid = this.valid; - - this.resize(source.videoWidth, source.videoHeight); - - // prevent multiple loaded dispatches.. - if (!valid && this._resolve) - { - this._resolve(this); - this._resolve = null; - } - - if (this._isSourcePlaying()) - { - this._onPlayStart(); - } - else if (this.autoPlay) - { - source.play(); - } - }; - - /** - * Destroys this texture - * @override + * @param {PIXI.RenderTexture} [input] - renderTexture from which size and resolution will be copied + * @param {number} [resolution] - override resolution of the renderTexture + * @returns {PIXI.RenderTexture} */ - VideoResource.prototype.dispose = function dispose () - { - if (this._isAutoUpdating) - { - ticker.Ticker.shared.remove(this.update, this); - } - - if (this.source) - { - this.source.removeEventListener('error', this._onError, true); - this.source.pause(); - this.source.src = ''; - this.source.load(); + FilterSystem.prototype.getFilterTexture = function (input, resolution) { + if (typeof input === 'number') { + var swap = input; + input = resolution; + resolution = swap; } - BaseImageResource.prototype.dispose.call(this); + input = input || this.activeState.renderTexture; + var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; }; - /** - * Should the base texture automatically update itself, set to true by default + * Frees a render texture back into the pool. * - * @member {boolean} + * @param {PIXI.RenderTexture} renderTexture - The renderTarget to free */ - prototypeAccessors.autoUpdate.get = function () - { - return this._autoUpdate; - }; - - prototypeAccessors.autoUpdate.set = function (value) // eslint-disable-line require-jsdoc - { - if (value !== this._autoUpdate) - { - this._autoUpdate = value; - - if (!this._autoUpdate && this._isAutoUpdating) - { - ticker.Ticker.shared.remove(this.update, this); - this._isAutoUpdating = false; - } - else if (this._autoUpdate && !this._isAutoUpdating) - { - ticker.Ticker.shared.add(this.update, this); - this._isAutoUpdating = true; - } - } + FilterSystem.prototype.returnFilterTexture = function (renderTexture) { + this.texturePool.returnTexture(renderTexture); }; - /** - * How many times a second to update the texture from the video. Leave at 0 to update at every render. - * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient. - * - * @member {number} + * Empties the texture pool. */ - prototypeAccessors.updateFPS.get = function () - { - return this._updateFPS; - }; - - prototypeAccessors.updateFPS.set = function (value) // eslint-disable-line require-jsdoc - { - if (value !== this._updateFPS) - { - this._updateFPS = value; - } + FilterSystem.prototype.emptyPool = function () { + this.texturePool.clear(true); }; - /** - * Used to auto-detect the type of resource. - * - * @static - * @param {*} source - The source object - * @param {string} extension - The extension of source, if set - * @return {boolean} `true` if video source + * calls `texturePool.resize()`, affects fullScreen renderTextures */ - VideoResource.test = function test (source, extension) - { - return (source instanceof HTMLVideoElement) - || VideoResource.TYPES.indexOf(extension) > -1; - }; - - Object.defineProperties( VideoResource.prototype, prototypeAccessors ); - - return VideoResource; -}(BaseImageResource)); - -/** - * List of common video file extensions supported by VideoResource. - * @constant - * @member {Array} - * @static - * @readonly - */ -VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov']; - -/** - * Resource type for ImageBitmap. - * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - * @param {ImageBitmap} source - Image element to use - */ -var ImageBitmapResource = /*@__PURE__*/(function (BaseImageResource) { - function ImageBitmapResource () { - BaseImageResource.apply(this, arguments); - } - - if ( BaseImageResource ) ImageBitmapResource.__proto__ = BaseImageResource; - ImageBitmapResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype ); - ImageBitmapResource.prototype.constructor = ImageBitmapResource; - - ImageBitmapResource.test = function test (source) - { - return !!window.createImageBitmap && source instanceof ImageBitmap; + FilterSystem.prototype.resize = function () { + this.texturePool.setScreenSize(this.renderer.view); }; - - return ImageBitmapResource; -}(BaseImageResource)); - -INSTALLED.push( - ImageResource, - ImageBitmapResource, - CanvasResource, - VideoResource, - SVGResource, - BufferResource, - CubeResource, - ArrayResource -); - -var index = ({ - INSTALLED: INSTALLED, - autoDetectResource: autoDetectResource, - ArrayResource: ArrayResource, - BufferResource: BufferResource, - CanvasResource: CanvasResource, - CubeResource: CubeResource, - ImageResource: ImageResource, - ImageBitmapResource: ImageBitmapResource, - SVGResource: SVGResource, - VideoResource: VideoResource, - Resource: Resource, - BaseImageResource: BaseImageResource -}); + return FilterSystem; +}(System)); /** - * System is a base class used for extending systems used by the {@link PIXI.Renderer} + * Base for a common object renderer that can be used as a + * system renderer plugin. * - * @see PIXI.Renderer#addSystem * @class + * @extends PIXI.System * @memberof PIXI */ -var System = function System(renderer) -{ +var ObjectRenderer = /** @class */ (function () { /** - * The renderer this manager works for. - * - * @member {PIXI.Renderer} + * @param {PIXI.Renderer} renderer - The renderer this manager works for. */ - this.renderer = renderer; -}; - -/** - * Generic destroy methods to be overridden by the subclass - */ -System.prototype.destroy = function destroy () -{ - this.renderer = null; -}; - -/** - * Resource type for DepthTexture. - * @class - * @extends PIXI.resources.BufferResource - * @memberof PIXI.resources - */ -var DepthResource = /*@__PURE__*/(function (BufferResource) { - function DepthResource () { - BufferResource.apply(this, arguments); + function ObjectRenderer(renderer) { + /** + * The renderer this manager works for. + * + * @member {PIXI.Renderer} + */ + this.renderer = renderer; } - - if ( BufferResource ) DepthResource.__proto__ = BufferResource; - DepthResource.prototype = Object.create( BufferResource && BufferResource.prototype ); - DepthResource.prototype.constructor = DepthResource; - - DepthResource.prototype.upload = function upload (renderer, baseTexture, glTexture) - { - var gl = renderer.gl; - - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants.ALPHA_MODES.UNPACK); - - if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height) - { - gl.texSubImage2D( - baseTexture.target, - 0, - 0, - 0, - baseTexture.width, - baseTexture.height, - baseTexture.format, - baseTexture.type, - this.data - ); - } - else - { - glTexture.width = baseTexture.width; - glTexture.height = baseTexture.height; - - gl.texImage2D( - baseTexture.target, - 0, - gl.DEPTH_COMPONENT16, // Needed for depth to render properly in webgl2.0 - baseTexture.width, - baseTexture.height, - 0, - baseTexture.format, - baseTexture.type, - this.data - ); - } - - return true; + /** + * Stub method that should be used to empty the current + * batch by rendering objects now. + */ + ObjectRenderer.prototype.flush = function () { + // flush! }; - - return DepthResource; -}(BufferResource)); - -/** - * Frame buffer used by the BaseRenderTexture - * - * @class - * @memberof PIXI - */ -var Framebuffer = function Framebuffer(width, height) -{ - this.width = Math.ceil(width || 100); - this.height = Math.ceil(height || 100); - - this.stencil = false; - this.depth = false; - - this.dirtyId = 0; - this.dirtyFormat = 0; - this.dirtySize = 0; - - this.depthTexture = null; - this.colorTextures = []; - - this.glFramebuffers = {}; - - this.disposeRunner = new runner.Runner('disposeFramebuffer', 2); -}; - -var prototypeAccessors$1 = { colorTexture: { configurable: true } }; - -/** - * Reference to the colorTexture. - * - * @member {PIXI.Texture[]} - * @readonly - */ -prototypeAccessors$1.colorTexture.get = function () -{ - return this.colorTextures[0]; -}; - -/** - * Add texture to the colorTexture array - * - * @param {number} [index=0] - Index of the array to add the texture to - * @param {PIXI.Texture} [texture] - Texture to add to the array - */ -Framebuffer.prototype.addColorTexture = function addColorTexture (index, texture) -{ - if ( index === void 0 ) index = 0; - - // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index] = texture || new BaseTexture(null, { scaleMode: 0, - resolution: 1, - mipmap: false, - width: this.width, - height: this.height }); - - this.dirtyId++; - this.dirtyFormat++; - - return this; -}; - -/** - * Add a depth texture to the frame buffer - * - * @param {PIXI.Texture} [texture] - Texture to add - */ -Framebuffer.prototype.addDepthTexture = function addDepthTexture (texture) -{ - /* eslint-disable max-len */ - this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { scaleMode: 0, - resolution: 1, - width: this.width, - height: this.height, - mipmap: false, - format: constants.FORMATS.DEPTH_COMPONENT, - type: constants.TYPES.UNSIGNED_SHORT }); - /* eslint-disable max-len */ - this.dirtyId++; - this.dirtyFormat++; - - return this; -}; - -/** - * Enable depth on the frame buffer - */ -Framebuffer.prototype.enableDepth = function enableDepth () -{ - this.depth = true; - - this.dirtyId++; - this.dirtyFormat++; - - return this; -}; - -/** - * Enable stencil on the frame buffer - */ -Framebuffer.prototype.enableStencil = function enableStencil () -{ - this.stencil = true; - - this.dirtyId++; - this.dirtyFormat++; - - return this; -}; - -/** - * Resize the frame buffer - * - * @param {number} width - Width of the frame buffer to resize to - * @param {number} height - Height of the frame buffer to resize to - */ -Framebuffer.prototype.resize = function resize (width, height) -{ - width = Math.ceil(width); - height = Math.ceil(height); - - if (width === this.width && height === this.height) { return; } - - this.width = width; - this.height = height; - - this.dirtyId++; - this.dirtySize++; - - for (var i = 0; i < this.colorTextures.length; i++) - { - var texture = this.colorTextures[i]; - var resolution = texture.resolution; - - // take into acount the fact the texture may have a different resolution.. - texture.setSize(width / resolution, height / resolution); - } - - if (this.depthTexture) - { - var resolution$1 = this.depthTexture.resolution; - - this.depthTexture.setSize(width / resolution$1, height / resolution$1); - } -}; - -/** - * disposes WebGL resources that are connected to this geometry - */ -Framebuffer.prototype.dispose = function dispose () -{ - this.disposeRunner.run(this, false); -}; - -Object.defineProperties( Framebuffer.prototype, prototypeAccessors$1 ); + /** + * Generic destruction method that frees all resources. This + * should be called by subclasses. + */ + ObjectRenderer.prototype.destroy = function () { + this.renderer = null; + }; + /** + * Stub method that initializes any state required before + * rendering starts. It is different from the `prerender` + * signal, which occurs every frame, in that it is called + * whenever an object requests _this_ renderer specifically. + */ + ObjectRenderer.prototype.start = function () { + // set the shader.. + }; + /** + * Stops the renderer. It should free up any state and + * become dormant. + */ + ObjectRenderer.prototype.stop = function () { + this.flush(); + }; + /** + * Keeps the object to render. It doesn't have to be + * rendered immediately. + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ObjectRenderer.prototype.render = function (_object) { + // render the object + }; + return ObjectRenderer; +}()); /** - * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. - * - * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded - * otherwise black rectangles will be drawn instead. - * - * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position - * and rotation of the given Display Objects is ignored. For example: - * - * ```js - * let renderer = PIXI.autoDetectRenderer(); - * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 }); - * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); - * let sprite = PIXI.Sprite.from("spinObj_01.png"); - * - * sprite.position.x = 800/2; - * sprite.position.y = 600/2; - * sprite.anchor.x = 0.5; - * sprite.anchor.y = 0.5; - * - * renderer.render(sprite, renderTexture); - * ``` - * - * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 - * you can clear the transform - * - * ```js - * - * sprite.setTransform() - * - * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 }); - * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); - * - * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture - * ``` + * System plugin to the renderer to manage batching. * * @class - * @extends PIXI.BaseTexture - * @memberof PIXI + * @extends PIXI.System + * @memberof PIXI.systems */ -var BaseRenderTexture = /*@__PURE__*/(function (BaseTexture) { - function BaseRenderTexture(options) - { - if (typeof options === 'number') - { - /* eslint-disable prefer-rest-params */ - // Backward compatibility of signature - var width$1 = arguments[0]; - var height$1 = arguments[1]; - var scaleMode = arguments[2]; - var resolution = arguments[3]; - - options = { width: width$1, height: height$1, scaleMode: scaleMode, resolution: resolution }; - /* eslint-enable prefer-rest-params */ - } - - BaseTexture.call(this, null, options); - - var ref = options || {}; - var width = ref.width; - var height = ref.height; - - // Set defaults - this.mipmap = false; - this.width = Math.ceil(width) || 100; - this.height = Math.ceil(height) || 100; - this.valid = true; - - /** - * A reference to the canvas render target (we only need one as this can be shared across renderers) - * - * @protected - * @member {object} - */ - this._canvasRenderTarget = null; - - this.clearColor = [0, 0, 0, 0]; - - this.framebuffer = new Framebuffer(this.width * this.resolution, this.height * this.resolution) - .addColorTexture(0, this); - - // TODO - could this be added the systems? - +var BatchSystem = /** @class */ (function (_super) { + __extends(BatchSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function BatchSystem(renderer) { + var _this = _super.call(this, renderer) || this; /** - * The data structure for the stencil masks. + * An empty renderer. * - * @member {PIXI.MaskData[]} + * @member {PIXI.ObjectRenderer} */ - this.maskStack = []; - + _this.emptyRenderer = new ObjectRenderer(renderer); /** - * The data structure for the filters. + * The currently active ObjectRenderer. * - * @member {Object[]} + * @member {PIXI.ObjectRenderer} */ - this.filterStack = [{}]; + _this.currentRenderer = _this.emptyRenderer; + return _this; } - - if ( BaseTexture ) BaseRenderTexture.__proto__ = BaseTexture; - BaseRenderTexture.prototype = Object.create( BaseTexture && BaseTexture.prototype ); - BaseRenderTexture.prototype.constructor = BaseRenderTexture; - /** - * Resizes the BaseRenderTexture. + * Changes the current renderer to the one given in parameter * - * @param {number} width - The width to resize to. - * @param {number} height - The height to resize to. + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. */ - BaseRenderTexture.prototype.resize = function resize (width, height) - { - width = Math.ceil(width); - height = Math.ceil(height); - this.framebuffer.resize(width * this.resolution, height * this.resolution); + BatchSystem.prototype.setObjectRenderer = function (objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); }; - /** - * Frees the texture and framebuffer from WebGL memory without destroying this texture object. - * This means you can still use the texture later which will upload it to GPU - * memory again. + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + */ + BatchSystem.prototype.flush = function () { + this.setObjectRenderer(this.emptyRenderer); + }; + /** + * Reset the system to an empty renderer + */ + BatchSystem.prototype.reset = function () { + this.setObjectRenderer(this.emptyRenderer); + }; + /** + * Handy function for batch renderers: copies bound textures in first maxTextures locations to array + * sets actual _batchLocation for them * - * @fires PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture[]} - arr copy destination + * @param {number} maxTextures - number of copied elements */ - BaseRenderTexture.prototype.dispose = function dispose () - { - this.framebuffer.dispose(); - - BaseTexture.prototype.dispose.call(this); + BatchSystem.prototype.copyBoundTextures = function (arr, maxTextures) { + var boundTextures = this.renderer.texture.boundTextures; + for (var i = maxTextures - 1; i >= 0; --i) { + arr[i] = boundTextures[i] || null; + if (arr[i]) { + arr[i]._batchLocation = i; + } + } }; - /** - * Destroys this texture. + * Assigns batch locations to textures in array based on boundTextures state. + * All textures in texArray should have `_batchEnabled = _batchId`, + * and their count should be less than `maxTextures`. * + * @param {PIXI.BatchTextureArray} texArray - textures to bound + * @param {PIXI.BaseTexture[]} boundTextures - current state of bound textures + * @param {number} batchId - marker for _batchEnabled param of textures in texArray + * @param {number} maxTextures - number of texture locations to manipulate */ - BaseRenderTexture.prototype.destroy = function destroy () - { - BaseTexture.prototype.destroy.call(this, true); - - this.framebuffer = null; + BatchSystem.prototype.boundArray = function (texArray, boundTextures, batchId, maxTextures) { + var elements = texArray.elements, ids = texArray.ids, count = texArray.count; + var j = 0; + for (var i = 0; i < count; i++) { + var tex = elements[i]; + var loc = tex._batchLocation; + if (loc >= 0 && loc < maxTextures + && boundTextures[loc] === tex) { + ids[i] = loc; + continue; + } + while (j < maxTextures) { + var bound = boundTextures[j]; + if (bound && bound._batchEnabled === batchId + && bound._batchLocation === j) { + j++; + continue; + } + ids[i] = j; + tex._batchLocation = j; + boundTextures[j] = tex; + break; + } + } }; + return BatchSystem; +}(System)); - return BaseRenderTexture; -}(BaseTexture)); - +var CONTEXT_UID_COUNTER = 0; /** - * Stores a texture's frame in UV coordinates, in - * which everything lies in the rectangle `[(0,0), (1,0), - * (1,1), (0,1)]`. - * - * | Corner | Coordinates | - * |--------------|-------------| - * | Top-Left | `(x0,y0)` | - * | Top-Right | `(x1,y1)` | - * | Bottom-Right | `(x2,y2)` | - * | Bottom-Left | `(x3,y3)` | + * System plugin to the renderer to manage the context. * * @class - * @protected - * @memberof PIXI + * @extends PIXI.System + * @memberof PIXI.systems */ -var TextureUvs = function TextureUvs() -{ +var ContextSystem = /** @class */ (function (_super) { + __extends(ContextSystem, _super); + /* eslint-enable camelcase */ /** - * X-component of top-left corner `(x0,y0)`. - * - * @member {number} + * @param {PIXI.Renderer} renderer - The renderer this System works for. */ - this.x0 = 0; - + function ContextSystem(renderer) { + var _this = _super.call(this, renderer) || this; + /** + * Either 1 or 2 to reflect the WebGL version being used + * @member {number} + * @readonly + */ + _this.webGLVersion = 1; + /** + * Extensions being used + * @member {object} + * @readonly + * @property {WEBGL_draw_buffers} drawBuffers - WebGL v1 extension + * @property {WEBGL_depth_texture} depthTexture - WebGL v1 extension + * @property {OES_texture_float} floatTexture - WebGL v1 extension + * @property {WEBGL_lose_context} loseContext - WebGL v1 extension + * @property {OES_vertex_array_object} vertexArrayObject - WebGL v1 extension + * @property {EXT_texture_filter_anisotropic} anisotropicFiltering - WebGL v1 and v2 extension + */ + _this.extensions = {}; + /** + * Features supported by current context + * @member {object} + * @private + * @readonly + * @property {boolean} uint32Indices - Supports of 32-bit indices buffer + */ + _this.supports = { + uint32Indices: false, + }; + // Bind functions + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + renderer.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + renderer.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + return _this; + } + Object.defineProperty(ContextSystem.prototype, "isLost", { + /** + * `true` if the context is lost + * @member {boolean} + * @readonly + */ + get: function () { + return (!this.gl || this.gl.isContextLost()); + }, + enumerable: false, + configurable: true + }); /** - * Y-component of top-left corner `(x0,y0)`. - * - * @member {number} + * Handle the context change event + * @param {WebGLRenderingContext} gl - new webgl context */ - this.y0 = 0; - + ContextSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + }; /** - * X-component of top-right corner `(x1,y1)`. + * Initialize the context * - * @member {number} + * @protected + * @param {WebGLRenderingContext} gl - WebGL context */ - this.x1 = 1; - + ContextSystem.prototype.initFromContext = function (gl) { + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + this.renderer.runners.contextChange.emit(gl); + }; /** - * Y-component of top-right corner `(x1,y1)`. + * Initialize from context options * - * @member {number} + * @protected + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext + * @param {object} options - context attributes */ - this.y1 = 0; - + ContextSystem.prototype.initFromOptions = function (options) { + var gl = this.createContext(this.renderer.view, options); + this.initFromContext(gl); + }; /** - * X-component of bottom-right corner `(x2,y2)`. + * Helper class to create a WebGL Context * - * @member {number} + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {object} An options object that gets passed in to the canvas element containing the context attributes + * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext + * @return {WebGLRenderingContext} the WebGL context */ - this.x2 = 1; - + ContextSystem.prototype.createContext = function (canvas, options) { + var gl; + if (settings.settings.PREFER_ENV >= constants.ENV.WEBGL2) { + gl = canvas.getContext('webgl2', options); + } + if (gl) { + this.webGLVersion = 2; + } + else { + this.webGLVersion = 1; + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support WebGL. Try using the canvas renderer'); + } + } + this.gl = gl; + this.getExtensions(); + return this.gl; + }; /** - * Y-component of bottom-right corner `(x2,y2)`. + * Auto-populate the extensions * - * @member {number} + * @protected */ - this.y2 = 1; - + ContextSystem.prototype.getExtensions = function () { + // time to set up default extensions that Pixi uses. + var gl = this.gl; + if (this.webGLVersion === 1) { + Object.assign(this.extensions, { + drawBuffers: gl.getExtension('WEBGL_draw_buffers'), + depthTexture: gl.getExtension('WEBGL_depth_texture'), + loseContext: gl.getExtension('WEBGL_lose_context'), + vertexArrayObject: gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'), + anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), + uint32ElementIndex: gl.getExtension('OES_element_index_uint'), + // Floats and half-floats + floatTexture: gl.getExtension('OES_texture_float'), + floatTextureLinear: gl.getExtension('OES_texture_float_linear'), + textureHalfFloat: gl.getExtension('OES_texture_half_float'), + textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'), + }); + } + else if (this.webGLVersion === 2) { + Object.assign(this.extensions, { + anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), + // Floats and half-floats + colorBufferFloat: gl.getExtension('EXT_color_buffer_float'), + floatTextureLinear: gl.getExtension('OES_texture_float_linear'), + }); + } + }; /** - * X-component of bottom-left corner `(x3,y3)`. + * Handles a lost webgl context * - * @member {number} + * @protected + * @param {WebGLContextEvent} event - The context lost event. */ - this.x3 = 0; - + ContextSystem.prototype.handleContextLost = function (event) { + event.preventDefault(); + }; /** - * Y-component of bottom-right corner `(x3,y3)`. + * Handles a restored webgl context * - * @member {number} + * @protected */ - this.y3 = 1; - - this.uvsFloat32 = new Float32Array(8); -}; - -/** - * Sets the texture Uvs based on the given frame information. - * - * @protected - * @param {PIXI.Rectangle} frame - The frame of the texture - * @param {PIXI.Rectangle} baseFrame - The base frame of the texture - * @param {number} rotate - Rotation of frame, see {@link PIXI.groupD8} - */ -TextureUvs.prototype.set = function set (frame, baseFrame, rotate) -{ - var tw = baseFrame.width; - var th = baseFrame.height; - - if (rotate) - { - // width and height div 2 div baseFrame size - var w2 = frame.width / 2 / tw; - var h2 = frame.height / 2 / th; - - // coordinates of center - var cX = (frame.x / tw) + w2; - var cY = (frame.y / th) + h2; - - rotate = math.groupD8.add(rotate, math.groupD8.NW); // NW is top-left corner - this.x0 = cX + (w2 * math.groupD8.uX(rotate)); - this.y0 = cY + (h2 * math.groupD8.uY(rotate)); - - rotate = math.groupD8.add(rotate, 2); // rotate 90 degrees clockwise - this.x1 = cX + (w2 * math.groupD8.uX(rotate)); - this.y1 = cY + (h2 * math.groupD8.uY(rotate)); - - rotate = math.groupD8.add(rotate, 2); - this.x2 = cX + (w2 * math.groupD8.uX(rotate)); - this.y2 = cY + (h2 * math.groupD8.uY(rotate)); - - rotate = math.groupD8.add(rotate, 2); - this.x3 = cX + (w2 * math.groupD8.uX(rotate)); - this.y3 = cY + (h2 * math.groupD8.uY(rotate)); - } - else - { - this.x0 = frame.x / tw; - this.y0 = frame.y / th; - - this.x1 = (frame.x + frame.width) / tw; - this.y1 = frame.y / th; - - this.x2 = (frame.x + frame.width) / tw; - this.y2 = (frame.y + frame.height) / th; - - this.x3 = frame.x / tw; - this.y3 = (frame.y + frame.height) / th; - } - - this.uvsFloat32[0] = this.x0; - this.uvsFloat32[1] = this.y0; - this.uvsFloat32[2] = this.x1; - this.uvsFloat32[3] = this.y1; - this.uvsFloat32[4] = this.x2; - this.uvsFloat32[5] = this.y2; - this.uvsFloat32[6] = this.x3; - this.uvsFloat32[7] = this.y3; -}; - -var DEFAULT_UVS = new TextureUvs(); + ContextSystem.prototype.handleContextRestored = function () { + this.renderer.runners.contextChange.emit(this.gl); + }; + ContextSystem.prototype.destroy = function () { + var view = this.renderer.view; + // remove listeners + view.removeEventListener('webglcontextlost', this.handleContextLost); + view.removeEventListener('webglcontextrestored', this.handleContextRestored); + this.gl.useProgram(null); + if (this.extensions.loseContext) { + this.extensions.loseContext.loseContext(); + } + }; + /** + * Handle the post-render runner event + * + * @protected + */ + ContextSystem.prototype.postrender = function () { + if (this.renderer.renderingToScreen) { + this.gl.flush(); + } + }; + /** + * Validate context + * + * @protected + * @param {WebGLRenderingContext} gl - Render context + */ + ContextSystem.prototype.validateContext = function (gl) { + var attributes = gl.getContextAttributes(); + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable max-len, no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable max-len, no-console */ + } + var hasuint32 = ('WebGL2RenderingContext' in window && gl instanceof window.WebGL2RenderingContext) + || !!gl.getExtension('OES_element_index_uint'); + this.supports.uint32Indices = hasuint32; + if (!hasuint32) { + /* eslint-disable max-len, no-console */ + console.warn('Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly'); + /* eslint-enable max-len, no-console */ + } + }; + return ContextSystem; +}(System)); /** - * A texture stores the information that represents an image or part of an image. - * - * It cannot be added to the display list directly; instead use it as the texture for a Sprite. - * If no frame is provided for a texture, then the whole image is used. - * - * You can directly create a texture from an image and then reuse it multiple times like this : - * - * ```js - * let texture = PIXI.Texture.from('assets/image.png'); - * let sprite1 = new PIXI.Sprite(texture); - * let sprite2 = new PIXI.Sprite(texture); - * ``` - * - * If you didnt pass the texture frame to constructor, it enables `noFrame` mode: - * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture. - * - * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. - * You can check for this by checking the sprite's _textureID property. - * ```js - * var texture = PIXI.Texture.from('assets/image.svg'); - * var sprite1 = new PIXI.Sprite(texture); - * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file - * ``` - * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. - * + * Internal framebuffer for WebGL context * @class - * @extends PIXI.utils.EventEmitter * @memberof PIXI */ -var Texture = /*@__PURE__*/(function (EventEmitter) { - function Texture(baseTexture, frame, orig, trim, rotate, anchor) - { - EventEmitter.call(this); - - /** - * Does this Texture have any frame data assigned to it? - * - * This mode is enabled automatically if no frame was passed inside constructor. - * - * In this mode texture is subscribed to baseTexture events, and fires `update` on any change. - * - * Beware, after loading or resize of baseTexture event can fired two times! - * If you want more control, subscribe on baseTexture itself. - * - * ```js - * texture.on('update', () => {}); - * ``` - * - * Any assignment of `frame` switches off `noFrame` mode. - * - * @member {boolean} - */ - this.noFrame = false; - - if (!frame) - { - this.noFrame = true; - frame = new math.Rectangle(0, 0, 1, 1); - } - - if (baseTexture instanceof Texture) - { - baseTexture = baseTexture.baseTexture; - } - - /** - * The base texture that this texture uses. - * - * @member {PIXI.BaseTexture} - */ - this.baseTexture = baseTexture; - +var GLFramebuffer = /** @class */ (function () { + function GLFramebuffer(framebuffer) { /** - * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, - * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) - * - * @member {PIXI.Rectangle} + * The WebGL framebuffer + * @member {WebGLFramebuffer} */ - this._frame = frame; - + this.framebuffer = framebuffer; /** - * This is the trimmed area of original texture, before it was put in atlas - * Please call `updateUvs()` after you change coordinates of `trim` manually. - * - * @member {PIXI.Rectangle} + * stencil+depth , usually costs 32bits per pixel + * @member {WebGLRenderbuffer} */ - this.trim = trim; - + this.stencil = null; /** - * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. - * - * @member {boolean} + * latest known version of framebuffer + * @member {number} + * @protected */ - this.valid = false; - + this.dirtyId = 0; /** - * This will let a renderer know that a texture has been updated (used mainly for WebGL uv updates) - * - * @member {boolean} + * latest known version of framebuffer format + * @member {number} + * @protected */ - this.requiresUpdate = false; - + this.dirtyFormat = 0; /** - * The WebGL UV data cache. Can be used as quad UV - * - * @member {PIXI.TextureUvs} + * latest known version of framebuffer size + * @member {number} * @protected */ - this._uvs = DEFAULT_UVS; - + this.dirtySize = 0; /** - * Default TextureMatrix instance for this texture - * By default that object is not created because its heavy - * - * @member {PIXI.TextureMatrix} + * Detected AA samples number + * @member {PIXI.MSAA_QUALITY} */ - this.uvMatrix = null; - + this.multisample = constants.MSAA_QUALITY.NONE; /** - * This is the area of original texture, before it was put in atlas - * - * @member {PIXI.Rectangle} + * In case MSAA, we use this Renderbuffer instead of colorTextures[0] when we write info + * @member {WebGLRenderbuffer} */ - this.orig = orig || frame;// new Rectangle(0, 0, 1, 1); - - this._rotate = Number(rotate || 0); - - if (rotate === true) - { - // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures - this._rotate = 2; - } - else if (this._rotate % 2 !== 0) - { - throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); - } - + this.msaaBuffer = null; /** - * Anchor point that is used as default if sprite is created with this texture. - * Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point. - * @member {PIXI.Point} - * @default {0,0} + * In case we use MSAA, this is actual framebuffer that has colorTextures[0] + * The contents of that framebuffer are read when we use that renderTexture in sprites + * @member {PIXI.Framebuffer} */ - this.defaultAnchor = anchor ? new math.Point(anchor.x, anchor.y) : new math.Point(0, 0); + this.blitFramebuffer = null; + } + return GLFramebuffer; +}()); +var tempRectangle = new math.Rectangle(); +/** + * System plugin to the renderer to manage framebuffers. + * + * @class + * @extends PIXI.System + * @memberof PIXI.systems + */ +var FramebufferSystem = /** @class */ (function (_super) { + __extends(FramebufferSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function FramebufferSystem(renderer) { + var _this = _super.call(this, renderer) || this; /** - * Update ID is observed by sprites and TextureMatrix instances. - * Call updateUvs() to increment it. - * - * @member {number} - * @protected + * A list of managed framebuffers + * @member {PIXI.Framebuffer[]} + * @readonly */ - - this._updateID = 0; - + _this.managedFramebuffers = []; /** - * The ids under which this Texture has been added to the texture cache. This is - * automatically set as long as Texture.addToCache is used, but may not be set if a - * Texture is added directly to the TextureCache array. - * - * @member {string[]} + * Framebuffer value that shows that we don't know what is bound + * @member {Framebuffer} + * @readonly */ - this.textureCacheIds = []; - - if (!baseTexture.valid) - { - baseTexture.once('loaded', this.onBaseTextureUpdated, this); - } - else if (this.noFrame) - { - // if there is no frame we should monitor for any base texture changes.. - if (baseTexture.valid) - { - this.onBaseTextureUpdated(baseTexture); - } - } - else - { - this.frame = frame; - } - - if (this.noFrame) - { - baseTexture.on('update', this.onBaseTextureUpdated, this); - } + _this.unknownFramebuffer = new Framebuffer(10, 10); + _this.msaaSamples = null; + return _this; } - - if ( EventEmitter ) Texture.__proto__ = EventEmitter; - Texture.prototype = Object.create( EventEmitter && EventEmitter.prototype ); - Texture.prototype.constructor = Texture; - - var prototypeAccessors = { resolution: { configurable: true },frame: { configurable: true },rotate: { configurable: true },width: { configurable: true },height: { configurable: true } }; - /** - * Updates this texture on the gpu. - * - * Calls the TextureResource update. - * - * If you adjusted `frame` manually, please call `updateUvs()` instead. - * + * Sets up the renderer context and necessary buffers. */ - Texture.prototype.update = function update () - { - if (this.baseTexture.resource) - { - this.baseTexture.resource.update(); + FramebufferSystem.prototype.contextChange = function () { + var gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.current = this.unknownFramebuffer; + this.viewport = new math.Rectangle(); + this.hasMRT = true; + this.writeDepthTexture = true; + this.disposeAll(true); + // webgl2 + if (this.renderer.context.webGLVersion === 1) { + // webgl 1! + var nativeDrawBuffersExtension_1 = this.renderer.context.extensions.drawBuffers; + var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture; + if (settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY) { + nativeDrawBuffersExtension_1 = null; + nativeDepthTextureExtension = null; + } + if (nativeDrawBuffersExtension_1) { + gl.drawBuffers = function (activeTextures) { + return nativeDrawBuffersExtension_1.drawBuffersWEBGL(activeTextures); + }; + } + else { + this.hasMRT = false; + gl.drawBuffers = function () { + // empty + }; + } + if (!nativeDepthTextureExtension) { + this.writeDepthTexture = false; + } + } + else { + // WebGL2 + // cache possible MSAA samples + this.msaaSamples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES); } }; - /** - * Called when the base texture is updated + * Bind a framebuffer * - * @protected - * @param {PIXI.BaseTexture} baseTexture - The base texture. + * @param {PIXI.Framebuffer} framebuffer + * @param {PIXI.Rectangle} [frame] frame, default is framebuffer size */ - Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated (baseTexture) - { - if (this.noFrame) - { - if (!this.baseTexture.valid) - { - return; + FramebufferSystem.prototype.bind = function (framebuffer, frame) { + var gl = this.gl; + if (framebuffer) { + // TODO caching layer! + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + if (this.current !== framebuffer) { + this.current = framebuffer; + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); + } + // make sure all textures are unbound.. + // now check for updates... + if (fbo.dirtyId !== framebuffer.dirtyId) { + fbo.dirtyId = framebuffer.dirtyId; + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { + fbo.dirtyFormat = framebuffer.dirtyFormat; + this.updateFramebuffer(framebuffer); + } + else if (fbo.dirtySize !== framebuffer.dirtySize) { + fbo.dirtySize = framebuffer.dirtySize; + this.resizeFramebuffer(framebuffer); + } + } + for (var i = 0; i < framebuffer.colorTextures.length; i++) { + var tex = framebuffer.colorTextures[i]; + this.renderer.texture.unbind(tex.parentTextureArray || tex); + } + if (framebuffer.depthTexture) { + this.renderer.texture.unbind(framebuffer.depthTexture); + } + if (frame) { + this.setViewport(frame.x, frame.y, frame.width, frame.height); + } + else { + this.setViewport(0, 0, framebuffer.width, framebuffer.height); } - - this._frame.width = baseTexture.width; - this._frame.height = baseTexture.height; - this.valid = true; - this.updateUvs(); } - else - { - // TODO this code looks confusing.. boo to abusing getters and setters! - // if user gave us frame that has bigger size than resized texture it can be a problem - this.frame = this._frame; + else { + if (this.current) { + this.current = null; + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } + if (frame) { + this.setViewport(frame.x, frame.y, frame.width, frame.height); + } + else { + this.setViewport(0, 0, this.renderer.width, this.renderer.height); + } } - - this.emit('update', this); }; - /** - * Destroys this texture + * Set the WebGLRenderingContext's viewport. * - * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + * @param {Number} x - X position of viewport + * @param {Number} y - Y position of viewport + * @param {Number} width - Width of viewport + * @param {Number} height - Height of viewport */ - Texture.prototype.destroy = function destroy (destroyBase) - { - if (this.baseTexture) - { - if (destroyBase) - { - var ref = this.baseTexture; - var resource = ref.resource; - - // delete the texture if it exists in the texture cache.. - // this only needs to be removed if the base texture is actually destroyed too.. - if (resource && utils.TextureCache[resource.url]) - { - Texture.removeFromCache(resource.url); - } - - this.baseTexture.destroy(); - } - - this.baseTexture.off('update', this.onBaseTextureUpdated, this); - - this.baseTexture = null; + FramebufferSystem.prototype.setViewport = function (x, y, width, height) { + var v = this.viewport; + if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) { + v.x = x; + v.y = y; + v.width = width; + v.height = height; + this.gl.viewport(x, y, width, height); } - - this._frame = null; - this._uvs = null; - this.trim = null; - this.orig = null; - - this.valid = false; - - Texture.removeFromCache(this); - this.textureCacheIds = null; }; - + Object.defineProperty(FramebufferSystem.prototype, "size", { + /** + * Get the size of the current width and height. Returns object with `width` and `height` values. + * + * @member {object} + * @readonly + */ + get: function () { + if (this.current) { + // TODO store temp + return { x: 0, y: 0, width: this.current.width, height: this.current.height }; + } + return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height }; + }, + enumerable: false, + configurable: true + }); /** - * Creates a new texture object that acts the same as this one. + * Clear the color of the context * - * @return {PIXI.Texture} The new texture + * @param {Number} r - Red value from 0 to 1 + * @param {Number} g - Green value from 0 to 1 + * @param {Number} b - Blue value from 0 to 1 + * @param {Number} a - Alpha value from 0 to 1 + * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks + * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. */ - Texture.prototype.clone = function clone () - { - return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate, this.defaultAnchor); + FramebufferSystem.prototype.clear = function (r, g, b, a, mask) { + if (mask === void 0) { mask = constants.BUFFER_BITS.COLOR | constants.BUFFER_BITS.DEPTH; } + var gl = this.gl; + // TODO clear color can be set only one right? + gl.clearColor(r, g, b, a); + gl.clear(mask); }; - /** - * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. - * Call it after changing the frame + * Initialize framebuffer for this context + * + * @protected + * @param {PIXI.Framebuffer} framebuffer + * @returns {PIXI.GLFramebuffer} created GLFramebuffer */ - Texture.prototype.updateUvs = function updateUvs () - { - if (this._uvs === DEFAULT_UVS) - { - this._uvs = new TextureUvs(); - } - - this._uvs.set(this._frame, this.baseTexture, this.rotate); - - this._updateID++; + FramebufferSystem.prototype.initFramebuffer = function (framebuffer) { + var gl = this.gl; + var fbo = new GLFramebuffer(gl.createFramebuffer()); + fbo.multisample = this.detectSamples(framebuffer.multisample); + framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo; + this.managedFramebuffers.push(framebuffer); + framebuffer.disposeRunner.add(this); + return fbo; }; - /** - * Helper function that creates a new Texture based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture + * Resize the framebuffer * - * @static - * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source - * Source to create texture from - * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. - * @param {boolean} [strict] Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. - * @return {PIXI.Texture} The newly created texture + * @protected + * @param {PIXI.Framebuffer} framebuffer */ - Texture.from = function from (source, options, strict) - { - if ( options === void 0 ) options = {}; - if ( strict === void 0 ) strict = settings.settings.STRICT_TEXTURE_CACHE; - - var isFrame = typeof source === 'string'; - var cacheId = null; - - if (isFrame) - { - cacheId = source; - } - else - { - if (!source._pixiId) - { - source._pixiId = "pixiid_" + (utils.uid()); - } - - cacheId = source._pixiId; + FramebufferSystem.prototype.resizeFramebuffer = function (framebuffer) { + var gl = this.gl; + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (fbo.stencil) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); } - - var texture = utils.TextureCache[cacheId]; - - // Strict-mode rejects invalid cacheIds - if (isFrame && strict && !texture) - { - throw new Error(("The cacheId \"" + cacheId + "\" does not exist in TextureCache.")); + var colorTextures = framebuffer.colorTextures; + for (var i = 0; i < colorTextures.length; i++) { + this.renderer.texture.bind(colorTextures[i], 0); } - - if (!texture) - { - if (!options.resolution) - { - options.resolution = utils.getResolutionOfUrl(source); - } - - texture = new Texture(new BaseTexture(source, options)); - texture.baseTexture.cacheId = cacheId; - - BaseTexture.addToCache(texture.baseTexture, cacheId); - Texture.addToCache(texture, cacheId); + if (framebuffer.depthTexture) { + this.renderer.texture.bind(framebuffer.depthTexture, 0); } - - // lets assume its a base texture! - return texture; }; - /** - * Create a new Texture with a BufferResource from a Float32Array. - * RGBA values are floats from 0 to 1. - * @static - * @param {Float32Array|Uint8Array} buffer The optional array to use, if no data - * is provided, a new Float32Array is created. - * @param {number} width - Width of the resource - * @param {number} height - Height of the resource - * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. - * @return {PIXI.Texture} The resulting new BaseTexture + * Update the framebuffer + * + * @protected + * @param {PIXI.Framebuffer} framebuffer */ - Texture.fromBuffer = function fromBuffer (buffer, width, height, options) - { - return new Texture(BaseTexture.fromBuffer(buffer, width, height, options)); - }; - - /** - * Create a texture from a source and add to the cache. - * - * @static - * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. - * @param {String} imageUrl - File name of texture, for cache and resolving resolution. - * @param {String} [name] - Human readable name for the texture cache. If no name is - * specified, only `imageUrl` will be used as the cache ID. - * @return {PIXI.Texture} Output texture - */ - Texture.fromLoader = function fromLoader (source, imageUrl, name) - { - var resource = new ImageResource(source); - - resource.url = imageUrl; - - var baseTexture = new BaseTexture(resource, { - scaleMode: settings.settings.SCALE_MODE, - resolution: utils.getResolutionOfUrl(imageUrl), - }); - - var texture = new Texture(baseTexture); - - // No name, use imageUrl instead - if (!name) - { - name = imageUrl; + FramebufferSystem.prototype.updateFramebuffer = function (framebuffer) { + var gl = this.gl; + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + // bind the color texture + var colorTextures = framebuffer.colorTextures; + var count = colorTextures.length; + if (!gl.drawBuffers) { + count = Math.min(count, 1); } - - // lets also add the frame to pixi's global cache for 'fromLoader' function - BaseTexture.addToCache(texture.baseTexture, name); - Texture.addToCache(texture, name); - - // also add references by url if they are different. - if (name !== imageUrl) - { - BaseTexture.addToCache(texture.baseTexture, imageUrl); - Texture.addToCache(texture, imageUrl); + if (fbo.multisample > 1) { + fbo.msaaBuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, fbo.msaaBuffer); } - - return texture; - }; - - /** - * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. - * - * @static - * @param {PIXI.Texture} texture - The Texture to add to the cache. - * @param {string} id - The id that the Texture will be stored against. - */ - Texture.addToCache = function addToCache (texture, id) - { - if (id) - { - if (texture.textureCacheIds.indexOf(id) === -1) - { - texture.textureCacheIds.push(id); + var activeTextures = []; + for (var i = 0; i < count; i++) { + if (i === 0 && fbo.multisample > 1) { + continue; } - - if (utils.TextureCache[id]) - { - // eslint-disable-next-line no-console - console.warn(("Texture added to the cache with an id [" + id + "] that already had an entry")); + var texture = framebuffer.colorTextures[i]; + var parentTexture = texture.parentTextureArray || texture; + this.renderer.texture.bind(parentTexture, 0); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, 0); + activeTextures.push(gl.COLOR_ATTACHMENT0 + i); + } + if (activeTextures.length > 1) { + gl.drawBuffers(activeTextures); + } + if (framebuffer.depthTexture) { + var writeDepthTexture = this.writeDepthTexture; + if (writeDepthTexture) { + var depthTexture = framebuffer.depthTexture; + this.renderer.texture.bind(depthTexture, 0); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, 0); + } + } + if (!fbo.stencil && (framebuffer.stencil || framebuffer.depth)) { + fbo.stencil = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // TODO.. this is depth AND stencil? + if (!framebuffer.depthTexture) { // you can't have both, so one should take priority if enabled + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); } - - utils.TextureCache[id] = texture; } }; - /** - * Remove a Texture from the global TextureCache. + * Detects number of samples that is not more than a param but as close to it as possible * - * @static - * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself - * @return {PIXI.Texture|null} The Texture that was removed + * @param {PIXI.MSAA_QUALITY} samples - number of samples + * @returns {PIXI.MSAA_QUALITY} - recommended number of samples */ - Texture.removeFromCache = function removeFromCache (texture) - { - if (typeof texture === 'string') - { - var textureFromCache = utils.TextureCache[texture]; - - if (textureFromCache) - { - var index = textureFromCache.textureCacheIds.indexOf(texture); - - if (index > -1) - { - textureFromCache.textureCacheIds.splice(index, 1); - } - - delete utils.TextureCache[texture]; - - return textureFromCache; - } + FramebufferSystem.prototype.detectSamples = function (samples) { + var msaaSamples = this.msaaSamples; + var res = constants.MSAA_QUALITY.NONE; + if (samples <= 1 || msaaSamples === null) { + return res; } - else if (texture && texture.textureCacheIds) - { - for (var i = 0; i < texture.textureCacheIds.length; ++i) - { - // Check that texture matches the one being passed in before deleting it from the cache. - if (utils.TextureCache[texture.textureCacheIds[i]] === texture) - { - delete utils.TextureCache[texture.textureCacheIds[i]]; - } + for (var i = 0; i < msaaSamples.length; i++) { + if (msaaSamples[i] <= samples) { + res = msaaSamples[i]; + break; } - - texture.textureCacheIds.length = 0; - - return texture; } - - return null; + if (res === 1) { + res = constants.MSAA_QUALITY.NONE; + } + return res; }; - /** - * Returns resolution of baseTexture + * Only works with WebGL2 * - * @member {number} - * @readonly + * blits framebuffer to another of the same or bigger size + * after that target framebuffer is bound + * + * Fails with WebGL warning if blits multisample framebuffer to different size + * + * @param {PIXI.Framebuffer} [framebuffer] - by default it blits "into itself", from renderBuffer to texture. + * @param {PIXI.Rectangle} [sourcePixels] - source rectangle in pixels + * @param {PIXI.Rectangle} [destPixels] - dest rectangle in pixels, assumed to be the same as sourcePixels */ - prototypeAccessors.resolution.get = function () - { - return this.baseTexture.resolution; + FramebufferSystem.prototype.blit = function (framebuffer, sourcePixels, destPixels) { + var _a = this, current = _a.current, renderer = _a.renderer, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + if (renderer.context.webGLVersion !== 2) { + return; + } + if (!current) { + return; + } + var fbo = current.glFramebuffers[CONTEXT_UID]; + if (!fbo) { + return; + } + if (!framebuffer) { + if (fbo.multisample <= 1) { + return; + } + if (!fbo.blitFramebuffer) { + fbo.blitFramebuffer = new Framebuffer(current.width, current.height); + fbo.blitFramebuffer.addColorTexture(0, current.colorTextures[0]); + } + framebuffer = fbo.blitFramebuffer; + framebuffer.width = current.width; + framebuffer.height = current.height; + } + if (!sourcePixels) { + sourcePixels = tempRectangle; + sourcePixels.width = current.width; + sourcePixels.height = current.height; + } + if (!destPixels) { + destPixels = sourcePixels; + } + var sameSize = sourcePixels.width === destPixels.width && sourcePixels.height === destPixels.height; + this.bind(framebuffer); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo.framebuffer); + gl.blitFramebuffer(sourcePixels.x, sourcePixels.y, sourcePixels.width, sourcePixels.height, destPixels.x, destPixels.y, destPixels.width, destPixels.height, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR); }; - /** - * The frame specifies the region of the base texture that this texture uses. - * Please call `updateUvs()` after you change coordinates of `frame` manually. - * - * @member {PIXI.Rectangle} + * Disposes framebuffer + * @param {PIXI.Framebuffer} framebuffer - framebuffer that has to be disposed of + * @param {boolean} [contextLost=false] - If context was lost, we suppress all delete function calls */ - prototypeAccessors.frame.get = function () - { - return this._frame; - }; - - prototypeAccessors.frame.set = function (frame) // eslint-disable-line require-jsdoc - { - this._frame = frame; - - this.noFrame = false; - - var x = frame.x; - var y = frame.y; - var width = frame.width; - var height = frame.height; - var xNotFit = x + width > this.baseTexture.width; - var yNotFit = y + height > this.baseTexture.height; - - if (xNotFit || yNotFit) - { - var relationship = xNotFit && yNotFit ? 'and' : 'or'; - var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + (this.baseTexture.width); - var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + (this.baseTexture.height); - - throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' - + errorX + " " + relationship + " " + errorY); + FramebufferSystem.prototype.disposeFramebuffer = function (framebuffer, contextLost) { + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + var gl = this.gl; + if (!fbo) { + return; } - - this.valid = width && height && this.baseTexture.valid; - - if (!this.trim && !this.rotate) - { - this.orig = frame; + delete framebuffer.glFramebuffers[this.CONTEXT_UID]; + var index = this.managedFramebuffers.indexOf(framebuffer); + if (index >= 0) { + this.managedFramebuffers.splice(index, 1); } - - if (this.valid) - { - this.updateUvs(); + framebuffer.disposeRunner.remove(this); + if (!contextLost) { + gl.deleteFramebuffer(fbo.framebuffer); + if (fbo.stencil) { + gl.deleteRenderbuffer(fbo.stencil); + } } }; - /** - * Indicates whether the texture is rotated inside the atlas - * set to 2 to compensate for texture packer rotation - * set to 6 to compensate for spine packer rotation - * can be used to rotate or mirror sprites - * See {@link PIXI.groupD8} for explanation - * - * @member {number} + * Disposes all framebuffers, but not textures bound to them + * @param {boolean} [contextLost=false] - If context was lost, we suppress all delete function calls */ - prototypeAccessors.rotate.get = function () - { - return this._rotate; - }; - - prototypeAccessors.rotate.set = function (rotate) // eslint-disable-line require-jsdoc - { - this._rotate = rotate; - if (this.valid) - { - this.updateUvs(); + FramebufferSystem.prototype.disposeAll = function (contextLost) { + var list = this.managedFramebuffers; + this.managedFramebuffers = []; + for (var i = 0; i < list.length; i++) { + this.disposeFramebuffer(list[i], contextLost); } }; - /** - * The width of the Texture in pixels. + * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. + * Used by MaskSystem, when its time to use stencil mask for Graphics element. * - * @member {number} + * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind. + * + * @private */ - prototypeAccessors.width.get = function () - { - return this.orig.width; + FramebufferSystem.prototype.forceStencil = function () { + var framebuffer = this.current; + if (!framebuffer) { + return; + } + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (!fbo || fbo.stencil) { + return; + } + framebuffer.enableStencil(); + var w = framebuffer.width; + var h = framebuffer.height; + var gl = this.gl; + var stencil = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); + fbo.stencil = stencil; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); }; - /** - * The height of the Texture in pixels. + * resets framebuffer stored state, binds screen framebuffer * - * @member {number} + * should be called before renderTexture reset() */ - prototypeAccessors.height.get = function () - { - return this.orig.height; + FramebufferSystem.prototype.reset = function () { + this.current = this.unknownFramebuffer; + this.viewport = new math.Rectangle(); }; + return FramebufferSystem; +}(System)); - Object.defineProperties( Texture.prototype, prototypeAccessors ); - - return Texture; -}(utils.EventEmitter)); - -function createWhiteTexture() -{ - var canvas = document.createElement('canvas'); - - canvas.width = 16; - canvas.height = 16; - - var context = canvas.getContext('2d'); - - context.fillStyle = 'white'; - context.fillRect(0, 0, 16, 16); - - return new Texture(new BaseTexture(new CanvasResource(canvas))); -} - -function removeAllHandlers(tex) -{ - tex.destroy = function _emptyDestroy() { /* empty */ }; - tex.on = function _emptyOn() { /* empty */ }; - tex.once = function _emptyOnce() { /* empty */ }; - tex.emit = function _emptyEmit() { /* empty */ }; -} - -/** - * An empty texture, used often to not have to create multiple empty textures. - * Can not be destroyed. - * - * @static - * @constant - * @member {PIXI.Texture} - */ -Texture.EMPTY = new Texture(new BaseTexture()); -removeAllHandlers(Texture.EMPTY); -removeAllHandlers(Texture.EMPTY.baseTexture); - -/** - * A white texture of 16x16 size, used for graphics and other things - * Can not be destroyed. - * - * @static - * @constant - * @member {PIXI.Texture} - */ -Texture.WHITE = createWhiteTexture(); -removeAllHandlers(Texture.WHITE); -removeAllHandlers(Texture.WHITE.baseTexture); +var GLBuffer = /** @class */ (function () { + function GLBuffer(buffer) { + this.buffer = buffer || null; + this.updateID = -1; + this.byteLength = -1; + this.refCount = 0; + } + return GLBuffer; +}()); +var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 }; /** - * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. - * - * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded - * otherwise black rectangles will be drawn instead. - * - * __Hint-2__: The actual memory allocation will happen on first render. - * You shouldn't create renderTextures each frame just to delete them after, try to reuse them. - * - * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: - * - * ```js - * let renderer = PIXI.autoDetectRenderer(); - * let renderTexture = PIXI.RenderTexture.create(800, 600); - * let sprite = PIXI.Sprite.from("spinObj_01.png"); - * - * sprite.position.x = 800/2; - * sprite.position.y = 600/2; - * sprite.anchor.x = 0.5; - * sprite.anchor.y = 0.5; - * - * renderer.render(sprite, renderTexture); - * ``` - * - * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 - * you can clear the transform - * - * ```js - * - * sprite.setTransform() - * - * let renderTexture = new PIXI.RenderTexture.create(100, 100); - * - * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture - * ``` + * System plugin to the renderer to manage geometry. * * @class - * @extends PIXI.Texture - * @memberof PIXI + * @extends PIXI.System + * @memberof PIXI.systems */ -var RenderTexture = /*@__PURE__*/(function (Texture) { - function RenderTexture(baseRenderTexture, frame) - { - // support for legacy.. - var _legacyRenderer = null; - - if (!(baseRenderTexture instanceof BaseRenderTexture)) - { - /* eslint-disable prefer-rest-params, no-console */ - var width = arguments[1]; - var height = arguments[2]; - var scaleMode = arguments[3]; - var resolution = arguments[4]; - - // we have an old render texture.. - console.warn(("Please use RenderTexture.create(" + width + ", " + height + ") instead of the ctor directly.")); - _legacyRenderer = arguments[0]; - /* eslint-enable prefer-rest-params, no-console */ - - frame = null; - baseRenderTexture = new BaseRenderTexture({ - width: width, - height: height, - scaleMode: scaleMode, - resolution: resolution, - }); - } - +var GeometrySystem = /** @class */ (function (_super) { + __extends(GeometrySystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function GeometrySystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this._activeGeometry = null; + _this._activeVao = null; /** - * The base texture object that this texture uses - * - * @member {PIXI.BaseTexture} + * `true` if we has `*_vertex_array_object` extension + * @member {boolean} + * @readonly */ - Texture.call(this, baseRenderTexture, frame); - - this.legacyRenderer = _legacyRenderer; - + _this.hasVao = true; /** - * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. - * + * `true` if has `ANGLE_instanced_arrays` extension * @member {boolean} + * @readonly */ - this.valid = true; - + _this.hasInstance = true; /** - * Stores `sourceFrame` when this texture is inside current filter stack. - * You can read it inside filters. - * + * `true` if support `gl.UNSIGNED_INT` in `gl.drawElements` or `gl.drawElementsInstanced` + * @member {boolean} * @readonly - * @member {PIXI.Rectangle} */ - this.filterFrame = null; - + _this.canUseUInt32ElementIndex = false; /** - * The key for pooled texture of FilterSystem - * @protected - * @member {string} + * Cache for all geometries by id, used in case renderer gets destroyed or for profiling + * @member {object} + * @readonly */ - this.filterPoolKey = null; - - this.updateUvs(); + _this.managedGeometries = {}; + /** + * Cache for all buffers by id, used in case renderer gets destroyed or for profiling + * @member {object} + * @readonly + */ + _this.managedBuffers = {}; + return _this; } - - if ( Texture ) RenderTexture.__proto__ = Texture; - RenderTexture.prototype = Object.create( Texture && Texture.prototype ); - RenderTexture.prototype.constructor = RenderTexture; - /** - * Resizes the RenderTexture. - * - * @param {number} width - The width to resize to. - * @param {number} height - The height to resize to. - * @param {boolean} [resizeBaseTexture=true] - Should the baseTexture.width and height values be resized as well? + * Sets up the renderer context and necessary buffers. */ - RenderTexture.prototype.resize = function resize (width, height, resizeBaseTexture) - { - if ( resizeBaseTexture === void 0 ) resizeBaseTexture = true; - - width = Math.ceil(width); - height = Math.ceil(height); - - // TODO - could be not required.. - this.valid = (width > 0 && height > 0); - - this._frame.width = this.orig.width = width; - this._frame.height = this.orig.height = height; - - if (resizeBaseTexture) - { - this.baseTexture.resize(width, height); + GeometrySystem.prototype.contextChange = function () { + this.disposeAll(true); + var gl = this.gl = this.renderer.gl; + var context = this.renderer.context; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + // webgl2 + if (!gl.createVertexArray) { + // webgl 1! + var nativeVaoExtension_1 = this.renderer.context.extensions.vertexArrayObject; + if (settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY) { + nativeVaoExtension_1 = null; + } + if (nativeVaoExtension_1) { + gl.createVertexArray = function () { + return nativeVaoExtension_1.createVertexArrayOES(); + }; + gl.bindVertexArray = function (vao) { + return nativeVaoExtension_1.bindVertexArrayOES(vao); + }; + gl.deleteVertexArray = function (vao) { + return nativeVaoExtension_1.deleteVertexArrayOES(vao); + }; + } + else { + this.hasVao = false; + gl.createVertexArray = function () { + return null; + }; + gl.bindVertexArray = function () { + return null; + }; + gl.deleteVertexArray = function () { + return null; + }; + } } - - this.updateUvs(); + if (!gl.vertexAttribDivisor) { + var instanceExt_1 = gl.getExtension('ANGLE_instanced_arrays'); + if (instanceExt_1) { + gl.vertexAttribDivisor = function (a, b) { + return instanceExt_1.vertexAttribDivisorANGLE(a, b); + }; + gl.drawElementsInstanced = function (a, b, c, d, e) { + return instanceExt_1.drawElementsInstancedANGLE(a, b, c, d, e); + }; + gl.drawArraysInstanced = function (a, b, c, d) { + return instanceExt_1.drawArraysInstancedANGLE(a, b, c, d); + }; + } + else { + this.hasInstance = false; + } + } + this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex; }; - /** - * Changes the resolution of baseTexture, but does not change framebuffer size. + * Binds geometry so that is can be drawn. Creating a Vao if required * - * @param {number} resolution - The new resolution to apply to RenderTexture + * @param {PIXI.Geometry} geometry - instance of geometry to bind + * @param {PIXI.Shader} [shader] - instance of shader to use vao for */ - RenderTexture.prototype.setResolution = function setResolution (resolution) - { - var ref = this; - var baseTexture = ref.baseTexture; - - if (baseTexture.resolution === resolution) - { - return; + GeometrySystem.prototype.bind = function (geometry, shader) { + shader = shader || this.renderer.shader.shader; + var gl = this.gl; + // not sure the best way to address this.. + // currently different shaders require different VAOs for the same geometry + // Still mulling over the best way to solve this one.. + // will likely need to modify the shader attribute locations at run time! + var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + if (!vaos) { + this.managedGeometries[geometry.id] = geometry; + geometry.disposeRunner.add(this); + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } - - baseTexture.setResolution(resolution); - this.resize(baseTexture.width, baseTexture.height, false); + var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); + this._activeGeometry = geometry; + if (this._activeVao !== vao) { + this._activeVao = vao; + if (this.hasVao) { + gl.bindVertexArray(vao); + } + else { + this.activateVao(geometry, shader.program); + } + } + // TODO - optimise later! + // don't need to loop through if nothing changed! + // maybe look to add an 'autoupdate' to geometry? + this.updateBuffers(); }; - /** - * A short hand way of creating a render texture. - * - * @param {object} [options] - Options - * @param {number} [options.width=100] - The width of the render texture - * @param {number} [options.height=100] - The height of the render texture - * @param {number} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the texture being generated - * @return {PIXI.RenderTexture} The new render texture + * Reset and unbind any active VAO and geometry */ - RenderTexture.create = function create (options) - { - // fallback, old-style: create(width, height, scaleMode, resolution) - if (typeof options === 'number') - { - /* eslint-disable prefer-rest-params */ - options = { - width: options, - height: arguments[1], - scaleMode: arguments[2], - resolution: arguments[3], - }; - /* eslint-enable prefer-rest-params */ - } - - return new RenderTexture(new BaseRenderTexture(options)); + GeometrySystem.prototype.reset = function () { + this.unbind(); }; - - return RenderTexture; -}(Texture)); - -/** - * Experimental! - * - * Texture pool, used by FilterSystem and plugins - * Stores collection of temporary pow2 or screen-sized renderTextures - * - * If you use custom RenderTexturePool for your filters, you can use methods - * `getFilterTexture` and `returnFilterTexture` same as in - * - * @class - * @memberof PIXI - */ -var RenderTexturePool = function RenderTexturePool(textureOptions) -{ - this.texturePool = {}; - this.textureOptions = textureOptions || {}; /** - * Allow renderTextures of the same size as screen, not just pow2 - * - * Automatically sets to true after `setScreenSize` - * - * @member {boolean} - * @default false + * Update buffers + * @protected */ - this.enableFullScreen = false; - - this._pixelsWidth = 0; - this._pixelsHeight = 0; -}; - -/** - * creates of texture with params that were specified in pool constructor - * - * @param {number} realWidth width of texture in pixels - * @param {number} realHeight height of texture in pixels - * @returns {RenderTexture} - */ -RenderTexturePool.prototype.createTexture = function createTexture (realWidth, realHeight) -{ - var baseRenderTexture = new BaseRenderTexture(Object.assign({ - width: realWidth, - height: realHeight, - resolution: 1, - }, this.textureOptions)); - - return new RenderTexture(baseRenderTexture); -}; - -/** - * Gets a Power-of-Two render texture or fullScreen texture - * - * @protected - * @param {number} minWidth - The minimum width of the render texture in real pixels. - * @param {number} minHeight - The minimum height of the render texture in real pixels. - * @param {number} [resolution=1] - The resolution of the render texture. - * @return {PIXI.RenderTexture} The new render texture. - */ -RenderTexturePool.prototype.getOptimalTexture = function getOptimalTexture (minWidth, minHeight, resolution) -{ - if ( resolution === void 0 ) resolution = 1; - - var key = RenderTexturePool.SCREEN_KEY; - - minWidth *= resolution; - minHeight *= resolution; - - if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) - { - minWidth = utils.nextPow2(minWidth); - minHeight = utils.nextPow2(minHeight); - key = ((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF); - } - - if (!this.texturePool[key]) - { - this.texturePool[key] = []; - } - - var renderTexture = this.texturePool[key].pop(); - - if (!renderTexture) - { - renderTexture = this.createTexture(minWidth, minHeight); - } - - renderTexture.filterPoolKey = key; - renderTexture.setResolution(resolution); - - return renderTexture; -}; - -/** - * Gets extra texture of the same size as input renderTexture - * - * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)` - * - * @param {PIXI.RenderTexture} input renderTexture from which size and resolution will be copied - * @param {number} [resolution] override resolution of the renderTexture - * It overrides, it does not multiply - * @returns {PIXI.RenderTexture} - */ -RenderTexturePool.prototype.getFilterTexture = function getFilterTexture (input, resolution) -{ - var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution); - - filterTexture.filterFrame = input.filterFrame; - - return filterTexture; -}; - -/** - * Place a render texture back into the pool. - * @param {PIXI.RenderTexture} renderTexture - The renderTexture to free - */ -RenderTexturePool.prototype.returnTexture = function returnTexture (renderTexture) -{ - var key = renderTexture.filterPoolKey; - - renderTexture.filterFrame = null; - this.texturePool[key].push(renderTexture); -}; - -/** - * Alias for returnTexture, to be compliant with FilterSystem interface - * @param {PIXI.RenderTexture} renderTexture - The renderTexture to free - */ -RenderTexturePool.prototype.returnFilterTexture = function returnFilterTexture (renderTexture) -{ - this.returnTexture(renderTexture); -}; - -/** - * Clears the pool - * - * @param {boolean} [destroyTextures=true] destroy all stored textures - */ -RenderTexturePool.prototype.clear = function clear (destroyTextures) -{ - destroyTextures = destroyTextures !== false; - if (destroyTextures) - { - for (var i in this.texturePool) - { - var textures = this.texturePool[i]; - - if (textures) - { - for (var j = 0; j < textures.length; j++) - { - textures[j].destroy(true); + GeometrySystem.prototype.updateBuffers = function () { + var geometry = this._activeGeometry; + var gl = this.gl; + for (var i = 0; i < geometry.buffers.length; i++) { + var buffer = geometry.buffers[i]; + var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; + if (buffer._updateID !== glBuffer.updateID) { + glBuffer.updateID = buffer._updateID; + // TODO can cache this on buffer! maybe added a getter / setter? + var type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; + // TODO this could change if the VAO changes... + // need to come up with a better way to cache.. + // if (this.boundBuffers[type] !== glBuffer) + // { + // this.boundBuffers[type] = glBuffer; + gl.bindBuffer(type, glBuffer.buffer); + // } + this._boundBuffer = glBuffer; + if (glBuffer.byteLength >= buffer.data.byteLength) { + // offset is always zero for now! + gl.bufferSubData(type, 0, buffer.data); + } + else { + var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW; + glBuffer.byteLength = buffer.data.byteLength; + gl.bufferData(type, buffer.data, drawType); } } } - } - - this.texturePool = {}; -}; - -/** - * If screen size was changed, drops all screen-sized textures, - * sets new screen size, sets `enableFullScreen` to true - * - * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen` - * - * @param {PIXI.ISize} size - Initial size of screen - */ -RenderTexturePool.prototype.setScreenSize = function setScreenSize (size) -{ - if (size.width === this._pixelsWidth - && size.height === this._pixelsHeight) - { - return; - } - - var screenKey = RenderTexturePool.SCREEN_KEY; - var textures = this.texturePool[screenKey]; - - this.enableFullScreen = size.width > 0 && size.height > 0; - - if (textures) - { - for (var j = 0; j < textures.length; j++) - { - textures[j].destroy(true); + }; + /** + * Check compability between a geometry and a program + * @protected + * @param {PIXI.Geometry} geometry - Geometry instance + * @param {PIXI.Program} program - Program instance + */ + GeometrySystem.prototype.checkCompatibility = function (geometry, program) { + // geometry must have at least all the attributes that the shader requires. + var geometryAttributes = geometry.attributes; + var shaderAttributes = program.attributeData; + for (var j in shaderAttributes) { + if (!geometryAttributes[j]) { + throw new Error("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute"); + } } - } - this.texturePool[screenKey] = []; - - this._pixelsWidth = size.width; - this._pixelsHeight = size.height; -}; - -/** - * Key that is used to store fullscreen renderTextures in a pool - * - * @static - * @const {string} - */ -RenderTexturePool.SCREEN_KEY = 'screen'; - -/* eslint-disable max-len */ - -/** - * Holds the information for a single attribute structure required to render geometry. - * - * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer} - * This can include anything from positions, uvs, normals, colors etc. - * - * @class - * @memberof PIXI - */ -var Attribute = function Attribute(buffer, size, normalized, type, stride, start, instance) -{ - if ( normalized === void 0 ) normalized = false; - if ( type === void 0 ) type = 5126; - - this.buffer = buffer; - this.size = size; - this.normalized = normalized; - this.type = type; - this.stride = stride; - this.start = start; - this.instance = instance; -}; - -/** - * Destroys the Attribute. - */ -Attribute.prototype.destroy = function destroy () -{ - this.buffer = null; -}; - -/** - * Helper function that creates an Attribute based on the information provided - * - * @static - * @param {string} buffer the id of the buffer that this attribute will look for - * @param {Number} [size=0] the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 - * @param {Boolean} [normalized=false] should the data be normalized. - * @param {Number} [start=0] How far into the array to start reading values (used for interleaving data) - * @param {Number} [type=PIXI.TYPES.FLOAT] what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available - * @param {Number} [stride=0] How far apart (in floats) the start of each value is. (used for interleaving data) - * - * @returns {PIXI.Attribute} A new {@link PIXI.Attribute} based on the information provided - */ -Attribute.from = function from (buffer, size, normalized, type, stride) -{ - return new Attribute(buffer, size, normalized, type, stride); -}; - -var UID = 0; -/* eslint-disable max-len */ - -/** - * A wrapper for data so that it can be used and uploaded by WebGL - * - * @class - * @memberof PIXI - */ -var Buffer = function Buffer(data, _static, index) -{ - if ( _static === void 0 ) _static = true; - if ( index === void 0 ) index = false; - + }; /** - * The data in the buffer, as a typed array + * Takes a geometry and program and generates a unique signature for them. * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + * @param {PIXI.Geometry} geometry - to get signature from + * @param {PIXI.Program} program - to test geometry against + * @returns {String} Unique signature of the geometry and program + * @protected */ - this.data = data || new Float32Array(1); - + GeometrySystem.prototype.getSignature = function (geometry, program) { + var attribs = geometry.attributes; + var shaderAttributes = program.attributeData; + var strings = ['g', geometry.id]; + for (var i in attribs) { + if (shaderAttributes[i]) { + strings.push(i); + } + } + return strings.join('-'); + }; /** - * A map of renderer IDs to webgl buffer + * Creates or gets Vao with the same structure as the geometry and stores it on the geometry. + * If vao is created, it is bound automatically. * - * @private - * @member {object} + * @protected + * @param {PIXI.Geometry} geometry - Instance of geometry to to generate Vao for + * @param {PIXI.Program} program - Instance of program */ - this._glBuffers = {}; - - this._updateID = 0; - - this.index = index; - - this.static = _static; - - this.id = UID++; - - this.disposeRunner = new runner.Runner('disposeBuffer', 2); -}; - -// TODO could explore flagging only a partial upload? -/** - * flags this buffer as requiring an upload to the GPU - * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView} [data] the data to update in the buffer. - */ -Buffer.prototype.update = function update (data) -{ - this.data = data || this.data; - this._updateID++; -}; - -/** - * disposes WebGL resources that are connected to this geometry - */ -Buffer.prototype.dispose = function dispose () -{ - this.disposeRunner.run(this, false); -}; - -/** - * Destroys the buffer - */ -Buffer.prototype.destroy = function destroy () -{ - this.dispose(); - - this.data = null; -}; - -/** - * Helper function that creates a buffer based on an array or TypedArray - * - * @static - * @param {ArrayBufferView | number[]} data the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array. - * @return {PIXI.Buffer} A new Buffer based on the data provided. - */ -Buffer.from = function from (data) -{ - if (data instanceof Array) - { - data = new Float32Array(data); - } - - return new Buffer(data); -}; - -function getBufferType(array) -{ - if (array.BYTES_PER_ELEMENT === 4) - { - if (array instanceof Float32Array) - { - return 'Float32Array'; + GeometrySystem.prototype.initGeometryVao = function (geometry, program) { + this.checkCompatibility(geometry, program); + var gl = this.gl; + var CONTEXT_UID = this.CONTEXT_UID; + var signature = this.getSignature(geometry, program); + var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var vao = vaoObjectHash[signature]; + if (vao) { + // this will give us easy access to the vao + vaoObjectHash[program.id] = vao; + return vao; } - else if (array instanceof Uint32Array) - { - return 'Uint32Array'; + var buffers = geometry.buffers; + var attributes = geometry.attributes; + var tempStride = {}; + var tempStart = {}; + for (var j in buffers) { + tempStride[j] = 0; + tempStart[j] = 0; } - - return 'Int32Array'; - } - else if (array.BYTES_PER_ELEMENT === 2) - { - if (array instanceof Uint16Array) - { - return 'Uint16Array'; + for (var j in attributes) { + if (!attributes[j].size && program.attributeData[j]) { + attributes[j].size = program.attributeData[j].size; + } + else if (!attributes[j].size) { + console.warn("PIXI Geometry attribute '" + j + "' size cannot be determined (likely the bound shader does not have the attribute)"); // eslint-disable-line + } + tempStride[attributes[j].buffer] += attributes[j].size * byteSizeMap$1[attributes[j].type]; } - } - else if (array.BYTES_PER_ELEMENT === 1) - { - if (array instanceof Uint8Array) - { - return 'Uint8Array'; + for (var j in attributes) { + var attribute = attributes[j]; + var attribSize = attribute.size; + if (attribute.stride === undefined) { + if (tempStride[attribute.buffer] === attribSize * byteSizeMap$1[attribute.type]) { + attribute.stride = 0; + } + else { + attribute.stride = tempStride[attribute.buffer]; + } + } + if (attribute.start === undefined) { + attribute.start = tempStart[attribute.buffer]; + tempStart[attribute.buffer] += attribSize * byteSizeMap$1[attribute.type]; + } } - } - - // TODO map out the rest of the array elements! - return null; -} - -/* eslint-disable object-shorthand */ -var map = { - Float32Array: Float32Array, - Uint32Array: Uint32Array, - Int32Array: Int32Array, - Uint8Array: Uint8Array, -}; - -function interleaveTypedArrays(arrays, sizes) -{ - var outSize = 0; - var stride = 0; - var views = {}; - - for (var i = 0; i < arrays.length; i++) - { - stride += sizes[i]; - outSize += arrays[i].length; - } - - var buffer = new ArrayBuffer(outSize * 4); - - var out = null; - var littleOffset = 0; - - for (var i$1 = 0; i$1 < arrays.length; i$1++) - { - var size = sizes[i$1]; - var array = arrays[i$1]; - - var type = getBufferType(array); - - if (!views[type]) - { - views[type] = new map[type](buffer); + vao = gl.createVertexArray(); + gl.bindVertexArray(vao); + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (var i = 0; i < buffers.length; i++) { + var buffer = buffers[i]; + if (!buffer._glBuffers[CONTEXT_UID]) { + buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer()); + this.managedBuffers[buffer.id] = buffer; + buffer.disposeRunner.add(this); + } + buffer._glBuffers[CONTEXT_UID].refCount++; } - - out = views[type]; - - for (var j = 0; j < array.length; j++) - { - var indexStart = ((j / size | 0) * stride) + littleOffset; - var index = j % size; - - out[indexStart + index] = array[j]; + // TODO - maybe make this a data object? + // lets wait to see if we need to first! + this.activateVao(geometry, program); + this._activeVao = vao; + // add it to the cache! + vaoObjectHash[program.id] = vao; + vaoObjectHash[signature] = vao; + return vao; + }; + /** + * Disposes buffer + * @param {PIXI.Buffer} buffer - buffer with data + * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray + */ + GeometrySystem.prototype.disposeBuffer = function (buffer, contextLost) { + if (!this.managedBuffers[buffer.id]) { + return; } - - littleOffset += size; - } - - return new Float32Array(buffer); -} - -var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; -var UID$1 = 0; - -/* eslint-disable object-shorthand */ -var map$1 = { - Float32Array: Float32Array, - Uint32Array: Uint32Array, - Int32Array: Int32Array, - Uint8Array: Uint8Array, - Uint16Array: Uint16Array, -}; - -/* eslint-disable max-len */ + delete this.managedBuffers[buffer.id]; + var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; + var gl = this.gl; + buffer.disposeRunner.remove(this); + if (!glBuffer) { + return; + } + if (!contextLost) { + gl.deleteBuffer(glBuffer.buffer); + } + delete buffer._glBuffers[this.CONTEXT_UID]; + }; + /** + * Disposes geometry + * @param {PIXI.Geometry} geometry - Geometry with buffers. Only VAO will be disposed + * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray + */ + GeometrySystem.prototype.disposeGeometry = function (geometry, contextLost) { + if (!this.managedGeometries[geometry.id]) { + return; + } + delete this.managedGeometries[geometry.id]; + var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var gl = this.gl; + var buffers = geometry.buffers; + geometry.disposeRunner.remove(this); + if (!vaos) { + return; + } + for (var i = 0; i < buffers.length; i++) { + var buf = buffers[i]._glBuffers[this.CONTEXT_UID]; + buf.refCount--; + if (buf.refCount === 0 && !contextLost) { + this.disposeBuffer(buffers[i], contextLost); + } + } + if (!contextLost) { + for (var vaoId in vaos) { + // delete only signatures, everything else are copies + if (vaoId[0] === 'g') { + var vao = vaos[vaoId]; + if (this._activeVao === vao) { + this.unbind(); + } + gl.deleteVertexArray(vao); + } + } + } + delete geometry.glVertexArrayObjects[this.CONTEXT_UID]; + }; + /** + * dispose all WebGL resources of all managed geometries and buffers + * @param {boolean} [contextLost=false] - If context was lost, we suppress `gl.delete` calls + */ + GeometrySystem.prototype.disposeAll = function (contextLost) { + var all = Object.keys(this.managedGeometries); + for (var i = 0; i < all.length; i++) { + this.disposeGeometry(this.managedGeometries[all[i]], contextLost); + } + all = Object.keys(this.managedBuffers); + for (var i = 0; i < all.length; i++) { + this.disposeBuffer(this.managedBuffers[all[i]], contextLost); + } + }; + /** + * Activate vertex array object + * + * @protected + * @param {PIXI.Geometry} geometry - Geometry instance + * @param {PIXI.Program} program - Shader program instance + */ + GeometrySystem.prototype.activateVao = function (geometry, program) { + var gl = this.gl; + var CONTEXT_UID = this.CONTEXT_UID; + var buffers = geometry.buffers; + var attributes = geometry.attributes; + if (geometry.indexBuffer) { + // first update the index buffer if we have one.. + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, geometry.indexBuffer._glBuffers[CONTEXT_UID].buffer); + } + var lastBuffer = null; + // add a new one! + for (var j in attributes) { + var attribute = attributes[j]; + var buffer = buffers[attribute.buffer]; + var glBuffer = buffer._glBuffers[CONTEXT_UID]; + if (program.attributeData[j]) { + if (lastBuffer !== glBuffer) { + gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); + lastBuffer = glBuffer; + } + var location = program.attributeData[j].location; + // TODO introduce state again + // we can optimise this for older devices that have no VAOs + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start); + if (attribute.instance) { + // TODO calculate instance count based of this... + if (this.hasInstance) { + gl.vertexAttribDivisor(location, 1); + } + else { + throw new Error('geometry error, GPU Instancing is not supported on this device'); + } + } + } + } + }; + /** + * Draw the geometry + * + * @param {Number} type - the type primitive to render + * @param {Number} [size] - the number of elements to be rendered + * @param {Number} [start] - Starting index + * @param {Number} [instanceCount] - the number of instances of the set of elements to execute + */ + GeometrySystem.prototype.draw = function (type, size, start, instanceCount) { + var gl = this.gl; + var geometry = this._activeGeometry; + // TODO.. this should not change so maybe cache the function? + if (geometry.indexBuffer) { + var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT; + var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; + if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) { + if (geometry.instanced) { + /* eslint-disable max-len */ + gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1); + /* eslint-enable max-len */ + } + else { + /* eslint-disable max-len */ + gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize); + /* eslint-enable max-len */ + } + } + else { + console.warn('unsupported index buffer type: uint32'); + } + } + else if (geometry.instanced) { + // TODO need a better way to calculate size.. + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } + else { + gl.drawArrays(type, start, size || geometry.getSize()); + } + return this; + }; + /** + * Unbind/reset everything + * @protected + */ + GeometrySystem.prototype.unbind = function () { + this.gl.bindVertexArray(null); + this._activeVao = null; + this._activeGeometry = null; + }; + return GeometrySystem; +}(System)); /** - * The Geometry represents a model. It consists of two components: - * - GeometryStyle - The structure of the model such as the attributes layout - * - GeometryData - the data of the model - this consists of buffers. - * This can include anything from positions, uvs, normals, colors etc. - * - * Geometry can be defined without passing in a style or data if required (thats how I prefer!) - * - * ```js - * let geometry = new PIXI.Geometry(); + * Component for masked elements * - * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); - * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2) - * geometry.addIndex([0,1,2,1,3,2]) + * Holds mask mode and temporary data about current mask * - * ``` * @class * @memberof PIXI */ -var Geometry = function Geometry(buffers, attributes) -{ - if ( buffers === void 0 ) buffers = []; - if ( attributes === void 0 ) attributes = {}; - - this.buffers = buffers; - - this.indexBuffer = null; - - this.attributes = attributes; - +var MaskData = /** @class */ (function () { /** - * A map of renderer IDs to webgl VAOs + * Create MaskData * - * @protected - * @type {object} + * @param {PIXI.DisplayObject} [maskObject=null] - object that describes the mask */ - this.glVertexArrayObjects = {}; - - this.id = UID$1++; - - this.instanced = false; - + function MaskData(maskObject) { + if (maskObject === void 0) { maskObject = null; } + /** + * Mask type + * @member {PIXI.MASK_TYPES} + */ + this.type = constants.MASK_TYPES.NONE; + /** + * Whether we know the mask type beforehand + * @member {boolean} + * @default true + */ + this.autoDetect = true; + /** + * Which element we use to mask + * @member {PIXI.DisplayObject} + */ + this.maskObject = maskObject || null; + /** + * Whether it belongs to MaskSystem pool + * @member {boolean} + */ + this.pooled = false; + /** + * Indicator of the type + * @member {boolean} + */ + this.isMaskData = true; + /** + * Stencil counter above the mask in stack + * @member {number} + * @private + */ + this._stencilCounter = 0; + /** + * Scissor counter above the mask in stack + * @member {number} + * @private + */ + this._scissorCounter = 0; + /** + * Scissor operation above the mask in stack. + * Null if _scissorCounter is zero, rectangle instance if positive. + * @member {PIXI.Rectangle} + */ + this._scissorRect = null; + /** + * Targeted element. Temporary variable set by MaskSystem + * @member {PIXI.DisplayObject} + * @private + */ + this._target = null; + } /** - * Number of instances in this geometry, pass it to `GeometrySystem.draw()` - * @member {number} - * @default 1 + * resets the mask data after popMask() */ - this.instanceCount = 1; - - this.disposeRunner = new runner.Runner('disposeGeometry', 2); - + MaskData.prototype.reset = function () { + if (this.pooled) { + this.maskObject = null; + this.type = constants.MASK_TYPES.NONE; + this.autoDetect = true; + } + this._target = null; + }; /** - * Count of existing (not destroyed) meshes that reference this geometry - * @member {number} + * copies counters from maskData above, called from pushMask() + * @param {PIXI.MaskData|null} maskAbove */ - this.refCount = 0; -}; + MaskData.prototype.copyCountersOrReset = function (maskAbove) { + if (maskAbove) { + this._stencilCounter = maskAbove._stencilCounter; + this._scissorCounter = maskAbove._scissorCounter; + this._scissorRect = maskAbove._scissorRect; + } + else { + this._stencilCounter = 0; + this._scissorCounter = 0; + this._scissorRect = null; + } + }; + return MaskData; +}()); /** -* -* Adds an attribute to the geometry -* -* @param {String} id - the name of the attribute (matching up to a shader) -* @param {PIXI.Buffer|number[]} [buffer] the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it. -* @param {Number} [size=0] the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 -* @param {Boolean} [normalized=false] should the data be normalized. -* @param {Number} [type=PIXI.TYPES.FLOAT] what type of number is the attribute. Check {PIXI.TYPES} to see the ones available -* @param {Number} [stride=0] How far apart (in floats) the start of each value is. (used for interleaving data) -* @param {Number} [start=0] How far into the array to start reading values (used for interleaving data) -* -* @return {PIXI.Geometry} returns self, useful for chaining. -*/ -Geometry.prototype.addAttribute = function addAttribute (id, buffer, size, normalized, type, stride, start, instance) -{ - if ( normalized === void 0 ) normalized = false; - if ( instance === void 0 ) instance = false; - - if (!buffer) - { - throw new Error('You must pass a buffer when creating an attribute'); - } - - // check if this is a buffer! - if (!buffer.data) - { - // its an array! - if (buffer instanceof Array) - { - buffer = new Float32Array(buffer); + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param src {string} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +function compileShader(gl, type, src) { + var shader = gl.createShader(type); + gl.shaderSource(shader, src); + gl.compileShader(shader); + return shader; +} +/** + * @method compileProgram + * @private + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations + * @return {WebGLProgram} the shader program + */ +function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + var program = gl.createProgram(); + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + // optionally, set the attributes manually for the program rather than letting WebGL decide.. + if (attributeLocations) { + for (var i in attributeLocations) { + gl.bindAttribLocation(program, attributeLocations[i], i); } - - buffer = new Buffer(buffer); } - - var ids = id.split('|'); - - if (ids.length > 1) - { - for (var i = 0; i < ids.length; i++) - { - this.addAttribute(ids[i], buffer, size, normalized, type); + gl.linkProgram(program); + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getShaderParameter(glVertShader, gl.COMPILE_STATUS)) { + console.warn(vertexSrc); + console.error(gl.getShaderInfoLog(glVertShader)); } - - return this; + if (!gl.getShaderParameter(glFragShader, gl.COMPILE_STATUS)) { + console.warn(fragmentSrc); + console.error(gl.getShaderInfoLog(glFragShader)); + } + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + gl.deleteProgram(program); + program = null; } + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + return program; +} - var bufferIndex = this.buffers.indexOf(buffer); - - if (bufferIndex === -1) - { - this.buffers.push(buffer); - bufferIndex = this.buffers.length - 1; +function booleanArray(size) { + var array = new Array(size); + for (var i = 0; i < array.length; i++) { + array[i] = false; } - - this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance); - - // assuming that if there is instanced data then this will be drawn with instancing! - this.instanced = this.instanced || instance; - - return this; -}; - + return array; +} /** - * returns the requested attribute - * - * @param {String} id the name of the attribute required - * @return {PIXI.Attribute} the attribute requested. + * @method defaultValue + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + * @private */ -Geometry.prototype.getAttribute = function getAttribute (id) -{ - return this.attributes[id]; -}; +function defaultValue(type, size) { + switch (type) { + case 'float': + return 0; + case 'vec2': + return new Float32Array(2 * size); + case 'vec3': + return new Float32Array(3 * size); + case 'vec4': + return new Float32Array(4 * size); + case 'int': + case 'sampler2D': + case 'sampler2DArray': + return 0; + case 'ivec2': + return new Int32Array(2 * size); + case 'ivec3': + return new Int32Array(3 * size); + case 'ivec4': + return new Int32Array(4 * size); + case 'bool': + return false; + case 'bvec2': + return booleanArray(2 * size); + case 'bvec3': + return booleanArray(3 * size); + case 'bvec4': + return booleanArray(4 * size); + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } + return null; +} +var unknownContext = {}; +var context = unknownContext; /** - * returns the requested buffer + * returns a little WebGL context to use for program inspection. * - * @param {String} id the name of the buffer required - * @return {PIXI.Buffer} the buffer requested. + * @static + * @private + * @returns {WebGLRenderingContext} a gl context to test with */ -Geometry.prototype.getBuffer = function getBuffer (id) -{ - return this.buffers[this.getAttribute(id).buffer]; -}; - -/** -* -* Adds an index buffer to the geometry -* The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer. -* -* @param {PIXI.Buffer|number[]} [buffer] the buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it. -* @return {PIXI.Geometry} returns self, useful for chaining. -*/ -Geometry.prototype.addIndex = function addIndex (buffer) -{ - if (!buffer.data) - { - // its an array! - if (buffer instanceof Array) - { - buffer = new Uint16Array(buffer); +function getTestContext() { + if (context === unknownContext || (context && context.isContextLost())) { + var canvas = document.createElement('canvas'); + var gl = void 0; + if (settings.settings.PREFER_ENV >= constants.ENV.WEBGL2) { + gl = canvas.getContext('webgl2', {}); } - - buffer = new Buffer(buffer); + if (!gl) { + gl = canvas.getContext('webgl', {}) + || canvas.getContext('experimental-webgl', {}); + if (!gl) { + // fail, not able to get a context + gl = null; + } + else { + // for shader testing.. + gl.getExtension('WEBGL_draw_buffers'); + } + } + context = gl; } + return context; +} - buffer.index = true; - this.indexBuffer = buffer; - - if (this.buffers.indexOf(buffer) === -1) - { - this.buffers.push(buffer); +var maxFragmentPrecision; +function getMaxFragmentPrecision() { + if (!maxFragmentPrecision) { + maxFragmentPrecision = constants.PRECISION.MEDIUM; + var gl = getTestContext(); + if (gl) { + if (gl.getShaderPrecisionFormat) { + var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); + maxFragmentPrecision = shaderFragment.precision ? constants.PRECISION.HIGH : constants.PRECISION.MEDIUM; + } + } } - - return this; -}; + return maxFragmentPrecision; +} /** - * returns the index buffer + * Sets the float precision on the shader, ensuring the device supports the request precision. + * If the precision is already present, it just ensures that the device is able to handle it. * - * @return {PIXI.Buffer} the index buffer. - */ -Geometry.prototype.getIndex = function getIndex () -{ - return this.indexBuffer; -}; - -/** - * this function modifies the structure so that all current attributes become interleaved into a single buffer - * This can be useful if your model remains static as it offers a little performance boost + * @private + * @param {string} src - The shader source + * @param {string} requestedPrecision - The request float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * @param {string} maxSupportedPrecision - The maximum precision the shader supports. * - * @return {PIXI.Geometry} returns self, useful for chaining. + * @return {string} modified shader source */ -Geometry.prototype.interleave = function interleave () -{ - // a simple check to see if buffers are already interleaved.. - if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer)) { return this; } - - // assume already that no buffers are interleaved - var arrays = []; - var sizes = []; - var interleavedBuffer = new Buffer(); - var i; - - for (i in this.attributes) - { - var attribute = this.attributes[i]; - - var buffer = this.buffers[attribute.buffer]; - - arrays.push(buffer.data); - - sizes.push((attribute.size * byteSizeMap[attribute.type]) / 4); - - attribute.buffer = 0; - } - - interleavedBuffer.data = interleaveTypedArrays(arrays, sizes); - - for (i = 0; i < this.buffers.length; i++) - { - if (this.buffers[i] !== this.indexBuffer) - { - this.buffers[i].destroy(); +function setPrecision(src, requestedPrecision, maxSupportedPrecision) { + if (src.substring(0, 9) !== 'precision') { + // no precision supplied, so PixiJS will add the requested level. + var precision = requestedPrecision; + // If highp is requested but not supported, downgrade precision to a level all devices support. + if (requestedPrecision === constants.PRECISION.HIGH && maxSupportedPrecision !== constants.PRECISION.HIGH) { + precision = constants.PRECISION.MEDIUM; } + return "precision " + precision + " float;\n" + src; } - - this.buffers = [interleavedBuffer]; - - if (this.indexBuffer) - { - this.buffers.push(this.indexBuffer); - } - - return this; -}; - -Geometry.prototype.getSize = function getSize () -{ - for (var i in this.attributes) - { - var attribute = this.attributes[i]; - var buffer = this.buffers[attribute.buffer]; - - return buffer.data.length / ((attribute.stride / 4) || attribute.size); + else if (maxSupportedPrecision !== constants.PRECISION.HIGH && src.substring(0, 15) === 'precision highp') { + // precision was supplied, but at a level this device does not support, so downgrading to mediump. + return src.replace('precision highp', 'precision mediump'); } + return src; +} - return 0; -}; - -/** - * disposes WebGL resources that are connected to this geometry - */ -Geometry.prototype.dispose = function dispose () -{ - this.disposeRunner.run(this, false); -}; - -/** - * Destroys the geometry. - */ -Geometry.prototype.destroy = function destroy () -{ - this.dispose(); - - this.buffers = null; - this.indexBuffer = null; - this.attributes = null; +var GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + mat2: 4, + mat3: 9, + mat4: 16, + sampler2D: 1, }; - /** - * returns a clone of the geometry - * - * @returns {PIXI.Geometry} a new clone of this geometry + * @private + * @method mapSize + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} */ -Geometry.prototype.clone = function clone () -{ - var geometry = new Geometry(); +function mapSize(type) { + return GLSL_TO_SIZE[type]; +} - for (var i = 0; i < this.buffers.length; i++) - { - geometry.buffers[i] = new Buffer(this.buffers[i].data.slice()); +var GL_TABLE = null; +var GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + SAMPLER_2D: 'sampler2D', + INT_SAMPLER_2D: 'sampler2D', + UNSIGNED_INT_SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + INT_SAMPLER_CUBE: 'samplerCube', + UNSIGNED_INT_SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', + INT_SAMPLER_2D_ARRAY: 'sampler2DArray', + UNSIGNED_INT_SAMPLER_2D_ARRAY: 'sampler2DArray', +}; +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function mapType(gl, type) { + if (!GL_TABLE) { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + GL_TABLE = {}; + for (var i = 0; i < typeNames.length; ++i) { + var tn = typeNames[i]; + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; + } } + return GL_TABLE[type]; +} - for (var i$1 in this.attributes) +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +// Parsers, each one of these will take a look at the type of shader property and uniform. +// if they pass the test function then the code function is called that returns a the shader upload code for that uniform. +// Shader upload code is automagically generated with these parsers. +// If no parser is valid then the default upload functions are used. +// exposing Parsers means that custom upload logic can be added to pixi's shaders. +// A good example would be a pixi rectangle can be directly set on a uniform. +// If the shader sees it it knows how to upload the rectangle structure as a vec4 +// format is as follows: +// +// { +// test: (data, uniform) => {} <--- test is this code should be used for this uniform +// code: (name, uniform) => {} <--- returns the string of the piece of code that uploads the uniform +// } +var uniformParsers = [ + // a float cache layer + { + test: function (data) { + return data.type === 'float' && data.size === 1; + }, + code: function (name) { + return "\n if(uv[\"" + name + "\"] !== ud[\"" + name + "\"].value)\n {\n ud[\"" + name + "\"].value = uv[\"" + name + "\"]\n gl.uniform1f(ud[\"" + name + "\"].location, uv[\"" + name + "\"])\n }\n "; + }, + }, + // handling samplers { - var attrib = this.attributes[i$1]; - - geometry.attributes[i$1] = new Attribute( - attrib.buffer, - attrib.size, - attrib.normalized, - attrib.type, - attrib.stride, - attrib.start, - attrib.instance - ); - } - - if (this.indexBuffer) + test: function (data) { + // eslint-disable-next-line max-len + return (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray; + }, + code: function (name) { return "t = syncData.textureCount++;\n\n renderer.texture.bind(uv[\"" + name + "\"], t);\n\n if(ud[\"" + name + "\"].value !== t)\n {\n ud[\"" + name + "\"].value = t;\n gl.uniform1i(ud[\"" + name + "\"].location, t);\n; // eslint-disable-line max-len\n }"; }, + }, + // uploading pixi matrix object to mat3 { - geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)]; - geometry.indexBuffer.index = true; - } - - return geometry; -}; - -/** - * merges an array of geometries into a new single one - * geometry attribute styles must match for this operation to work - * - * @param {PIXI.Geometry[]} geometries array of geometries to merge - * @returns {PIXI.Geometry} shiny new geometry! - */ -Geometry.merge = function merge (geometries) -{ - // todo add a geometry check! - // also a size check.. cant be too big!] - - var geometryOut = new Geometry(); - - var arrays = []; - var sizes = []; - var offsets = []; - - var geometry; - - // pass one.. get sizes.. - for (var i = 0; i < geometries.length; i++) + test: function (data, uniform) { + return data.type === 'mat3' && data.size === 1 && uniform.a !== undefined; + }, + code: function (name) { + // TODO and some smart caching dirty ids here! + return "\n gl.uniformMatrix3fv(ud[\"" + name + "\"].location, false, uv[\"" + name + "\"].toArray(true));\n "; + }, + }, + // uploading a pixi point as a vec2 with caching layer { - geometry = geometries[i]; - - for (var j = 0; j < geometry.buffers.length; j++) - { - sizes[j] = sizes[j] || 0; - sizes[j] += geometry.buffers[j].data.length; - offsets[j] = 0; - } - } - - // build the correct size arrays.. - for (var i$1 = 0; i$1 < geometry.buffers.length; i$1++) + test: function (data, uniform) { + return data.type === 'vec2' && data.size === 1 && uniform.x !== undefined; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud[\"" + name + "\"].location, v.x, v.y);\n }"; + }, + }, + // caching layer for a vec2 { - // TODO types! - arrays[i$1] = new map$1[getBufferType(geometry.buffers[i$1].data)](sizes[i$1]); - geometryOut.buffers[i$1] = new Buffer(arrays[i$1]); - } - - // pass to set data.. - for (var i$2 = 0; i$2 < geometries.length; i$2++) + test: function (data) { + return data.type === 'vec2' && data.size === 1; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud[\"" + name + "\"].location, v[0], v[1]);\n }\n "; + }, + }, + // upload a pixi rectangle as a vec4 with caching layer { - geometry = geometries[i$2]; - - for (var j$1 = 0; j$1 < geometry.buffers.length; j$1++) - { - arrays[j$1].set(geometry.buffers[j$1].data, offsets[j$1]); - offsets[j$1] += geometry.buffers[j$1].data.length; - } - } - - geometryOut.attributes = geometry.attributes; - - if (geometry.indexBuffer) + test: function (data, uniform) { + return data.type === 'vec4' && data.size === 1 && uniform.width !== undefined; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud[\"" + name + "\"].location, v.x, v.y, v.width, v.height)\n }"; + }, + }, + // a caching layer for vec4 uploading { - geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)]; - geometryOut.indexBuffer.index = true; - - var offset = 0; - var stride = 0; - var offset2 = 0; - var bufferIndexToCount = 0; + test: function (data) { + return data.type === 'vec4' && data.size === 1; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud[\"" + name + "\"].location, v[0], v[1], v[2], v[3])\n }"; + }, + } ]; - // get a buffer - for (var i$3 = 0; i$3 < geometry.buffers.length; i$3++) - { - if (geometry.buffers[i$3] !== geometry.indexBuffer) - { - bufferIndexToCount = i$3; - break; +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = location +var GLSL_TO_SINGLE_SETTERS_CACHED = { + float: "\n if(cv !== v)\n {\n cv.v = v;\n gl.uniform1f(location, v)\n }", + vec2: "\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(location, v[0], v[1])\n }", + vec3: "\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }", + vec4: 'gl.uniform4f(location, v[0], v[1], v[2], v[3])', + int: 'gl.uniform1i(location, v)', + ivec2: 'gl.uniform2i(location, v[0], v[1])', + ivec3: 'gl.uniform3i(location, v[0], v[1], v[2])', + ivec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])', + bool: 'gl.uniform1i(location, v)', + bvec2: 'gl.uniform2i(location, v[0], v[1])', + bvec3: 'gl.uniform3i(location, v[0], v[1], v[2])', + bvec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])', + mat2: 'gl.uniformMatrix2fv(location, false, v)', + mat3: 'gl.uniformMatrix3fv(location, false, v)', + mat4: 'gl.uniformMatrix4fv(location, false, v)', + sampler2D: 'gl.uniform1i(location, v)', + samplerCube: 'gl.uniform1i(location, v)', + sampler2DArray: 'gl.uniform1i(location, v)', +}; +var GLSL_TO_ARRAY_SETTERS = { + float: "gl.uniform1fv(location, v)", + vec2: "gl.uniform2fv(location, v)", + vec3: "gl.uniform3fv(location, v)", + vec4: 'gl.uniform4fv(location, v)', + mat4: 'gl.uniformMatrix4fv(location, false, v)', + mat3: 'gl.uniformMatrix3fv(location, false, v)', + mat2: 'gl.uniformMatrix2fv(location, false, v)', + int: 'gl.uniform1iv(location, v)', + ivec2: 'gl.uniform2iv(location, v)', + ivec3: 'gl.uniform3iv(location, v)', + ivec4: 'gl.uniform4iv(location, v)', + bool: 'gl.uniform1iv(location, v)', + bvec2: 'gl.uniform2iv(location, v)', + bvec3: 'gl.uniform3iv(location, v)', + bvec4: 'gl.uniform4iv(location, v)', + sampler2D: 'gl.uniform1iv(location, v)', + samplerCube: 'gl.uniform1iv(location, v)', + sampler2DArray: 'gl.uniform1iv(location, v)', +}; +function generateUniformsSync(group, uniformData) { + var funcFragments = ["\n var v = null;\n var cv = null\n var t = 0;\n var gl = renderer.gl\n "]; + for (var i in group.uniforms) { + var data = uniformData[i]; + if (!data) { + if (group.uniforms[i].group) { + funcFragments.push("\n renderer.shader.syncUniformGroup(uv[\"" + i + "\"], syncData);\n "); } + continue; } - - // figure out the stride of one buffer.. - for (var i$4 in geometry.attributes) - { - var attribute = geometry.attributes[i$4]; - - if ((attribute.buffer | 0) === bufferIndexToCount) - { - stride += ((attribute.size * byteSizeMap[attribute.type]) / 4); + var uniform = group.uniforms[i]; + var parsed = false; + for (var j = 0; j < uniformParsers.length; j++) { + if (uniformParsers[j].test(data, uniform)) { + funcFragments.push(uniformParsers[j].code(i, uniform)); + parsed = true; + break; } } - - // time to off set all indexes.. - for (var i$5 = 0; i$5 < geometries.length; i$5++) - { - var indexBufferData = geometries[i$5].indexBuffer.data; - - for (var j$2 = 0; j$2 < indexBufferData.length; j$2++) - { - geometryOut.indexBuffer.data[j$2 + offset2] += offset; - } - - offset += geometry.buffers[bufferIndexToCount].data.length / (stride); - offset2 += indexBufferData.length; + if (!parsed) { + var templateType = (data.size === 1) ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS; + var template = templateType[data.type].replace('location', "ud[\"" + i + "\"].location"); + funcFragments.push("\n cv = ud[\"" + i + "\"].value;\n v = uv[\"" + i + "\"];\n " + template + ";"); } } + /** + * the introduction of syncData is to solve an issue where textures in uniform groups are not set correctly + * the texture count was always starting from 0 in each group. This needs to increment each time a texture is used + * no matter which group is being used + * + */ + // eslint-disable-next-line no-new-func + return new Function('ud', 'uv', 'renderer', 'syncData', funcFragments.join('\n')); +} - return geometryOut; -}; +var fragTemplate = [ + 'precision mediump float;', + 'void main(void){', + 'float test = 0.1;', + '%forloop%', + 'gl_FragColor = vec4(0.0);', + '}' ].join('\n'); +function generateIfTestSrc(maxIfs) { + var src = ''; + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + if (i < maxIfs - 1) { + src += "if(test == " + i + ".0){}"; + } + } + return src; +} +function checkMaxIfStatementsInShader(maxIfs, gl) { + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + var shader = gl.createShader(gl.FRAGMENT_SHADER); + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = (maxIfs / 2) | 0; + } + else { + // valid! + break; + } + } + return maxIfs; +} +// Cache the result to prevent running this over and over +var unsafeEval; /** - * Helper class to create a quad + * Not all platforms allow to generate function code (e.g., `new Function`). + * this provides the platform-level detection. * - * @class - * @memberof PIXI + * @private + * @returns {boolean} */ -var Quad = /*@__PURE__*/(function (Geometry) { - function Quad() - { - Geometry.call(this); - - this.addAttribute('aVertexPosition', [ - 0, 0, - 1, 0, - 1, 1, - 0, 1 ]) - .addIndex([0, 1, 3, 2]); +function unsafeEvalSupported() { + if (typeof unsafeEval === 'boolean') { + return unsafeEval; + } + try { + /* eslint-disable no-new-func */ + var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;'); + /* eslint-enable no-new-func */ + unsafeEval = func({ a: 'b' }, 'a', 'b') === true; + } + catch (e) { + unsafeEval = false; } + return unsafeEval; +} - if ( Geometry ) Quad.__proto__ = Geometry; - Quad.prototype = Object.create( Geometry && Geometry.prototype ); - Quad.prototype.constructor = Quad; +var defaultFragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"; - return Quad; -}(Geometry)); +var defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"; +var UID$3 = 0; +var nameCache = {}; /** - * Helper class to create a quad with uvs like in v4 + * Helper class to create a shader program. * * @class * @memberof PIXI - * @extends PIXI.Geometry */ -var QuadUv = /*@__PURE__*/(function (Geometry) { - function QuadUv() - { - Geometry.call(this); - +var Program = /** @class */ (function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {string} [name] - Name for shader + */ + function Program(vertexSrc, fragmentSrc, name) { + if (name === void 0) { name = 'pixi-shader'; } + this.id = UID$3++; /** - * An array of vertices + * The vertex shader. * - * @member {Float32Array} + * @member {string} */ - this.vertices = new Float32Array([ - -1, -1, - 1, -1, - 1, 1, - -1, 1 ]); - + this.vertexSrc = vertexSrc || Program.defaultVertexSrc; /** - * The Uvs of the quad + * The fragment shader. * - * @member {Float32Array} + * @member {string} */ - this.uvs = new Float32Array([ - 0, 0, - 1, 0, - 1, 1, - 0, 1 ]); - - this.vertexBuffer = new Buffer(this.vertices); - this.uvBuffer = new Buffer(this.uvs); - - this.addAttribute('aVertexPosition', this.vertexBuffer) - .addAttribute('aTextureCoord', this.uvBuffer) - .addIndex([0, 1, 2, 0, 2, 3]); + this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc; + this.vertexSrc = this.vertexSrc.trim(); + this.fragmentSrc = this.fragmentSrc.trim(); + if (this.vertexSrc.substring(0, 8) !== '#version') { + name = name.replace(/\s+/g, '-'); + if (nameCache[name]) { + nameCache[name]++; + name += "-" + nameCache[name]; + } + else { + nameCache[name] = 1; + } + this.vertexSrc = "#define SHADER_NAME " + name + "\n" + this.vertexSrc; + this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + this.fragmentSrc; + this.vertexSrc = setPrecision(this.vertexSrc, settings.settings.PRECISION_VERTEX, constants.PRECISION.HIGH); + this.fragmentSrc = setPrecision(this.fragmentSrc, settings.settings.PRECISION_FRAGMENT, getMaxFragmentPrecision()); + } + // currently this does not extract structs only default types + this.extractData(this.vertexSrc, this.fragmentSrc); + // this is where we store shader references.. + this.glPrograms = {}; + this.syncUniforms = null; } - - if ( Geometry ) QuadUv.__proto__ = Geometry; - QuadUv.prototype = Object.create( Geometry && Geometry.prototype ); - QuadUv.prototype.constructor = QuadUv; - /** - * Maps two Rectangle to the quad. + * Extracts the data for a buy creating a small test program + * or reading the src directly. + * @protected * - * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle - * @param {PIXI.Rectangle} destinationFrame - the second rectangle - * @return {PIXI.Quad} Returns itself. + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. */ - QuadUv.prototype.map = function map (targetTextureFrame, destinationFrame) - { - var x = 0; // destinationFrame.x / targetTextureFrame.width; - var y = 0; // destinationFrame.y / targetTextureFrame.height; - - this.uvs[0] = x; - this.uvs[1] = y; - - this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width); - this.uvs[3] = y; - - this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width); - this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height); - - this.uvs[6] = x; - this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height); - - x = destinationFrame.x; - y = destinationFrame.y; - - this.vertices[0] = x; - this.vertices[1] = y; - - this.vertices[2] = x + destinationFrame.width; - this.vertices[3] = y; - - this.vertices[4] = x + destinationFrame.width; - this.vertices[5] = y + destinationFrame.height; - - this.vertices[6] = x; - this.vertices[7] = y + destinationFrame.height; - - this.invalidate(); - - return this; + Program.prototype.extractData = function (vertexSrc, fragmentSrc) { + var gl = getTestContext(); + if (gl) { + var program = compileProgram(gl, vertexSrc, fragmentSrc); + this.attributeData = this.getAttributeData(program, gl); + this.uniformData = this.getUniformData(program, gl); + gl.deleteProgram(program); + } + else { + this.uniformData = {}; + this.attributeData = {}; + } }; - /** - * legacy upload method, just marks buffers dirty - * @returns {PIXI.QuadUv} Returns itself. - */ - QuadUv.prototype.invalidate = function invalidate () - { - this.vertexBuffer._updateID++; - this.uvBuffer._updateID++; - - return this; + * returns the attribute data from the program + * @private + * + * @param {WebGLProgram} [program] - the WebGL program + * @param {WebGLRenderingContext} [gl] - the WebGL context + * + * @returns {object} the attribute data for this program + */ + Program.prototype.getAttributeData = function (program, gl) { + var attributes = {}; + var attributesArray = []; + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (var i = 0; i < totalAttributes; i++) { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + /*eslint-disable */ + var data = { + type: type, + name: attribData.name, + size: mapSize(type), + location: 0, + }; + /* eslint-enable */ + attributes[attribData.name] = data; + attributesArray.push(data); + } + attributesArray.sort(function (a, b) { return (a.name > b.name) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow + for (var i = 0; i < attributesArray.length; i++) { + attributesArray[i].location = i; + } + return attributes; }; - - return QuadUv; -}(Geometry)); - -var UID$2 = 0; - -/** - * Uniform group holds uniform map and some ID's for work - * - * @class - * @memberof PIXI - */ -var UniformGroup = function UniformGroup(uniforms, _static) -{ /** - * uniform values - * @member {object} - * @readonly - */ - this.uniforms = uniforms; - - /** - * Its a group and not a single uniforms - * @member {boolean} - * @readonly - * @default true - */ - this.group = true; - - // lets generate this when the shader ? - this.syncUniforms = {}; - - /** - * dirty version - * @protected - * @member {number} - */ - this.dirtyId = 0; - - /** - * unique id - * @protected - * @member {number} - */ - this.id = UID$2++; - + * returns the uniform data from the program + * @private + * + * @param {webGL-program} [program] - the webgl program + * @param {context} [gl] - the WebGL context + * + * @returns {object} the uniform data for this program + */ + Program.prototype.getUniformData = function (program, gl) { + var uniforms = {}; + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + // TODO expose this as a prop? + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + for (var i = 0; i < totalUniforms; i++) { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]$/, ''); + var isArray = uniformData.name.match(/\[.*?\]$/); + var type = mapType(gl, uniformData.type); + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray: isArray, + value: defaultValue(type, uniformData.size), + }; + /* eslint-enable */ + } + return uniforms; + }; + Object.defineProperty(Program, "defaultVertexSrc", { + /** + * The default vertex shader source + * + * @static + * @constant + * @member {string} + */ + get: function () { + return defaultVertex; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Program, "defaultFragmentSrc", { + /** + * The default fragment shader source + * + * @static + * @constant + * @member {string} + */ + get: function () { + return defaultFragment; + }, + enumerable: false, + configurable: true + }); /** - * Uniforms wont be changed after creation - * @member {boolean} + * A short hand function to create a program based of a vertex and fragment shader + * this method will also check to see if there is a cached program. + * + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {string} [name=pixi-shader] - Name for shader + * + * @returns {PIXI.Program} an shiny new Pixi shader! */ - this.static = !!_static; -}; - -UniformGroup.prototype.update = function update () -{ - this.dirtyId++; -}; - -UniformGroup.prototype.add = function add (name, uniforms, _static) -{ - this.uniforms[name] = new UniformGroup(uniforms, _static); -}; - -UniformGroup.from = function from (uniforms, _static) -{ - return new UniformGroup(uniforms, _static); -}; + Program.from = function (vertexSrc, fragmentSrc, name) { + var key = vertexSrc + fragmentSrc; + var program = utils.ProgramCache[key]; + if (!program) { + utils.ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name); + } + return program; + }; + return Program; +}()); /** - * System plugin to the renderer to manage filter states. + * A helper class for shaders * * @class - * @private + * @memberof PIXI */ -var FilterState = function FilterState() -{ - this.renderTexture = null; - +var Shader = /** @class */ (function () { /** - * Target of the filters - * We store for case when custom filter wants to know the element it was applied on - * @member {PIXI.DisplayObject} - * @private + * @param {PIXI.Program} [program] - The program the shader will use. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. */ - this.target = null; - + function Shader(program, uniforms) { + /** + * Program that the shader uses + * + * @member {PIXI.Program} + */ + this.program = program; + // lets see whats been passed in + // uniforms should be converted to a uniform group + if (uniforms) { + if (uniforms instanceof UniformGroup) { + this.uniformGroup = uniforms; + } + else { + this.uniformGroup = new UniformGroup(uniforms); + } + } + else { + this.uniformGroup = new UniformGroup({}); + } + // time to build some getters and setters! + // I guess down the line this could sort of generate an instruction list rather than use dirty ids? + // does the trick for now though! + for (var i in program.uniformData) { + if (this.uniformGroup.uniforms[i] instanceof Array) { + this.uniformGroup.uniforms[i] = new Float32Array(this.uniformGroup.uniforms[i]); + } + } + } + // TODO move to shader system.. + Shader.prototype.checkUniformExists = function (name, group) { + if (group.uniforms[name]) { + return true; + } + for (var i in group.uniforms) { + var uniform = group.uniforms[i]; + if (uniform.group) { + if (this.checkUniformExists(name, uniform)) { + return true; + } + } + } + return false; + }; + Shader.prototype.destroy = function () { + // usage count on programs? + // remove if not used! + this.uniformGroup = null; + }; + Object.defineProperty(Shader.prototype, "uniforms", { + /** + * Shader uniform values, shortcut for `uniformGroup.uniforms` + * @readonly + * @member {object} + */ + get: function () { + return this.uniformGroup.uniforms; + }, + enumerable: false, + configurable: true + }); /** - * Compatibility with PixiJS v4 filters - * @member {boolean} - * @default false - * @private + * A short hand function to create a shader based of a vertex and fragment shader + * + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + * + * @returns {PIXI.Shader} an shiny new Pixi shader! */ - this.legacy = false; + Shader.from = function (vertexSrc, fragmentSrc, uniforms) { + var program = Program.from(vertexSrc, fragmentSrc); + return new Shader(program, uniforms); + }; + return Shader; +}()); - /** - * Resolution of filters - * @member {number} - * @default 1 - * @private - */ - this.resolution = 1; +/* eslint-disable max-len */ +var BLEND = 0; +var OFFSET = 1; +var CULLING = 2; +var DEPTH_TEST = 3; +var WINDING = 4; +/** + * This is a WebGL state, and is is passed The WebGL StateManager. + * + * Each mesh rendered may require WebGL to be in a different state. + * For example you may want different blend mode or to enable polygon offsets + * + * @class + * @memberof PIXI + */ +var State = /** @class */ (function () { + function State() { + this.data = 0; + this.blendMode = constants.BLEND_MODES.NORMAL; + this.polygonOffset = 0; + this.blend = true; + // this.depthTest = true; + } + Object.defineProperty(State.prototype, "blend", { + /** + * Activates blending of the computed fragment color values + * + * @member {boolean} + */ + get: function () { + return !!(this.data & (1 << BLEND)); + }, + set: function (value) { + if (!!(this.data & (1 << BLEND)) !== value) { + this.data ^= (1 << BLEND); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "offsets", { + /** + * Activates adding an offset to depth values of polygon's fragments + * + * @member {boolean} + * @default false + */ + get: function () { + return !!(this.data & (1 << OFFSET)); + }, + set: function (value) { + if (!!(this.data & (1 << OFFSET)) !== value) { + this.data ^= (1 << OFFSET); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "culling", { + /** + * Activates culling of polygons. + * + * @member {boolean} + * @default false + */ + get: function () { + return !!(this.data & (1 << CULLING)); + }, + set: function (value) { + if (!!(this.data & (1 << CULLING)) !== value) { + this.data ^= (1 << CULLING); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "depthTest", { + /** + * Activates depth comparisons and updates to the depth buffer. + * + * @member {boolean} + * @default false + */ + get: function () { + return !!(this.data & (1 << DEPTH_TEST)); + }, + set: function (value) { + if (!!(this.data & (1 << DEPTH_TEST)) !== value) { + this.data ^= (1 << DEPTH_TEST); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "clockwiseFrontFace", { + /** + * Specifies whether or not front or back-facing polygons can be culled. + * @member {boolean} + * @default false + */ + get: function () { + return !!(this.data & (1 << WINDING)); + }, + set: function (value) { + if (!!(this.data & (1 << WINDING)) !== value) { + this.data ^= (1 << WINDING); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "blendMode", { + /** + * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * Setting this mode to anything other than NO_BLEND will automatically switch blending on. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + get: function () { + return this._blendMode; + }, + set: function (value) { + this.blend = (value !== constants.BLEND_MODES.NONE); + this._blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "polygonOffset", { + /** + * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill. + * + * @member {number} + * @default 0 + */ + get: function () { + return this._polygonOffset; + }, + set: function (value) { + this.offsets = !!value; + this._polygonOffset = value; + }, + enumerable: false, + configurable: true + }); + State.for2d = function () { + var state = new State(); + state.depthTest = false; + state.blend = true; + return state; + }; + return State; +}()); - // next three fields are created only for root - // re-assigned for everything else +var defaultVertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; - /** - * Source frame - * @member {PIXI.Rectangle} - * @private - */ - this.sourceFrame = new math.Rectangle(); +var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"; +/** + * Filter is a special type of WebGL shader that is applied to the screen. + * + * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the + * {@link PIXI.filters.BlurFilter BlurFilter}. + * + * ### Usage + * Filters can be applied to any DisplayObject or Container. + * PixiJS' `FilterSystem` renders the container into temporary Framebuffer, + * then filter renders it to the screen. + * Multiple filters can be added to the `filters` array property and stacked on each other. + * + * ``` + * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 }); + * const container = new PIXI.Container(); + * container.filters = [filter]; + * ``` + * + * ### Previous Version Differences + * + * In PixiJS **v3**, a filter was always applied to _whole screen_. + * + * In PixiJS **v4**, a filter can be applied _only part of the screen_. + * Developers had to create a set of uniforms to deal with coordinates. + * + * In PixiJS **v5** combines _both approaches_. + * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers, + * bringing those extra uniforms into account. + * + * Also be aware that we have changed default vertex shader, please consult + * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. + * + * ### Built-in Uniforms + * + * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`, + * and `projectionMatrix` uniform maps it to the gl viewport. + * + * **uSampler** + * + * The most important uniform is the input texture that container was rendered into. + * _Important note: as with all Framebuffers in PixiJS, both input and output are + * premultiplied by alpha._ + * + * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`. + * Use it to sample the input. + * + * ``` + * const fragment = ` + * varying vec2 vTextureCoord; + * uniform sampler2D uSampler; + * void main(void) + * { + * gl_FragColor = texture2D(uSampler, vTextureCoord); + * } + * `; + * + * const myFilter = new PIXI.Filter(null, fragment); + * ``` + * + * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}. + * + * **outputFrame** + * + * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates. + * It's the same as `renderer.screen` for a fullscreen filter. + * Only a part of `outputFrame.zw` size of temporary Framebuffer is used, + * `(0, 0, outputFrame.width, outputFrame.height)`, + * + * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute. + * To calculate vertex position in screen space using normalized (0-1) space: + * + * ``` + * vec4 filterVertexPosition( void ) + * { + * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy; + * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); + * } + * ``` + * + * **inputSize** + * + * Temporary framebuffer is different, it can be either the size of screen, either power-of-two. + * The `inputSize.xy` are size of temporary framebuffer that holds input. + * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader. + * + * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter. + * + * To calculate input normalized coordinate, you have to map it to filter normalized space. + * Multiply by `outputFrame.zw` to get input coordinate. + * Divide by `inputSize.xy` to get input normalized coordinate. + * + * ``` + * vec2 filterTextureCoord( void ) + * { + * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy + * } + * ``` + * **resolution** + * + * The `resolution` is the ratio of screen (CSS) pixels to real pixels. + * + * **inputPixel** + * + * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution` + * `inputPixel.zw` is inverted `inputPixel.xy`. + * + * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}. + * + * **inputClamp** + * + * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour. + * For displacements, coordinates has to be clamped. + * + * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer + * `inputClamp.zw` is bottom-right pixel center. + * + * ``` + * vec4 color = texture2D(uSampler, clamp(modifigedTextureCoord, inputClamp.xy, inputClamp.zw)) + * ``` + * OR + * ``` + * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw)) + * ``` + * + * ### Additional Information + * + * Complete documentation on Filter usage is located in the + * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. + * + * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded + * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var Filter = /** @class */ (function (_super) { + __extends(Filter, _super); /** - * Destination frame - * @member {PIXI.Rectangle} - * @private + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. */ - this.destinationFrame = new math.Rectangle(); - + function Filter(vertexSrc, fragmentSrc, uniforms) { + var _this = this; + var program = Program.from(vertexSrc || Filter.defaultVertexSrc, fragmentSrc || Filter.defaultFragmentSrc); + _this = _super.call(this, program, uniforms) || this; + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + _this.padding = 0; + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + _this.resolution = settings.settings.FILTER_RESOLUTION; + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + _this.enabled = true; + /** + * If enabled, PixiJS will fit the filter area into boundaries for better performance. + * Switch it off if it does not work for specific shader. + * + * @member {boolean} + */ + _this.autoFit = true; + /** + * Legacy filters use position and uvs from attributes + * @member {boolean} + * @readonly + */ + _this.legacy = !!_this.program.attributeData.aTextureCoord; + /** + * The WebGL state the filter requires to render + * @member {PIXI.State} + */ + _this.state = new State(); + return _this; + } /** - * Collection of filters - * @member {PIXI.Filter[]} - * @private + * Applies the filter + * + * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTexture} input - The input render target. + * @param {PIXI.RenderTexture} output - The target to output to. + * @param {PIXI.CLEAR_MODES} clearMode - Should the output be cleared before rendering to it. + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution */ - this.filters = []; -}; + Filter.prototype.apply = function (filterManager, input, output, clearMode, _currentState) { + // do as you please! + filterManager.applyFilter(this, input, output, clearMode); + // or just do a regular render.. + }; + Object.defineProperty(Filter.prototype, "blendMode", { + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this.state.blendMode; + }, + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter, "defaultVertexSrc", { + /** + * The default vertex shader source + * + * @static + * @type {string} + * @constant + */ + get: function () { + return defaultVertex$1; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter, "defaultFragmentSrc", { + /** + * The default fragment shader source + * + * @static + * @type {string} + * @constant + */ + get: function () { + return defaultFragment$1; + }, + enumerable: false, + configurable: true + }); + return Filter; +}(Shader)); -/** - * clears the state - * @private - */ -FilterState.prototype.clear = function clear () -{ - this.target = null; - this.filters = null; - this.renderTexture = null; -}; +var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n"; + +var fragment = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n"; +var tempMat = new math.Matrix(); /** - * System plugin to the renderer to manage the filters. + * Class controls uv mapping from Texture normal space to BaseTexture normal space. + * + * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite. + * + * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture. + * If you want to add support for texture region of certain feature or filter, that's what you're looking for. * + * Takes track of Texture changes through `_lastTextureID` private field. + * Use `update()` method call to track it from outside. + * + * @see PIXI.Texture + * @see PIXI.Mesh + * @see PIXI.TilingSprite * @class - * @memberof PIXI.systems - * @extends PIXI.System + * @memberof PIXI */ -var FilterSystem = /*@__PURE__*/(function (System) { - function FilterSystem(renderer) - { - System.call(this, renderer); - +var TextureMatrix = /** @class */ (function () { + /** + * + * @param {PIXI.Texture} texture - observed texture + * @param {number} [clampMargin] - Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureMatrix(texture, clampMargin) { + this._texture = texture; /** - * List of filters for the FilterSystem - * @member {Object[]} + * Matrix operation that converts texture region coords to texture coords + * @member {PIXI.Matrix} * @readonly */ - this.defaultFilterStack = [{}]; - + this.mapCoord = new math.Matrix(); /** - * stores a bunch of PO2 textures used for filtering - * @member {Object} + * Clamp region for normalized coords, left-top pixel center in xy , bottom-right in zw. + * Calculated based on clampOffset. + * @member {Float32Array} + * @readonly */ - this.texturePool = new RenderTexturePool(); - - this.texturePool.setScreenSize(renderer.view); - + this.uClampFrame = new Float32Array(4); /** - * a pool for storing filter states, save us creating new ones each tick - * @member {Object[]} + * Normalized clamp offset. + * Calculated based on clampOffset. + * @member {Float32Array} + * @readonly */ - this.statePool = []; - + this.uClampOffset = new Float32Array(2); /** - * A very simple geometry used when drawing a filter effect to the screen - * @member {PIXI.Quad} + * Tracks Texture frame changes + * @member {number} + * @protected */ - this.quad = new Quad(); - + this._textureID = -1; /** - * Quad UVs - * @member {PIXI.QuadUv} + * Tracks Texture frame changes + * @member {number} + * @protected */ - this.quadUv = new QuadUv(); - + this._updateID = 0; /** - * Temporary rect for maths - * @type {PIXI.Rectangle} + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} */ - this.tempRect = new math.Rectangle(); - + this.clampOffset = 0; /** - * Active state - * @member {object} + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} */ - this.activeState = {}; - + this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin; /** - * This uniform group is attached to filter uniforms when used - * @member {PIXI.UniformGroup} - * @property {PIXI.Rectangle} outputFrame - * @property {Float32Array} inputSize - * @property {Float32Array} inputPixel - * @property {Float32Array} inputClamp - * @property {Number} resolution - * @property {Float32Array} filterArea - * @property {Fload32Array} filterClamp + * If texture size is the same as baseTexture + * @member {boolean} + * @default false + * @readonly */ - this.globalUniforms = new UniformGroup({ - outputFrame: this.tempRect, - inputSize: new Float32Array(4), - inputPixel: new Float32Array(4), - inputClamp: new Float32Array(4), - resolution: 1, - - // legacy variables - filterArea: new Float32Array(4), - filterClamp: new Float32Array(4), - }, true); - - this._pixelsWidth = renderer.view.width; - this._pixelsHeight = renderer.view.height; + this.isSimple = false; } - - if ( System ) FilterSystem.__proto__ = System; - FilterSystem.prototype = Object.create( System && System.prototype ); - FilterSystem.prototype.constructor = FilterSystem; - + Object.defineProperty(TextureMatrix.prototype, "texture", { + /** + * texture property + * @member {PIXI.Texture} + */ + get: function () { + return this._texture; + }, + set: function (value) { + this._texture = value; + this._textureID = -1; + }, + enumerable: false, + configurable: true + }); /** - * Adds a new filter to the System. - * - * @param {PIXI.DisplayObject} target - The target of the filter to render. - * @param {PIXI.Filter[]} filters - The filters to apply. + * Multiplies uvs array to transform + * @param {Float32Array} uvs - mesh uvs + * @param {Float32Array} [out=uvs] output + * @returns {Float32Array} output */ - FilterSystem.prototype.push = function push (target, filters) - { - var renderer = this.renderer; - var filterStack = this.defaultFilterStack; - var state = this.statePool.pop() || new FilterState(); - - var resolution = filters[0].resolution; - var padding = filters[0].padding; - var autoFit = filters[0].autoFit; - var legacy = filters[0].legacy; - - for (var i = 1; i < filters.length; i++) - { - var filter = filters[i]; - - // lets use the lowest resolution.. - resolution = Math.min(resolution, filter.resolution); - // and the largest amount of padding! - padding = Math.max(padding, filter.padding); - // only auto fit if all filters are autofit - autoFit = autoFit || filter.autoFit; - - legacy = legacy || filter.legacy; - } - - if (filterStack.length === 1) - { - this.defaultFilterStack[0].renderTexture = renderer.renderTexture.current; + TextureMatrix.prototype.multiplyUvs = function (uvs, out) { + if (out === undefined) { + out = uvs; } - - filterStack.push(state); - - state.resolution = resolution; - - state.legacy = legacy; - - state.target = target; - - state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true)); - - state.sourceFrame.pad(padding); - if (autoFit) - { - state.sourceFrame.fit(this.renderer.renderTexture.sourceFrame); + var mat = this.mapCoord; + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + out[i] = (x * mat.a) + (y * mat.c) + mat.tx; + out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty; } - - // round to whole number based on resolution - state.sourceFrame.ceil(resolution); - - state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution); - state.filters = filters; - - state.destinationFrame.width = state.renderTexture.width; - state.destinationFrame.height = state.renderTexture.height; - - state.renderTexture.filterFrame = state.sourceFrame; - - renderer.renderTexture.bind(state.renderTexture, state.sourceFrame);// /, state.destinationFrame); - renderer.renderTexture.clear(); + return out; }; - /** - * Pops off the filter and applies it. - * + * updates matrices if texture was changed + * @param {boolean} [forceUpdate=false] - if true, matrices will be updated any case + * @returns {boolean} whether or not it was updated */ - FilterSystem.prototype.pop = function pop () - { - var filterStack = this.defaultFilterStack; - var state = filterStack.pop(); - var filters = state.filters; - - this.activeState = state; - - var globalUniforms = this.globalUniforms.uniforms; - - globalUniforms.outputFrame = state.sourceFrame; - globalUniforms.resolution = state.resolution; - - var inputSize = globalUniforms.inputSize; - var inputPixel = globalUniforms.inputPixel; - var inputClamp = globalUniforms.inputClamp; - - inputSize[0] = state.destinationFrame.width; - inputSize[1] = state.destinationFrame.height; - inputSize[2] = 1.0 / inputSize[0]; - inputSize[3] = 1.0 / inputSize[1]; - - inputPixel[0] = inputSize[0] * state.resolution; - inputPixel[1] = inputSize[1] * state.resolution; - inputPixel[2] = 1.0 / inputPixel[0]; - inputPixel[3] = 1.0 / inputPixel[1]; - - inputClamp[0] = 0.5 * inputPixel[2]; - inputClamp[1] = 0.5 * inputPixel[3]; - inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]); - inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]); - - // only update the rect if its legacy.. - if (state.legacy) - { - var filterArea = globalUniforms.filterArea; - - filterArea[0] = state.destinationFrame.width; - filterArea[1] = state.destinationFrame.height; - filterArea[2] = state.sourceFrame.x; - filterArea[3] = state.sourceFrame.y; - - globalUniforms.filterClamp = globalUniforms.inputClamp; - } - - this.globalUniforms.update(); - - var lastState = filterStack[filterStack.length - 1]; - - if (filters.length === 1) - { - filters[0].apply(this, state.renderTexture, lastState.renderTexture, false, state); - - this.returnFilterTexture(state.renderTexture); + TextureMatrix.prototype.update = function (forceUpdate) { + var tex = this._texture; + if (!tex || !tex.valid) { + return false; } - else - { - var flip = state.renderTexture; - var flop = this.getOptimalFilterTexture( - flip.width, - flip.height, - state.resolution - ); - - flop.filterFrame = flip.filterFrame; - - var i = 0; - - for (i = 0; i < filters.length - 1; ++i) - { - filters[i].apply(this, flip, flop, true, state); - - var t = flip; - - flip = flop; - flop = t; - } - - filters[i].apply(this, flip, lastState.renderTexture, false, state); - - this.returnFilterTexture(flip); - this.returnFilterTexture(flop); + if (!forceUpdate + && this._textureID === tex._updateID) { + return false; } - - state.clear(); - this.statePool.push(state); + this._textureID = tex._updateID; + this._updateID++; + var uvs = tex._uvs; + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + var orig = tex.orig; + var trim = tex.trim; + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + this.isSimple = tex._frame.width === texBase.width + && tex._frame.height === texBase.height + && tex.rotate === 0; + return true; }; + return TextureMatrix; +}()); +/** + * This handles a Sprite acting as a mask, as opposed to a Graphic. + * + * WebGL only. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = /** @class */ (function (_super) { + __extends(SpriteMaskFilter, _super); /** - * Draws a filter. + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + var _this = this; + var maskMatrix = new math.Matrix(); + _this = _super.call(this, vertex, fragment) || this; + sprite.renderable = false; + /** + * Sprite mask + * @member {PIXI.Sprite} + */ + _this.maskSprite = sprite; + /** + * Mask matrix + * @member {PIXI.Matrix} + */ + _this.maskMatrix = maskMatrix; + return _this; + } + /** + * Applies the filter * - * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from * @param {PIXI.RenderTexture} input - The input render target. * @param {PIXI.RenderTexture} output - The target to output to. - * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {PIXI.CLEAR_MODES} clearMode - Should the output be cleared before rendering to it. */ - FilterSystem.prototype.applyFilter = function applyFilter (filter, input, output, clear) - { - var renderer = this.renderer; - - renderer.renderTexture.bind(output, output ? output.filterFrame : null); - - if (clear) - { - // gl.disable(gl.SCISSOR_TEST); - renderer.renderTexture.clear(); - // gl.enable(gl.SCISSOR_TEST); - } - - // set the uniforms.. - filter.uniforms.uSampler = input; - filter.uniforms.filterGlobals = this.globalUniforms; - - // TODO make it so that the order of this does not matter.. - // because it does at the moment cos of global uniforms. - // they need to get resynced - - renderer.state.set(filter.state); - renderer.shader.bind(filter); - - if (filter.legacy) - { - this.quadUv.map(input._frame, input.filterFrame); - - renderer.geometry.bind(this.quadUv); - renderer.geometry.draw(constants.DRAW_MODES.TRIANGLES); + SpriteMaskFilter.prototype.apply = function (filterManager, input, output, clearMode) { + var maskSprite = this.maskSprite; + var tex = maskSprite._texture; + if (!tex.valid) { + return; } - else - { - renderer.geometry.bind(this.quad); - renderer.geometry.draw(constants.DRAW_MODES.TRIANGLE_STRIP); + if (!tex.uvMatrix) { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.uvMatrix = new TextureMatrix(tex, 0.0); } + tex.uvMatrix.update(); + this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0; + this.uniforms.mask = tex; + // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend` + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite) + .prepend(tex.uvMatrix.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.uvMatrix.uClampFrame; + filterManager.applyFilter(this, input, output, clearMode); }; + return SpriteMaskFilter; +}(Filter)); +/** + * System plugin to the renderer to manage masks. + * + * @class + * @extends PIXI.System + * @memberof PIXI.systems + */ +var MaskSystem = /** @class */ (function (_super) { + __extends(MaskSystem, _super); /** - * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_. - * - * Use `outputMatrix * vTextureCoord` in the shader. - * - * @param {PIXI.Matrix} outputMatrix - The matrix to output to. - * @param {PIXI.Sprite} sprite - The sprite to map to. - * @return {PIXI.Matrix} The mapped matrix. + * @param {PIXI.Renderer} renderer - The renderer this System works for. */ - FilterSystem.prototype.calculateSpriteMatrix = function calculateSpriteMatrix (outputMatrix, sprite) - { - var ref = this.activeState; - var sourceFrame = ref.sourceFrame; - var destinationFrame = ref.destinationFrame; - var ref$1 = sprite._texture; - var orig = ref$1.orig; - var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, - destinationFrame.height, sourceFrame.x, sourceFrame.y); - var worldTransform = sprite.worldTransform.copyTo(math.Matrix.TEMP_MATRIX); - - worldTransform.invert(); - mappedMatrix.prepend(worldTransform); - mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); - mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); - - return mappedMatrix; - }; - + function MaskSystem(renderer) { + var _this = _super.call(this, renderer) || this; + /** + * Enable scissor + * @member {boolean} + * @readonly + */ + _this.enableScissor = false; + /** + * Pool of used sprite mask filters + * @member {PIXI.SpriteMaskFilter[]} + * @readonly + */ + _this.alphaMaskPool = []; + /** + * Pool of mask data + * @member {PIXI.MaskData[]} + * @readonly + */ + _this.maskDataPool = []; + _this.maskStack = []; + /** + * Current index of alpha mask pool + * @member {number} + * @default 0 + * @readonly + */ + _this.alphaMaskIndex = 0; + return _this; + } /** - * Destroys this Filter System. + * Changes the mask stack that is used by this System. + * + * @param {PIXI.MaskData[]} maskStack - The mask stack */ - FilterSystem.prototype.destroy = function destroy () - { - // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem - this.texturePool.clear(false); + MaskSystem.prototype.setMaskStack = function (maskStack) { + this.maskStack = maskStack; + this.renderer.scissor.setMaskStack(maskStack); + this.renderer.stencil.setMaskStack(maskStack); }; - /** - * Gets a Power-of-Two render texture or fullScreen texture + * Applies the Mask and adds it to the current filter stack. + * Renderer batch must be flushed beforehand. * - * @protected - * @param {number} minWidth - The minimum width of the render texture in real pixels. - * @param {number} minHeight - The minimum height of the render texture in real pixels. - * @param {number} [resolution=1] - The resolution of the render texture. - * @return {PIXI.RenderTexture} The new render texture. + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskData - The masking data. */ - FilterSystem.prototype.getOptimalFilterTexture = function getOptimalFilterTexture (minWidth, minHeight, resolution) - { - if ( resolution === void 0 ) resolution = 1; - - return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution); + MaskSystem.prototype.push = function (target, maskDataOrTarget) { + var maskData = maskDataOrTarget; + if (!maskData.isMaskData) { + var d = this.maskDataPool.pop() || new MaskData(); + d.pooled = true; + d.maskObject = maskDataOrTarget; + maskData = d; + } + if (maskData.autoDetect) { + this.detect(maskData); + } + maskData.copyCountersOrReset(this.maskStack[this.maskStack.length - 1]); + maskData._target = target; + switch (maskData.type) { + case constants.MASK_TYPES.SCISSOR: + this.maskStack.push(maskData); + this.renderer.scissor.push(maskData); + break; + case constants.MASK_TYPES.STENCIL: + this.maskStack.push(maskData); + this.renderer.stencil.push(maskData); + break; + case constants.MASK_TYPES.SPRITE: + maskData.copyCountersOrReset(null); + this.pushSpriteMask(maskData); + this.maskStack.push(maskData); + break; + default: + break; + } }; - /** - * Gets extra render texture to use inside current filter - * To be compliant with older filters, you can use params in any order + * Removes the last mask from the mask stack and doesn't return it. + * Renderer batch must be flushed beforehand. * - * @param {PIXI.RenderTexture} [input] renderTexture from which size and resolution will be copied - * @param {number} [resolution] override resolution of the renderTexture - * @returns {PIXI.RenderTexture} + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from */ - FilterSystem.prototype.getFilterTexture = function getFilterTexture (input, resolution) - { - if (typeof input === 'number') - { - var swap = input; - - input = resolution; - resolution = swap; + MaskSystem.prototype.pop = function (target) { + var maskData = this.maskStack.pop(); + if (!maskData || maskData._target !== target) { + // TODO: add an assert when we have it + return; + } + switch (maskData.type) { + case constants.MASK_TYPES.SCISSOR: + this.renderer.scissor.pop(); + break; + case constants.MASK_TYPES.STENCIL: + this.renderer.stencil.pop(maskData.maskObject); + break; + case constants.MASK_TYPES.SPRITE: + this.popSpriteMask(); + break; + default: + break; + } + maskData.reset(); + if (maskData.pooled) { + this.maskDataPool.push(maskData); } - - input = input || this.activeState.renderTexture; - - var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution); - - filterTexture.filterFrame = input.filterFrame; - - return filterTexture; }; - /** - * Frees a render texture back into the pool. - * - * @param {PIXI.RenderTexture} renderTexture - The renderTarget to free + * Sets type of MaskData based on its maskObject + * @param {PIXI.MaskData} maskData */ - FilterSystem.prototype.returnFilterTexture = function returnFilterTexture (renderTexture) - { - this.texturePool.returnTexture(renderTexture); + MaskSystem.prototype.detect = function (maskData) { + var maskObject = maskData.maskObject; + if (maskObject.isSprite) { + maskData.type = constants.MASK_TYPES.SPRITE; + return; + } + maskData.type = constants.MASK_TYPES.STENCIL; + // detect scissor in graphics + if (this.enableScissor + && maskObject.isFastRect + && maskObject.isFastRect()) { + var matrix = maskObject.worldTransform; + // TODO: move the check to the matrix itself + // we are checking that its orthogonal and x rotation is 0 90 180 or 270 + var rotX = Math.atan2(matrix.b, matrix.a); + var rotXY = Math.atan2(matrix.d, matrix.c); + // use the nearest degree to 0.01 + rotX = Math.round(rotX * (180 / Math.PI) * 100); + rotXY = Math.round(rotXY * (180 / Math.PI) * 100) - rotX; + rotX = ((rotX % 9000) + 9000) % 9000; + rotXY = ((rotXY % 18000) + 18000) % 18000; + if (rotX === 0 && rotXY === 9000) { + maskData.type = constants.MASK_TYPES.SCISSOR; + } + } }; - /** - * Empties the texture pool. + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.MaskData} maskData - Sprite to be used as the mask */ - FilterSystem.prototype.emptyPool = function emptyPool () - { - this.texturePool.clear(true); + MaskSystem.prototype.pushSpriteMask = function (maskData) { + var maskObject = maskData.maskObject; + var target = maskData._target; + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter(maskObject)]; + } + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskObject; + var stashFilterArea = target.filterArea; + target.filterArea = maskObject.getBounds(true); + this.renderer.filter.push(target, alphaMaskFilter); + target.filterArea = stashFilterArea; + this.alphaMaskIndex++; }; - /** - * calls `texturePool.resize()`, affects fullScreen renderTextures + * Removes the last filter from the filter stack and doesn't return it. */ - FilterSystem.prototype.resize = function resize () - { - this.texturePool.setScreenSize(this.renderer.view); + MaskSystem.prototype.popSpriteMask = function () { + this.renderer.filter.pop(); + this.alphaMaskIndex--; }; - - return FilterSystem; + return MaskSystem; }(System)); /** - * Base for a common object renderer that can be used as a - * system renderer plugin. + * System plugin to the renderer to manage masks of certain type * * @class * @extends PIXI.System - * @memberof PIXI + * @memberof PIXI.systems */ -var ObjectRenderer = function ObjectRenderer(renderer) -{ +var AbstractMaskSystem = /** @class */ (function (_super) { + __extends(AbstractMaskSystem, _super); /** - * The renderer this manager works for. - * - * @member {PIXI.Renderer} + * @param {PIXI.Renderer} renderer - The renderer this System works for. */ - this.renderer = renderer; -}; - -/** - * Stub method that should be used to empty the current - * batch by rendering objects now. - */ -ObjectRenderer.prototype.flush = function flush () -{ - // flush! -}; - -/** - * Generic destruction method that frees all resources. This - * should be called by subclasses. - */ -ObjectRenderer.prototype.destroy = function destroy () -{ - this.renderer = null; -}; - -/** - * Stub method that initializes any state required before - * rendering starts. It is different from the `prerender` - * signal, which occurs every frame, in that it is called - * whenever an object requests _this_ renderer specifically. - */ -ObjectRenderer.prototype.start = function start () -{ - // set the shader.. -}; - -/** - * Stops the renderer. It should free up any state and - * become dormant. - */ -ObjectRenderer.prototype.stop = function stop () -{ - this.flush(); -}; - -/** - * Keeps the object to render. It doesn't have to be - * rendered immediately. - * - * @param {PIXI.DisplayObject} object - The object to render. - */ -ObjectRenderer.prototype.render = function render (object) // eslint-disable-line no-unused-vars -{ - // render the object -}; - -/** - * System plugin to the renderer to manage batching. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ -var BatchSystem = /*@__PURE__*/(function (System) { - function BatchSystem(renderer) - { - System.call(this, renderer); - + function AbstractMaskSystem(renderer) { + var _this = _super.call(this, renderer) || this; /** - * An empty renderer. - * - * @member {PIXI.ObjectRenderer} + * The mask stack + * @member {PIXI.MaskData[]} */ - this.emptyRenderer = new ObjectRenderer(renderer); - + _this.maskStack = []; /** - * The currently active ObjectRenderer. - * - * @member {PIXI.ObjectRenderer} + * Constant for gl.enable + * @member {number} + * @private */ - this.currentRenderer = this.emptyRenderer; + _this.glConst = 0; + return _this; } - - if ( System ) BatchSystem.__proto__ = System; - BatchSystem.prototype = Object.create( System && System.prototype ); - BatchSystem.prototype.constructor = BatchSystem; - /** - * Changes the current renderer to the one given in parameter - * - * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + * gets count of masks of certain type + * @returns {number} */ - BatchSystem.prototype.setObjectRenderer = function setObjectRenderer (objectRenderer) - { - if (this.currentRenderer === objectRenderer) - { - return; - } - - this.currentRenderer.stop(); - this.currentRenderer = objectRenderer; - - this.currentRenderer.start(); + AbstractMaskSystem.prototype.getStackLength = function () { + return this.maskStack.length; }; - /** - * This should be called if you wish to do some custom rendering - * It will basically render anything that may be batched up such as sprites + * Changes the mask stack that is used by this System. + * + * @param {PIXI.MaskData[]} maskStack - The mask stack */ - BatchSystem.prototype.flush = function flush () - { - this.setObjectRenderer(this.emptyRenderer); + AbstractMaskSystem.prototype.setMaskStack = function (maskStack) { + var gl = this.renderer.gl; + var curStackLen = this.getStackLength(); + this.maskStack = maskStack; + var newStackLen = this.getStackLength(); + if (newStackLen !== curStackLen) { + if (newStackLen === 0) { + gl.disable(this.glConst); + } + else { + gl.enable(this.glConst); + this._useCurrent(); + } + } }; - /** - * Reset the system to an empty renderer + * Setup renderer to use the current mask data. + * @private */ - BatchSystem.prototype.reset = function reset () - { - this.setObjectRenderer(this.emptyRenderer); + AbstractMaskSystem.prototype._useCurrent = function () { + // OVERWRITE; }; - /** - * Handy function for batch renderers: copies bound textures in first maxTextures locations to array - * sets actual _batchLocation for them + * Destroys the mask stack. * - * @param arr - * @param maxTextures */ - BatchSystem.prototype.copyBoundTextures = function copyBoundTextures (arr, maxTextures) - { - var ref = this.renderer.texture; - var boundTextures = ref.boundTextures; - - for (var i = maxTextures - 1; i >= 0; --i) - { - arr[i] = boundTextures[i] || null; - if (arr[i]) - { - arr[i]._batchLocation = i; - } - } + AbstractMaskSystem.prototype.destroy = function () { + _super.prototype.destroy.call(this); + this.maskStack = null; }; - - /** - * Assigns batch locations to textures in array based on boundTextures state. - * All textures in texArray should have `_batchEnabled = _batchId`, - * and their count should be less than `maxTextures`. - * - * @param {PIXI.BatchTextureArray} texArray textures to bound - * @param {PIXI.BaseTexture[]} boundTextures current state of bound textures - * @param {number} batchId marker for _batchEnabled param of textures in texArray - * @param {number} maxTextures number of texture locations to manipulate - */ - BatchSystem.prototype.boundArray = function boundArray (texArray, boundTextures, batchId, maxTextures) - { - var elements = texArray.elements; - var ids = texArray.ids; - var count = texArray.count; - var j = 0; - - for (var i = 0; i < count; i++) - { - var tex = elements[i]; - var loc = tex._batchLocation; - - if (loc >= 0 && loc < maxTextures - && boundTextures[loc] === tex) - { - ids[i] = loc; - continue; - } - - while (j < maxTextures) - { - var bound = boundTextures[j]; - - if (bound && bound._batchEnabled === batchId - && bound._batchLocation === j) - { - j++; - continue; - } - - ids[i] = j; - tex._batchLocation = j; - boundTextures[j] = tex; - break; - } - } - }; - - return BatchSystem; + return AbstractMaskSystem; }(System)); /** - * The maximum support for using WebGL. If a device does not - * support WebGL version, for instance WebGL 2, it will still - * attempt to fallback support to WebGL 1. If you want to - * explicitly remove feature support to target a more stable - * baseline, prefer a lower environment. - * - * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium} - * we disable webgl2 by default for all non-apple mobile devices. - * - * @static - * @name PREFER_ENV - * @memberof PIXI.settings - * @type {number} - * @default PIXI.ENV.WEBGL2 - */ -settings.settings.PREFER_ENV = utils.isMobile.any ? constants.ENV.WEBGL : constants.ENV.WEBGL2; - -/** - * If set to `true`, Textures and BaseTexture objects stored - * in the caches ({@link PIXI.utils.TextureCache TextureCache} and - * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can *only* be - * used when calling {@link PIXI.Texture.from Texture.from} or - * {@link PIXI.BaseTexture.from BaseTexture.from}. - * Otherwise, these `from` calls throw an exception. Using this property - * can be useful if you want to enforce preloading all assets with - * {@link PIXI.Loader Loader}. - * - * @static - * @name STRICT_TEXTURE_CACHE - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ -settings.settings.STRICT_TEXTURE_CACHE = false; - -var CONTEXT_UID = 0; - -/** - * System plugin to the renderer to manage the context. + * System plugin to the renderer to manage scissor rects (used for masks). * * @class * @extends PIXI.System * @memberof PIXI.systems */ -var ContextSystem = /*@__PURE__*/(function (System) { - function ContextSystem(renderer) - { - System.call(this, renderer); - - /** - * Either 1 or 2 to reflect the WebGL version being used - * @member {number} - * @readonly - */ - this.webGLVersion = 1; - - /** - * Extensions being used - * @member {object} - * @readonly - * @property {WEBGL_draw_buffers} drawBuffers - WebGL v1 extension - * @property {WEBGL_depth_texture} depthTexture - WebGL v1 extension - * @property {OES_texture_float} floatTexture - WebGL v1 extension - * @property {WEBGL_lose_context} loseContext - WebGL v1 extension - * @property {OES_vertex_array_object} vertexArrayObject - WebGL v1 extension - * @property {EXT_texture_filter_anisotropic} anisotropicFiltering - WebGL v1 and v2 extension - */ - this.extensions = {}; - - // Bind functions - this.handleContextLost = this.handleContextLost.bind(this); - this.handleContextRestored = this.handleContextRestored.bind(this); - - renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); - renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); +var ScissorSystem = /** @class */ (function (_super) { + __extends(ScissorSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function ScissorSystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this.glConst = WebGLRenderingContext.SCISSOR_TEST; + return _this; } - - if ( System ) ContextSystem.__proto__ = System; - ContextSystem.prototype = Object.create( System && System.prototype ); - ContextSystem.prototype.constructor = ContextSystem; - - var prototypeAccessors = { isLost: { configurable: true } }; - + ScissorSystem.prototype.getStackLength = function () { + var maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._scissorCounter; + } + return 0; + }; /** - * `true` if the context is lost - * @member {boolean} - * @readonly + * Applies the Mask and adds it to the current stencil stack. @alvin + * + * @param {PIXI.MaskData} maskData - The mask data */ - prototypeAccessors.isLost.get = function () - { - return (!this.gl || this.gl.isContextLost()); + ScissorSystem.prototype.push = function (maskData) { + var maskObject = maskData.maskObject; + maskObject.renderable = true; + var prevData = maskData._scissorRect; + var bounds = maskObject.getBounds(true); + var gl = this.renderer.gl; + maskObject.renderable = false; + if (prevData) { + bounds.fit(prevData); + } + else { + gl.enable(gl.SCISSOR_TEST); + } + maskData._scissorCounter++; + maskData._scissorRect = bounds; + this._useCurrent(); }; - /** - * Handle the context change event - * @param {WebGLRenderingContext} gl new webgl context + * Pops scissor mask. MaskData is already removed from stack */ - ContextSystem.prototype.contextChange = function contextChange (gl) - { - this.gl = gl; - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - - // restore a context if it was previously lost - if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) - { - gl.getExtension('WEBGL_lose_context').restoreContext(); + ScissorSystem.prototype.pop = function () { + var gl = this.renderer.gl; + if (this.getStackLength() > 0) { + this._useCurrent(); + } + else { + gl.disable(gl.SCISSOR_TEST); } }; - /** - * Initialize the context - * - * @protected - * @param {WebGLRenderingContext} gl - WebGL context + * Setup renderer to use the current scissor data. + * @private */ - ContextSystem.prototype.initFromContext = function initFromContext (gl) - { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + ScissorSystem.prototype._useCurrent = function () { + var rect = this.maskStack[this.maskStack.length - 1]._scissorRect; + var rt = this.renderer.renderTexture.current; + var _a = this.renderer.projection, transform = _a.transform, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; + var resolution = rt ? rt.resolution : this.renderer.resolution; + var x = ((rect.x - sourceFrame.x) * resolution) + destinationFrame.x; + var y = ((rect.y - sourceFrame.y) * resolution) + destinationFrame.y; + var width = rect.width * resolution; + var height = rect.height * resolution; + if (transform) { + x += transform.tx * resolution; + y += transform.ty * resolution; + } + if (!rt) { + // flipY. In future we'll have it over renderTextures as an option + y = this.renderer.height - height - y; + } + this.renderer.gl.scissor(x, y, width, height); }; + return ScissorSystem; +}(AbstractMaskSystem)); +/** + * System plugin to the renderer to manage stencils (used for masks). + * + * @class + * @extends PIXI.System + * @memberof PIXI.systems + */ +var StencilSystem = /** @class */ (function (_super) { + __extends(StencilSystem, _super); /** - * Initialize from context options - * - * @protected - * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext - * @param {object} options - context attributes + * @param {PIXI.Renderer} renderer - The renderer this System works for. */ - ContextSystem.prototype.initFromOptions = function initFromOptions (options) - { - var gl = this.createContext(this.renderer.view, options); - - this.initFromContext(gl); + function StencilSystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this.glConst = WebGLRenderingContext.STENCIL_TEST; + return _this; + } + StencilSystem.prototype.getStackLength = function () { + var maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._stencilCounter; + } + return 0; }; - /** - * Helper class to create a WebGL Context + * Applies the Mask and adds it to the current stencil stack. * - * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from - * @param options {object} An options object that gets passed in to the canvas element containing the context attributes - * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext - * @return {WebGLRenderingContext} the WebGL context + * @param {PIXI.MaskData} maskData - The mask data */ - ContextSystem.prototype.createContext = function createContext (canvas, options) - { - var gl; - - if (settings.settings.PREFER_ENV >= constants.ENV.WEBGL2) - { - gl = canvas.getContext('webgl2', options); - } - - if (gl) - { - this.webGLVersion = 2; - } - else - { - this.webGLVersion = 1; - - gl = canvas.getContext('webgl', options) - || canvas.getContext('experimental-webgl', options); - - if (!gl) - { - // fail, not able to get a context - throw new Error('This browser does not support WebGL. Try using the canvas renderer'); - } + StencilSystem.prototype.push = function (maskData) { + var maskObject = maskData.maskObject; + var gl = this.renderer.gl; + var prevMaskCount = maskData._stencilCounter; + if (prevMaskCount === 0) { + // force use stencil texture in current framebuffer + this.renderer.framebuffer.forceStencil(); + gl.enable(gl.STENCIL_TEST); } - - this.gl = gl; - - this.getExtensions(); - - return gl; + maskData._stencilCounter++; + // Increment the reference stencil value where the new mask overlaps with the old ones. + gl.colorMask(false, false, false, false); + gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + this._useCurrent(); }; - /** - * Auto-populate the extensions + * Pops stencil mask. MaskData is already removed from stack * - * @protected + * @param {PIXI.DisplayObject} maskObject - object of popped mask data */ - ContextSystem.prototype.getExtensions = function getExtensions () - { - // time to set up default extensions that Pixi uses. - var ref = this; - var gl = ref.gl; - - if (this.webGLVersion === 1) - { - Object.assign(this.extensions, { - drawBuffers: gl.getExtension('WEBGL_draw_buffers'), - depthTexture: gl.getExtension('WEBKIT_WEBGL_depth_texture'), - loseContext: gl.getExtension('WEBGL_lose_context'), - vertexArrayObject: gl.getExtension('OES_vertex_array_object') - || gl.getExtension('MOZ_OES_vertex_array_object') - || gl.getExtension('WEBKIT_OES_vertex_array_object'), - anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), - uint32ElementIndex: gl.getExtension('OES_element_index_uint'), - // Floats and half-floats - floatTexture: gl.getExtension('OES_texture_float'), - floatTextureLinear: gl.getExtension('OES_texture_float_linear'), - textureHalfFloat: gl.getExtension('OES_texture_half_float'), - textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'), - }); + StencilSystem.prototype.pop = function (maskObject) { + var gl = this.renderer.gl; + if (this.getStackLength() === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.clearStencil(0); } - else if (this.webGLVersion === 2) - { - Object.assign(this.extensions, { - anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), - // Floats and half-floats - colorBufferFloat: gl.getExtension('EXT_color_buffer_float'), - floatTextureLinear: gl.getExtension('OES_texture_float_linear'), - }); + else { + // Decrement the reference stencil value where the popped mask overlaps with the other ones + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + this._useCurrent(); } }; - /** - * Handles a lost webgl context - * - * @protected - * @param {WebGLContextEvent} event - The context lost event. + * Setup renderer to use the current stencil data. + * @private */ - ContextSystem.prototype.handleContextLost = function handleContextLost (event) - { - event.preventDefault(); + StencilSystem.prototype._useCurrent = function () { + var gl = this.renderer.gl; + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.EQUAL, this.getStackLength(), this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); }; - /** - * Handles a restored webgl context - * - * @protected + * Fill 1s equal to the number of acitve stencil masks. + * @private + * @return {number} The bitwise mask. */ - ContextSystem.prototype.handleContextRestored = function handleContextRestored () - { - this.renderer.runners.contextChange.run(this.gl); + StencilSystem.prototype._getBitwiseMask = function () { + return (1 << this.getStackLength()) - 1; }; + return StencilSystem; +}(AbstractMaskSystem)); - ContextSystem.prototype.destroy = function destroy () - { - var view = this.renderer.view; - - // remove listeners - view.removeEventListener('webglcontextlost', this.handleContextLost); - view.removeEventListener('webglcontextrestored', this.handleContextRestored); - - this.gl.useProgram(null); - - if (this.extensions.loseContext) - { - this.extensions.loseContext.loseContext(); +/** + * System plugin to the renderer to manage the projection matrix. + * + * @class + * @extends PIXI.System + * @memberof PIXI.systems + */ +var ProjectionSystem = /** @class */ (function (_super) { + __extends(ProjectionSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function ProjectionSystem(renderer) { + var _this = _super.call(this, renderer) || this; + /** + * Destination frame + * @member {PIXI.Rectangle} + * @readonly + */ + _this.destinationFrame = null; + /** + * Source frame + * @member {PIXI.Rectangle} + * @readonly + */ + _this.sourceFrame = null; + /** + * Default destination frame + * @member {PIXI.Rectangle} + * @readonly + */ + _this.defaultFrame = null; + /** + * Project matrix + * @member {PIXI.Matrix} + * @readonly + */ + _this.projectionMatrix = new math.Matrix(); + /** + * A transform that will be appended to the projection matrix + * if null, nothing will be applied + * @member {PIXI.Matrix} + */ + _this.transform = null; + return _this; + } + /** + * Updates the projection matrix based on a projection frame (which is a rectangle). + * + * Make sure to run `renderer.framebuffer.setViewport(destinationFrame)` after calling this. + * + * @param {PIXI.Rectangle} destinationFrame - The destination frame. + * @param {PIXI.Rectangle} sourceFrame - The source frame. + * @param {Number} resolution - Resolution + * @param {boolean} root - If is root + */ + ProjectionSystem.prototype.update = function (destinationFrame, sourceFrame, resolution, root) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + // Calculate object-space to clip-space projection + this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root); + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + var renderer = this.renderer; + renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix; + renderer.globalUniforms.update(); + // this will work for now + // but would be sweet to stick and even on the global uniforms.. + if (renderer.shader.shader) { + renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals); } }; - /** - * Handle the post-render runner event + * Updates the projection matrix based on a projection frame (which is a rectangle) * - * @protected + * @param {PIXI.Rectangle} destinationFrame - The destination frame. + * @param {PIXI.Rectangle} sourceFrame - The source frame. + * @param {Number} resolution - Resolution + * @param {boolean} root - If is root */ - ContextSystem.prototype.postrender = function postrender () - { - if (this.renderer.renderingToScreen) - { - this.gl.flush(); - } + ProjectionSystem.prototype.calculateProjection = function (_destinationFrame, sourceFrame, _resolution, root) { + var pm = this.projectionMatrix; + var sign = !root ? 1 : -1; + pm.identity(); + pm.a = (1 / sourceFrame.width * 2); + pm.d = sign * (1 / sourceFrame.height * 2); + pm.tx = -1 - (sourceFrame.x * pm.a); + pm.ty = -sign - (sourceFrame.y * pm.d); }; - /** - * Validate context + * Sets the transform of the active render target to the given matrix * - * @protected - * @param {WebGLRenderingContext} gl - Render context + * @param {PIXI.Matrix} matrix - The transformation matrix */ - ContextSystem.prototype.validateContext = function validateContext (gl) - { - var attributes = gl.getContextAttributes(); - - // this is going to be fairly simple for now.. but at least we have room to grow! - if (!attributes.stencil) - { - /* eslint-disable max-len */ - - /* eslint-disable no-console */ - console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); - /* eslint-enable no-console */ - - /* eslint-enable max-len */ - } + ProjectionSystem.prototype.setTransform = function (_matrix) { + // this._activeRenderTarget.transform = matrix; }; - - Object.defineProperties( ContextSystem.prototype, prototypeAccessors ); - - return ContextSystem; + return ProjectionSystem; }(System)); +// Temporary rectangle for assigned sourceFrame or destinationFrame +var tempRect = new math.Rectangle(); +// Temporary rectangle for renderTexture destinationFrame +var tempRect2 = new math.Rectangle(); +// Temporary rectangle for passing the framebuffer viewport +var viewportFrame = new math.Rectangle(); /** - * System plugin to the renderer to manage framebuffers. + * System plugin to the renderer to manage render textures. + * + * Should be added after FramebufferSystem * * @class * @extends PIXI.System * @memberof PIXI.systems */ -var FramebufferSystem = /*@__PURE__*/(function (System) { - function FramebufferSystem(renderer) - { - System.call(this, renderer); - +var RenderTextureSystem = /** @class */ (function (_super) { + __extends(RenderTextureSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function RenderTextureSystem(renderer) { + var _this = _super.call(this, renderer) || this; /** - * A list of managed framebuffers - * @member {PIXI.Framebuffer[]} + * The clear background color as rgba + * @member {number[]} + */ + _this.clearColor = renderer._backgroundColorRgba; + // TODO move this property somewhere else! + /** + * List of masks for the StencilSystem + * @member {PIXI.Graphics[]} * @readonly */ - this.managedFramebuffers = []; - + _this.defaultMaskStack = []; + // empty render texture? /** - * Framebuffer value that shows that we don't know what is bound - * @member {Framebuffer} + * Render texture + * @member {PIXI.RenderTexture} * @readonly */ - this.unknownFramebuffer = new Framebuffer(10, 10); + _this.current = null; + /** + * Source frame + * @member {PIXI.Rectangle} + * @readonly + */ + _this.sourceFrame = new math.Rectangle(); + /** + * Destination frame + * @member {PIXI.Rectangle} + * @readonly + */ + _this.destinationFrame = new math.Rectangle(); + return _this; } - - if ( System ) FramebufferSystem.__proto__ = System; - FramebufferSystem.prototype = Object.create( System && System.prototype ); - FramebufferSystem.prototype.constructor = FramebufferSystem; - - var prototypeAccessors = { size: { configurable: true } }; - /** - * Sets up the renderer context and necessary buffers. + * Bind the current render texture + * + * @param {PIXI.RenderTexture} [renderTexture] - RenderTexture to bind, by default its `null`, the screen + * @param {PIXI.Rectangle} [sourceFrame] - part of screen that is mapped to the renderTexture + * @param {PIXI.Rectangle} [destinationFrame] - part of renderTexture, by default it has the same size as sourceFrame */ - FramebufferSystem.prototype.contextChange = function contextChange () - { - var gl = this.gl = this.renderer.gl; - - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - this.current = this.unknownFramebuffer; - this.viewport = new math.Rectangle(); - this.hasMRT = true; - this.writeDepthTexture = true; - - this.disposeAll(true); - - // webgl2 - if (this.renderer.context.webGLVersion === 1) - { - // webgl 1! - var nativeDrawBuffersExtension = this.renderer.context.extensions.drawBuffers; - var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture; - - if (settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY) - { - nativeDrawBuffersExtension = null; - nativeDepthTextureExtension = null; + RenderTextureSystem.prototype.bind = function (renderTexture, sourceFrame, destinationFrame) { + if (renderTexture === void 0) { renderTexture = null; } + var renderer = this.renderer; + this.current = renderTexture; + var baseTexture; + var framebuffer; + var resolution; + if (renderTexture) { + baseTexture = renderTexture.baseTexture; + resolution = baseTexture.resolution; + if (!sourceFrame) { + tempRect.width = renderTexture.frame.width; + tempRect.height = renderTexture.frame.height; + sourceFrame = tempRect; } - - if (nativeDrawBuffersExtension) - { - gl.drawBuffers = function (activeTextures) { return nativeDrawBuffersExtension.drawBuffersWEBGL(activeTextures); }; + if (!destinationFrame) { + tempRect2.x = renderTexture.frame.x; + tempRect2.y = renderTexture.frame.y; + tempRect2.width = sourceFrame.width; + tempRect2.height = sourceFrame.height; + destinationFrame = tempRect2; } - else - { - this.hasMRT = false; - gl.drawBuffers = function () { - // empty - }; + framebuffer = baseTexture.framebuffer; + } + else { + resolution = renderer.resolution; + if (!sourceFrame) { + tempRect.width = renderer.screen.width; + tempRect.height = renderer.screen.height; + sourceFrame = tempRect; } - - if (!nativeDepthTextureExtension) - { - this.writeDepthTexture = false; + if (!destinationFrame) { + destinationFrame = tempRect; + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; } } + viewportFrame.x = destinationFrame.x * resolution; + viewportFrame.y = destinationFrame.y * resolution; + viewportFrame.width = destinationFrame.width * resolution; + viewportFrame.height = destinationFrame.height * resolution; + this.renderer.framebuffer.bind(framebuffer, viewportFrame); + this.renderer.projection.update(destinationFrame, sourceFrame, resolution, !framebuffer); + if (renderTexture) { + this.renderer.mask.setMaskStack(baseTexture.maskStack); + } + else { + this.renderer.mask.setMaskStack(this.defaultMaskStack); + } + this.sourceFrame.copyFrom(sourceFrame); + this.destinationFrame.copyFrom(destinationFrame); }; - /** - * Bind a framebuffer + * Erases the render texture and fills the drawing area with a colour * - * @param {PIXI.Framebuffer} framebuffer - * @param {PIXI.Rectangle} [frame] frame, default is framebuffer size + * @param {number[]} [clearColor] - The color as rgba, default to use the renderer backgroundColor + * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks + * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. + * @return {PIXI.Renderer} Returns itself. */ - FramebufferSystem.prototype.bind = function bind (framebuffer, frame) - { - var ref = this; - var gl = ref.gl; - - if (framebuffer) - { - // TODO caching layer! - - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); - - if (this.current !== framebuffer) - { - this.current = framebuffer; - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); - } - // make sure all textures are unbound.. - - // now check for updates... - if (fbo.dirtyId !== framebuffer.dirtyId) - { - fbo.dirtyId = framebuffer.dirtyId; - - if (fbo.dirtyFormat !== framebuffer.dirtyFormat) - { - fbo.dirtyFormat = framebuffer.dirtyFormat; - this.updateFramebuffer(framebuffer); - } - else if (fbo.dirtySize !== framebuffer.dirtySize) - { - fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer); - } - } - - for (var i = 0; i < framebuffer.colorTextures.length; i++) - { - if (framebuffer.colorTextures[i].texturePart) - { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); - } - else - { - this.renderer.texture.unbind(framebuffer.colorTextures[i]); - } - } - - if (framebuffer.depthTexture) - { - this.renderer.texture.unbind(framebuffer.depthTexture); - } - - if (frame) - { - this.setViewport(frame.x, frame.y, frame.width, frame.height); - } - else - { - this.setViewport(0, 0, framebuffer.width, framebuffer.height); - } + RenderTextureSystem.prototype.clear = function (clearColor, mask) { + if (this.current) { + clearColor = clearColor || this.current.baseTexture.clearColor; } - else - { - if (this.current) - { - this.current = null; - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - } - - if (frame) - { - this.setViewport(frame.x, frame.y, frame.width, frame.height); - } - else - { - this.setViewport(0, 0, this.renderer.width, this.renderer.height); - } + else { + clearColor = clearColor || this.clearColor; } + this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3], mask); + }; + RenderTextureSystem.prototype.resize = function () { + // resize the root only! + this.bind(null); + }; + /** + * Resets renderTexture state + */ + RenderTextureSystem.prototype.reset = function () { + this.bind(null); }; + return RenderTextureSystem; +}(System)); +var IGLUniformData = /** @class */ (function () { + function IGLUniformData() { + } + return IGLUniformData; +}()); +/** + * Helper class to create a WebGL Program + * + * @class + * @memberof PIXI + */ +var GLProgram = /** @class */ (function () { /** - * Set the WebGLRenderingContext's viewport. + * Makes a new Pixi program * - * @param {Number} x - X position of viewport - * @param {Number} y - Y position of viewport - * @param {Number} width - Width of viewport - * @param {Number} height - Height of viewport + * @param program {WebGLProgram} webgl program + * @param uniformData {Object} uniforms */ - FramebufferSystem.prototype.setViewport = function setViewport (x, y, width, height) - { - var v = this.viewport; - - if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) - { - v.x = x; - v.y = y; - v.width = width; - v.height = height; - - this.gl.viewport(x, y, width, height); - } + function GLProgram(program, uniformData) { + /** + * The shader program + * + * @member {WebGLProgram} + */ + this.program = program; + /** + * holds the uniform data which contains uniform locations + * and current uniform values used for caching and preventing unneeded GPU commands + * @member {Object} + */ + this.uniformData = uniformData; + /** + * uniformGroups holds the various upload functions for the shader. Each uniform group + * and program have a unique upload function generated. + * @member {Object} + */ + this.uniformGroups = {}; + } + /** + * Destroys this program + */ + GLProgram.prototype.destroy = function () { + this.uniformData = null; + this.uniformGroups = null; + this.program = null; }; + return GLProgram; +}()); +var UID$4 = 0; +// defualt sync data so we don't create a new one each time! +var defaultSyncData = { textureCount: 0 }; +/** + * System plugin to the renderer to manage shaders. + * + * @class + * @memberof PIXI.systems + * @extends PIXI.System + */ +var ShaderSystem = /** @class */ (function (_super) { + __extends(ShaderSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function ShaderSystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this.destroyed = false; + // Validation check that this environment support `new Function` + _this.systemCheck(); + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + _this.gl = null; + _this.shader = null; + _this.program = null; + /** + * Cache to holds the generated functions. Stored against UniformObjects unique signature + * @type {Object} + * @private + */ + _this.cache = {}; + _this.id = UID$4++; + return _this; + } /** - * Get the size of the current width and height. Returns object with `width` and `height` values. + * Overrideable function by `@pixi/unsafe-eval` to silence + * throwing an error if platform doesn't support unsafe-evals. * - * @member {object} - * @readonly + * @private */ - prototypeAccessors.size.get = function () - { - if (this.current) - { - // TODO store temp - return { x: 0, y: 0, width: this.current.width, height: this.current.height }; + ShaderSystem.prototype.systemCheck = function () { + if (!unsafeEvalSupported()) { + throw new Error('Current environment does not allow unsafe-eval, ' + + 'please use @pixi/unsafe-eval module to enable support.'); } - - return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height }; }; - + ShaderSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.reset(); + }; /** - * Clear the color of the context + * Changes the current shader to the one given in parameter * - * @param {Number} r - Red value from 0 to 1 - * @param {Number} g - Green value from 0 to 1 - * @param {Number} b - Blue value from 0 to 1 - * @param {Number} a - Alpha value from 0 to 1 + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [dontSync] - false if the shader should automatically sync its uniforms. + * @returns {PIXI.GLProgram} the glProgram that belongs to the shader. */ - FramebufferSystem.prototype.clear = function clear (r, g, b, a) - { - var ref = this; - var gl = ref.gl; - - // TODO clear color can be set only one right? - gl.clearColor(r, g, b, a); - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + ShaderSystem.prototype.bind = function (shader, dontSync) { + shader.uniforms.globals = this.renderer.globalUniforms; + var program = shader.program; + var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current Pixi plugins bypass this.. so it not safe to use yet.. + if (this.program !== program) { + this.program = program; + this.gl.useProgram(glProgram.program); + } + if (!dontSync) { + defaultSyncData.textureCount = 0; + this.syncUniformGroup(shader.uniformGroup, defaultSyncData); + } + return glProgram; }; - /** - * Initialize framebuffer + * Uploads the uniforms values to the currently bound shader. * - * @protected - * @param {PIXI.Framebuffer} framebuffer + * @param {object} uniforms - the uniforms values that be applied to the current shader */ - FramebufferSystem.prototype.initFramebuffer = function initFramebuffer (framebuffer) - { - var ref = this; - var gl = ref.gl; - - // TODO - make this a class? - var fbo = { - framebuffer: gl.createFramebuffer(), - stencil: null, - dirtyId: 0, - dirtyFormat: 0, - dirtySize: 0, - }; - - framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo; - - this.managedFramebuffers.push(framebuffer); - framebuffer.disposeRunner.add(this); - - return fbo; + ShaderSystem.prototype.setUniforms = function (uniforms) { + var shader = this.shader.program; + var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID]; + shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer); }; - + /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /** - * Resize the framebuffer * - * @protected - * @param {PIXI.Framebuffer} framebuffer + * syncs uniforms on the group + * @param {*} group - the uniform group to sync + * @param {*} [syncData] - this is data that is passed to the sync function and any nested sync functions */ - FramebufferSystem.prototype.resizeFramebuffer = function resizeFramebuffer (framebuffer) - { - var ref = this; - var gl = ref.gl; - - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - - if (fbo.stencil) - { - gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); - } - - var colorTextures = framebuffer.colorTextures; - - for (var i = 0; i < colorTextures.length; i++) - { - this.renderer.texture.bind(colorTextures[i], 0); - } - - if (framebuffer.depthTexture) - { - this.renderer.texture.bind(framebuffer.depthTexture, 0); + ShaderSystem.prototype.syncUniformGroup = function (group, syncData) { + var glProgram = this.getglProgram(); + if (!group.static || group.dirtyId !== glProgram.uniformGroups[group.id]) { + glProgram.uniformGroups[group.id] = group.dirtyId; + this.syncUniforms(group, glProgram, syncData); } }; - /** - * Update the framebuffer + * Overrideable by the @pixi/unsafe-eval package to use static + * syncUnforms instead. * - * @protected - * @param {PIXI.Framebuffer} framebuffer + * @private */ - FramebufferSystem.prototype.updateFramebuffer = function updateFramebuffer (framebuffer) - { - var ref = this; - var gl = ref.gl; - - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - - // bind the color texture - var colorTextures = framebuffer.colorTextures; - - var count = colorTextures.length; - - if (!gl.drawBuffers) - { - count = Math.min(count, 1); - } - - var activeTextures = []; - - for (var i = 0; i < count; i++) - { - var texture = framebuffer.colorTextures[i]; - - if (texture.texturePart) - { - this.renderer.texture.bind(texture.texture, 0); - - gl.framebufferTexture2D(gl.FRAMEBUFFER, - gl.COLOR_ATTACHMENT0 + i, - gl.TEXTURE_CUBE_MAP_NEGATIVE_X + texture.side, - texture.texture._glTextures[this.CONTEXT_UID].texture, - 0); - } - else - { - this.renderer.texture.bind(texture, 0); - - gl.framebufferTexture2D(gl.FRAMEBUFFER, - gl.COLOR_ATTACHMENT0 + i, - gl.TEXTURE_2D, - texture._glTextures[this.CONTEXT_UID].texture, - 0); - } - - activeTextures.push(gl.COLOR_ATTACHMENT0 + i); - } - - if (activeTextures.length > 1) - { - gl.drawBuffers(activeTextures); - } - - if (framebuffer.depthTexture) - { - var writeDepthTexture = this.writeDepthTexture; - - if (writeDepthTexture) - { - var depthTexture = framebuffer.depthTexture; - - this.renderer.texture.bind(depthTexture, 0); - - gl.framebufferTexture2D(gl.FRAMEBUFFER, - gl.DEPTH_ATTACHMENT, - gl.TEXTURE_2D, - depthTexture._glTextures[this.CONTEXT_UID].texture, - 0); - } - } - - if (!fbo.stencil && (framebuffer.stencil || framebuffer.depth)) - { - fbo.stencil = gl.createRenderbuffer(); - - gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); - - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); - // TODO.. this is depth AND stencil? - if (!framebuffer.depthTexture) - { // you can't have both, so one should take priority if enabled - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - } + ShaderSystem.prototype.syncUniforms = function (group, glProgram, syncData) { + var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); + syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData); + }; + /* eslint-enable @typescript-eslint/explicit-module-boundary-types */ + ShaderSystem.prototype.createSyncGroups = function (group) { + var id = this.getSignature(group, this.shader.program.uniformData); + if (!this.cache[id]) { + this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData); } + group.syncUniforms[this.shader.program.id] = this.cache[id]; + return group.syncUniforms[this.shader.program.id]; }; - /** - * Disposes framebuffer - * @param {PIXI.Framebuffer} framebuffer framebuffer that has to be disposed of - * @param {boolean} [contextLost=false] If context was lost, we suppress all delete function calls + * Takes a uniform group and data and generates a unique signature for them. + * + * @param {PIXI.UniformGroup} group - the uniform group to get signature of + * @param {Object} uniformData - uniform information generated by the shader + * @returns {String} Unique signature of the uniform group + * @private */ - FramebufferSystem.prototype.disposeFramebuffer = function disposeFramebuffer (framebuffer, contextLost) - { - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - var gl = this.gl; - - if (!fbo) - { - return; - } - - delete framebuffer.glFramebuffers[this.CONTEXT_UID]; - - var index = this.managedFramebuffers.indexOf(framebuffer); - - if (index >= 0) - { - this.managedFramebuffers.splice(index, 1); - } - - framebuffer.disposeRunner.remove(this); - - if (!contextLost) - { - gl.deleteFramebuffer(fbo.framebuffer); - if (fbo.stencil) - { - gl.deleteRenderbuffer(fbo.stencil); + ShaderSystem.prototype.getSignature = function (group, uniformData) { + var uniforms = group.uniforms; + var strings = []; + for (var i in uniforms) { + strings.push(i); + if (uniformData[i]) { + strings.push(uniformData[i].type); } } + return strings.join('-'); }; - /** - * Disposes all framebuffers, but not textures bound to them - * @param {boolean} [contextLost=false] If context was lost, we suppress all delete function calls + * Returns the underlying GLShade rof the currently bound shader. + * This can be handy for when you to have a little more control over the setting of your uniforms. + * + * @return {PIXI.GLProgram} the glProgram for the currently bound Shader for this context */ - FramebufferSystem.prototype.disposeAll = function disposeAll (contextLost) - { - var list = this.managedFramebuffers; - - this.managedFramebuffers = []; - - for (var i = 0; i < list.length; i++) - { - this.disposeFramebuffer(list[i], contextLost); + ShaderSystem.prototype.getglProgram = function () { + if (this.shader) { + return this.shader.program.glPrograms[this.renderer.CONTEXT_UID]; } + return null; }; - /** - * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. - * Used by MaskSystem, when its time to use stencil mask for Graphics element. - * - * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind. + * Generates a glProgram version of the Shader provided. * * @private + * @param {PIXI.Shader} shader - the shader that the glProgram will be based on. + * @return {PIXI.GLProgram} A shiny new glProgram! */ - FramebufferSystem.prototype.forceStencil = function forceStencil () - { - var framebuffer = this.current; - - if (!framebuffer) - { - return; + ShaderSystem.prototype.generateShader = function (shader) { + var gl = this.gl; + var program = shader.program; + var attribMap = {}; + for (var i in program.attributeData) { + attribMap[i] = program.attributeData[i].location; } - - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - - if (!fbo || fbo.stencil) - { - return; + var shaderProgram = compileProgram(gl, program.vertexSrc, program.fragmentSrc, attribMap); + var uniformData = {}; + for (var i in program.uniformData) { + var data = program.uniformData[i]; + uniformData[i] = { + location: gl.getUniformLocation(shaderProgram, i), + value: defaultValue(data.type, data.size), + }; } - framebuffer.enableStencil(); - - var w = framebuffer.width; - var h = framebuffer.height; - var gl = this.gl; - var stencil = gl.createRenderbuffer(); - - gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); - - fbo.stencil = stencil; - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); + var glProgram = new GLProgram(shaderProgram, uniformData); + program.glPrograms[this.renderer.CONTEXT_UID] = glProgram; + return glProgram; }; - /** - * resets framebuffer stored state, binds screen framebuffer - * - * should be called before renderTexture reset() + * Resets ShaderSystem state, does not affect WebGL state */ - FramebufferSystem.prototype.reset = function reset () - { - this.current = this.unknownFramebuffer; - this.viewport = new math.Rectangle(); + ShaderSystem.prototype.reset = function () { + this.program = null; + this.shader = null; }; - - Object.defineProperties( FramebufferSystem.prototype, prototypeAccessors ); - - return FramebufferSystem; + /** + * Destroys this System and removes all its textures + */ + ShaderSystem.prototype.destroy = function () { + // TODO implement destroy method for ShaderSystem + this.destroyed = true; + }; + return ShaderSystem; }(System)); -var GLBuffer = function GLBuffer(buffer) -{ - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - this.refCount = 0; -}; - -var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 }; +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {number[][]} [array=[]] - The array to output into. + * @return {number[][]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl, array) { + if (array === void 0) { array = []; } + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[constants.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; + array[constants.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.NONE] = [0, 0]; + // not-premultiplied blend modes + array[constants.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; + array[constants.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + // composite operations + array[constants.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO]; + array[constants.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO]; + array[constants.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE]; + array[constants.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA]; + array[constants.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA]; + array[constants.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA]; + array[constants.BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + // SUBTRACT from flash + array[constants.BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD]; + return array; +} +var BLEND$1 = 0; +var OFFSET$1 = 1; +var CULLING$1 = 2; +var DEPTH_TEST$1 = 3; +var WINDING$1 = 4; /** - * System plugin to the renderer to manage geometry. + * System plugin to the renderer to manage WebGL state machines. * * @class * @extends PIXI.System * @memberof PIXI.systems */ -var GeometrySystem = /*@__PURE__*/(function (System) { - function GeometrySystem(renderer) - { - System.call(this, renderer); - - this._activeGeometry = null; - this._activeVao = null; - +var StateSystem = /** @class */ (function (_super) { + __extends(StateSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function StateSystem(renderer) { + var _this = _super.call(this, renderer) || this; /** - * `true` if we has `*_vertex_array_object` extension - * @member {boolean} + * GL context + * @member {WebGLRenderingContext} * @readonly */ - this.hasVao = true; - + _this.gl = null; /** - * `true` if has `ANGLE_instanced_arrays` extension - * @member {boolean} + * State ID + * @member {number} * @readonly */ - this.hasInstance = true; - + _this.stateId = 0; /** - * `true` if support `gl.UNSIGNED_INT` in `gl.drawElements` or `gl.drawElementsInstanced` - * @member {boolean} + * Polygon offset + * @member {number} * @readonly */ - this.canUseUInt32ElementIndex = false; - + _this.polygonOffset = 0; /** - * A cache of currently bound buffer, - * contains only two members with keys ARRAY_BUFFER and ELEMENT_ARRAY_BUFFER - * @member {Object.} + * Blend mode + * @member {number} + * @default PIXI.BLEND_MODES.NONE * @readonly */ - this.boundBuffers = {}; - + _this.blendMode = constants.BLEND_MODES.NONE; /** - * Cache for all geometries by id, used in case renderer gets destroyed or for profiling - * @member {object} + * Whether current blend equation is different + * @member {boolean} + * @protected + */ + _this._blendEq = false; + /** + * Collection of calls + * @member {function[]} * @readonly */ - this.managedGeometries = {}; - + _this.map = []; + // map functions for when we set state.. + _this.map[BLEND$1] = _this.setBlend; + _this.map[OFFSET$1] = _this.setOffset; + _this.map[CULLING$1] = _this.setCullFace; + _this.map[DEPTH_TEST$1] = _this.setDepthTest; + _this.map[WINDING$1] = _this.setFrontFace; /** - * Cache for all buffers by id, used in case renderer gets destroyed or for profiling - * @member {object} + * Collection of check calls + * @member {function[]} + * @readonly + */ + _this.checks = []; + /** + * Default WebGL State + * @member {PIXI.State} * @readonly */ - this.managedBuffers = {}; + _this.defaultState = new State(); + _this.defaultState.blend = true; + return _this; } - - if ( System ) GeometrySystem.__proto__ = System; - GeometrySystem.prototype = Object.create( System && System.prototype ); - GeometrySystem.prototype.constructor = GeometrySystem; - + StateSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.blendModes = mapWebGLBlendModesToPixi(gl); + this.set(this.defaultState); + this.reset(); + }; /** - * Sets up the renderer context and necessary buffers. + * Sets the current state + * + * @param {*} state - The state to set. */ - GeometrySystem.prototype.contextChange = function contextChange () - { - this.disposeAll(true); - - var gl = this.gl = this.renderer.gl; - var context = this.renderer.context; - - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - - // webgl2 - if (!gl.createVertexArray) - { - // webgl 1! - var nativeVaoExtension = this.renderer.context.extensions.vertexArrayObject; - - if (settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY) - { - nativeVaoExtension = null; - } - - if (nativeVaoExtension) - { - gl.createVertexArray = function () { return nativeVaoExtension.createVertexArrayOES(); }; - - gl.bindVertexArray = function (vao) { return nativeVaoExtension.bindVertexArrayOES(vao); }; - - gl.deleteVertexArray = function (vao) { return nativeVaoExtension.deleteVertexArrayOES(vao); }; - } - else - { - this.hasVao = false; - gl.createVertexArray = function () { - // empty - }; - - gl.bindVertexArray = function () { - // empty - }; - - gl.deleteVertexArray = function () { - // empty - }; + StateSystem.prototype.set = function (state) { + state = state || this.defaultState; + // TODO maybe to an object check? ( this.state === state )? + if (this.stateId !== state.data) { + var diff = this.stateId ^ state.data; + var i = 0; + // order from least to most common + while (diff) { + if (diff & 1) { + // state change! + this.map[i].call(this, !!(state.data & (1 << i))); + } + diff = diff >> 1; + i++; } + this.stateId = state.data; } - - if (!gl.vertexAttribDivisor) - { - var instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - - if (instanceExt) - { - gl.vertexAttribDivisor = function (a, b) { return instanceExt.vertexAttribDivisorANGLE(a, b); }; - - gl.drawElementsInstanced = function (a, b, c, d, e) { return instanceExt.drawElementsInstancedANGLE(a, b, c, d, e); }; - - gl.drawArraysInstanced = function (a, b, c, d) { return instanceExt.drawArraysInstancedANGLE(a, b, c, d); }; - } - else - { - this.hasInstance = false; - } + // based on the above settings we check for specific modes.. + // for example if blend is active we check and set the blend modes + // or of polygon offset is active we check the poly depth. + for (var i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); } - - this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex; }; - /** - * Binds geometry so that is can be drawn. Creating a Vao if required + * Sets the state, when previous state is unknown * - * @param {PIXI.Geometry} geometry instance of geometry to bind - * @param {PIXI.Shader} [shader] instance of shader to use vao for + * @param {*} state - The state to set */ - GeometrySystem.prototype.bind = function bind (geometry, shader) - { - shader = shader || this.renderer.shader.shader; - - var ref = this; - var gl = ref.gl; - - // not sure the best way to address this.. - // currently different shaders require different VAOs for the same geometry - // Still mulling over the best way to solve this one.. - // will likely need to modify the shader attribute locations at run time! - var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - - if (!vaos) - { - this.managedGeometries[geometry.id] = geometry; - geometry.disposeRunner.add(this); - geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; + StateSystem.prototype.forceState = function (state) { + state = state || this.defaultState; + for (var i = 0; i < this.map.length; i++) { + this.map[i].call(this, !!(state.data & (1 << i))); } - - var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); - - this._activeGeometry = geometry; - - if (this._activeVao !== vao) - { - this._activeVao = vao; - - if (this.hasVao) - { - gl.bindVertexArray(vao); - } - else - { - this.activateVao(geometry, shader.program); - } + for (var i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); } - - // TODO - optimise later! - // don't need to loop through if nothing changed! - // maybe look to add an 'autoupdate' to geometry? - this.updateBuffers(); + this.stateId = state.data; }; - /** - * Reset and unbind any active VAO and geometry + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. */ - GeometrySystem.prototype.reset = function reset () - { - this.unbind(); + StateSystem.prototype.setBlend = function (value) { + this.updateCheck(StateSystem.checkBlendMode, value); + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); }; - /** - * Update buffers - * @protected + * Enables or disable polygon offset fill + * + * @param {boolean} value - Turn on or off webgl polygon offset testing. */ - GeometrySystem.prototype.updateBuffers = function updateBuffers () - { - var geometry = this._activeGeometry; - var ref = this; - var gl = ref.gl; - - for (var i = 0; i < geometry.buffers.length; i++) - { - var buffer = geometry.buffers[i]; - - var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - - if (buffer._updateID !== glBuffer.updateID) - { - glBuffer.updateID = buffer._updateID; - - // TODO can cache this on buffer! maybe added a getter / setter? - var type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; - - // TODO this could change if the VAO changes... - // need to come up with a better way to cache.. - // if (this.boundBuffers[type] !== glBuffer) - // { - // this.boundBuffers[type] = glBuffer; - gl.bindBuffer(type, glBuffer.buffer); - // } - - this._boundBuffer = glBuffer; - - if (glBuffer.byteLength >= buffer.data.byteLength) - { - // offset is always zero for now! - gl.bufferSubData(type, 0, buffer.data); - } - else - { - var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW; - - glBuffer.byteLength = buffer.data.byteLength; - gl.bufferData(type, buffer.data, drawType); - } - } - } + StateSystem.prototype.setOffset = function (value) { + this.updateCheck(StateSystem.checkPolygonOffset, value); + this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL); }; - /** - * Check compability between a geometry and a program - * @protected - * @param {PIXI.Geometry} geometry - Geometry instance - * @param {PIXI.Program} program - Program instance + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. */ - GeometrySystem.prototype.checkCompatibility = function checkCompatibility (geometry, program) - { - // geometry must have at least all the attributes that the shader requires. - var geometryAttributes = geometry.attributes; - var shaderAttributes = program.attributeData; - - for (var j in shaderAttributes) - { - if (!geometryAttributes[j]) - { - throw new Error(("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute")); - } - } + StateSystem.prototype.setDepthTest = function (value) { + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); }; - /** - * Takes a geometry and program and generates a unique signature for them. + * Sets whether to enable or disable cull face. * - * @param {PIXI.Geometry} geometry to get signature from - * @param {PIXI.Program} program to test geometry against - * @returns {String} Unique signature of the geometry and program - * @protected + * @param {boolean} value - Turn on or off webgl cull face. */ - GeometrySystem.prototype.getSignature = function getSignature (geometry, program) - { - var attribs = geometry.attributes; - var shaderAttributes = program.attributeData; - - var strings = ['g', geometry.id]; - - for (var i in attribs) - { - if (shaderAttributes[i]) - { - strings.push(i); - } - } - - return strings.join('-'); + StateSystem.prototype.setCullFace = function (value) { + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); }; - /** - * Creates or gets Vao with the same structure as the geometry and stores it on the geometry. - * If vao is created, it is bound automatically. + * Sets the gl front face. * - * @protected - * @param {PIXI.Geometry} geometry - Instance of geometry to to generate Vao for - * @param {PIXI.Program} program - Instance of program + * @param {boolean} value - true is clockwise and false is counter-clockwise */ - GeometrySystem.prototype.initGeometryVao = function initGeometryVao (geometry, program) - { - this.checkCompatibility(geometry, program); - - var gl = this.gl; - var CONTEXT_UID = this.CONTEXT_UID; - - var signature = this.getSignature(geometry, program); - - var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - - var vao = vaoObjectHash[signature]; - - if (vao) - { - // this will give us easy access to the vao - vaoObjectHash[program.id] = vao; - - return vao; - } - - var buffers = geometry.buffers; - var attributes = geometry.attributes; - var tempStride = {}; - var tempStart = {}; - - for (var j in buffers) - { - tempStride[j] = 0; - tempStart[j] = 0; - } - - for (var j$1 in attributes) - { - if (!attributes[j$1].size && program.attributeData[j$1]) - { - attributes[j$1].size = program.attributeData[j$1].size; - } - else if (!attributes[j$1].size) - { - console.warn(("PIXI Geometry attribute '" + j$1 + "' size cannot be determined (likely the bound shader does not have the attribute)")); // eslint-disable-line - } - - tempStride[attributes[j$1].buffer] += attributes[j$1].size * byteSizeMap$1[attributes[j$1].type]; - } - - for (var j$2 in attributes) - { - var attribute = attributes[j$2]; - var attribSize = attribute.size; - - if (attribute.stride === undefined) - { - if (tempStride[attribute.buffer] === attribSize * byteSizeMap$1[attribute.type]) - { - attribute.stride = 0; - } - else - { - attribute.stride = tempStride[attribute.buffer]; - } - } - - if (attribute.start === undefined) - { - attribute.start = tempStart[attribute.buffer]; - - tempStart[attribute.buffer] += attribSize * byteSizeMap$1[attribute.type]; - } - } - - vao = gl.createVertexArray(); - - gl.bindVertexArray(vao); - - // first update - and create the buffers! - // only create a gl buffer if it actually gets - for (var i = 0; i < buffers.length; i++) - { - var buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer()); - this.managedBuffers[buffer.id] = buffer; - buffer.disposeRunner.add(this); - } - - buffer._glBuffers[CONTEXT_UID].refCount++; - } - - // TODO - maybe make this a data object? - // lets wait to see if we need to first! - - this.activateVao(geometry, program); - - this._activeVao = vao; - - // add it to the cache! - vaoObjectHash[program.id] = vao; - vaoObjectHash[signature] = vao; - - return vao; + StateSystem.prototype.setFrontFace = function (value) { + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); }; - /** - * Disposes buffer - * @param {PIXI.Buffer} buffer buffer with data - * @param {boolean} [contextLost=false] If context was lost, we suppress deleteVertexArray + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. */ - GeometrySystem.prototype.disposeBuffer = function disposeBuffer (buffer, contextLost) - { - if (!this.managedBuffers[buffer.id]) - { + StateSystem.prototype.setBlendMode = function (value) { + if (value === this.blendMode) { return; } - - delete this.managedBuffers[buffer.id]; - - var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; + this.blendMode = value; + var mode = this.blendModes[value]; var gl = this.gl; - - buffer.disposeRunner.remove(this); - - if (!glBuffer) - { - return; + if (mode.length === 2) { + gl.blendFunc(mode[0], mode[1]); } - - if (!contextLost) - { - gl.deleteBuffer(glBuffer.buffer); + else { + gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + if (mode.length === 6) { + this._blendEq = true; + gl.blendEquationSeparate(mode[4], mode[5]); + } + else if (this._blendEq) { + this._blendEq = false; + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); } - - delete buffer._glBuffers[this.CONTEXT_UID]; }; - /** - * Disposes geometry - * @param {PIXI.Geometry} geometry Geometry with buffers. Only VAO will be disposed - * @param {boolean} [contextLost=false] If context was lost, we suppress deleteVertexArray + * Sets the polygon offset. + * + * @param {number} value - the polygon offset + * @param {number} scale - the polygon offset scale */ - GeometrySystem.prototype.disposeGeometry = function disposeGeometry (geometry, contextLost) - { - if (!this.managedGeometries[geometry.id]) - { - return; - } - - delete this.managedGeometries[geometry.id]; - - var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - var gl = this.gl; - var buffers = geometry.buffers; - - geometry.disposeRunner.remove(this); - - if (!vaos) - { - return; - } - - for (var i = 0; i < buffers.length; i++) - { - var buf = buffers[i]._glBuffers[this.CONTEXT_UID]; - - buf.refCount--; - if (buf.refCount === 0 && !contextLost) - { - this.disposeBuffer(buffers[i], contextLost); - } - } - - if (!contextLost) - { - for (var vaoId in vaos) - { - // delete only signatures, everything else are copies - if (vaoId[0] === 'g') - { - var vao = vaos[vaoId]; - - if (this._activeVao === vao) - { - this.unbind(); - } - gl.deleteVertexArray(vao); - } - } - } - - delete geometry.glVertexArrayObjects[this.CONTEXT_UID]; + StateSystem.prototype.setPolygonOffset = function (value, scale) { + this.gl.polygonOffset(value, scale); }; - + // used /** - * dispose all WebGL resources of all managed geometries and buffers - * @param {boolean} [contextLost=false] If context was lost, we suppress `gl.delete` calls + * Resets all the logic and disables the vaos */ - GeometrySystem.prototype.disposeAll = function disposeAll (contextLost) - { - var all = Object.keys(this.managedGeometries); - - for (var i = 0; i < all.length; i++) - { - this.disposeGeometry(this.managedGeometries[all[i]], contextLost); - } - all = Object.keys(this.managedBuffers); - for (var i$1 = 0; i$1 < all.length; i$1++) - { - this.disposeBuffer(this.managedBuffers[all[i$1]], contextLost); - } + StateSystem.prototype.reset = function () { + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + this.forceState(this.defaultState); + this._blendEq = true; + this.blendMode = -1; + this.setBlendMode(0); }; - /** - * Activate vertex array object + * checks to see which updates should be checked based on which settings have been activated. + * For example, if blend is enabled then we should check the blend modes each time the state is changed + * or if polygon fill is activated then we need to check if the polygon offset changes. + * The idea is that we only check what we have too. * - * @protected - * @param {PIXI.Geometry} geometry - Geometry instance - * @param {PIXI.Program} program - Shader program instance + * @param {Function} func - the checking function to add or remove + * @param {boolean} value - should the check function be added or removed. */ - GeometrySystem.prototype.activateVao = function activateVao (geometry, program) - { - var gl = this.gl; - var CONTEXT_UID = this.CONTEXT_UID; - var buffers = geometry.buffers; - var attributes = geometry.attributes; - - if (geometry.indexBuffer) - { - // first update the index buffer if we have one.. - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, geometry.indexBuffer._glBuffers[CONTEXT_UID].buffer); + StateSystem.prototype.updateCheck = function (func, value) { + var index = this.checks.indexOf(func); + if (value && index === -1) { + this.checks.push(func); } - - var lastBuffer = null; - - // add a new one! - for (var j in attributes) - { - var attribute = attributes[j]; - var buffer = buffers[attribute.buffer]; - var glBuffer = buffer._glBuffers[CONTEXT_UID]; - - if (program.attributeData[j]) - { - if (lastBuffer !== glBuffer) - { - gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); - - lastBuffer = glBuffer; - } - - var location = program.attributeData[j].location; - - // TODO introduce state again - // we can optimise this for older devices that have no VAOs - gl.enableVertexAttribArray(location); - - gl.vertexAttribPointer(location, - attribute.size, - attribute.type || gl.FLOAT, - attribute.normalized, - attribute.stride, - attribute.start); - - if (attribute.instance) - { - // TODO calculate instance count based of this... - if (this.hasInstance) - { - gl.vertexAttribDivisor(location, 1); - } - else - { - throw new Error('geometry error, GPU Instancing is not supported on this device'); - } - } - } + else if (!value && index !== -1) { + this.checks.splice(index, 1); } }; - /** - * Draw the geometry + * A private little wrapper function that we call to check the blend mode. * - * @param {Number} type - the type primitive to render - * @param {Number} [size] - the number of elements to be rendered - * @param {Number} [start] - Starting index - * @param {Number} [instanceCount] - the number of instances of the set of elements to execute + * @static + * @private + * @param {PIXI.StateSystem} System - the System to perform the state check on + * @param {PIXI.State} state - the state that the blendMode will pulled from */ - GeometrySystem.prototype.draw = function draw (type, size, start, instanceCount) - { - var ref = this; - var gl = ref.gl; - var geometry = this._activeGeometry; - - // TODO.. this should not change so maybe cache the function? - - if (geometry.indexBuffer) - { - var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT; - var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; - - if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) - { - if (geometry.instanced) - { - /* eslint-disable max-len */ - gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1); - /* eslint-enable max-len */ - } - else - { - /* eslint-disable max-len */ - gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize); - /* eslint-enable max-len */ - } - } - else - { - console.warn('unsupported index buffer type: uint32'); - } - } - else if (geometry.instanced) - { - // TODO need a better way to calculate size.. - gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || geometry.getSize()); - } - - return this; + StateSystem.checkBlendMode = function (system, state) { + system.setBlendMode(state.blendMode); }; - /** - * Unbind/reset everything - * @protected + * A private little wrapper function that we call to check the polygon offset. + * + * @static + * @private + * @param {PIXI.StateSystem} System - the System to perform the state check on + * @param {PIXI.State} state - the state that the blendMode will pulled from */ - GeometrySystem.prototype.unbind = function unbind () - { - this.gl.bindVertexArray(null); - this._activeVao = null; - this._activeGeometry = null; + StateSystem.checkPolygonOffset = function (system, state) { + system.setPolygonOffset(1, state.polygonOffset); }; - - return GeometrySystem; + return StateSystem; }(System)); /** - * Component for masked elements - * - * Holds mask mode and temporary data about current mask + * System plugin to the renderer to manage texture garbage collection on the GPU, + * ensuring that it does not get clogged up with textures that are no longer being used. * * @class - * @memberof PIXI + * @memberof PIXI.systems + * @extends PIXI.System */ -var MaskData = function MaskData(maskObject) -{ +var TextureGCSystem = /** @class */ (function (_super) { + __extends(TextureGCSystem, _super); /** - * Mask type - * @member {PIXI.MASK_TYPES} + * @param {PIXI.Renderer} renderer - The renderer this System works for. */ - this.type = constants.MASK_TYPES.NONE; - + function TextureGCSystem(renderer) { + var _this = _super.call(this, renderer) || this; + /** + * Count + * @member {number} + * @readonly + */ + _this.count = 0; + /** + * Check count + * @member {number} + * @readonly + */ + _this.checkCount = 0; + /** + * Maximum idle time, in seconds + * @member {number} + * @see PIXI.settings.GC_MAX_IDLE + */ + _this.maxIdle = settings.settings.GC_MAX_IDLE; + /** + * Maximum number of item to check + * @member {number} + * @see PIXI.settings.GC_MAX_CHECK_COUNT + */ + _this.checkCountMax = settings.settings.GC_MAX_CHECK_COUNT; + /** + * Current garabage collection mode + * @member {PIXI.GC_MODES} + * @see PIXI.settings.GC_MODE + */ + _this.mode = settings.settings.GC_MODE; + return _this; + } /** - * Whether we know the mask type beforehand - * @member {boolean} - * @default true + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU */ - this.autoDetect = true; - + TextureGCSystem.prototype.postrender = function () { + if (!this.renderer.renderingToScreen) { + return; + } + this.count++; + if (this.mode === constants.GC_MODES.MANUAL) { + return; + } + this.checkCount++; + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + this.run(); + } + }; /** - * Which element we use to mask - * @member {PIXI.DisplayObject} + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU */ - this.maskObject = maskObject || null; - + TextureGCSystem.prototype.run = function () { + var tm = this.renderer.texture; + var managedTextures = tm.managedTextures; + var wasRemoved = false; + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + // only supports non generated textures at the moment! + if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + if (wasRemoved) { + var j = 0; + for (var i = 0; i < managedTextures.length; i++) { + if (managedTextures[i] !== null) { + managedTextures[j++] = managedTextures[i]; + } + } + managedTextures.length = j; + } + }; /** - * Whether it belongs to MaskSystem pool - * @member {boolean} + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. */ - this.pooled = false; + TextureGCSystem.prototype.unload = function (displayObject) { + var _a; + var tm = this.renderer.texture; + // only destroy non generated textures + if ((_a = displayObject._texture) === null || _a === void 0 ? void 0 : _a.framebuffer) { + tm.destroyTexture(displayObject._texture); + } + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + return TextureGCSystem; +}(System)); + +/** + * Internal texture for WebGL context + * @class + * @memberof PIXI + */ +var GLTexture = /** @class */ (function () { + function GLTexture(texture) { + /** + * The WebGL texture + * @member {WebGLTexture} + */ + this.texture = texture; + /** + * Width of texture that was used in texImage2D + * @member {number} + */ + this.width = -1; + /** + * Height of texture that was used in texImage2D + * @member {number} + */ + this.height = -1; + /** + * Texture contents dirty flag + * @member {number} + */ + this.dirtyId = -1; + /** + * Texture style dirty flag + * @member {number} + */ + this.dirtyStyleId = -1; + /** + * Whether mip levels has to be generated + * @member {boolean} + */ + this.mipmap = false; + /** + * WrapMode copied from baseTexture + * @member {number} + */ + this.wrapMode = 33071; + /** + * Type copied from baseTexture + * @member {number} + */ + this.type = 6408; + /** + * Type copied from baseTexture + * @member {number} + */ + this.internalFormat = 5121; + } + return GLTexture; +}()); +/** + * System plugin to the renderer to manage textures. + * + * @class + * @extends PIXI.System + * @memberof PIXI.systems + */ +var TextureSystem = /** @class */ (function (_super) { + __extends(TextureSystem, _super); /** - * Indicator of the type - * @member {boolean} + * @param {PIXI.Renderer} renderer - The renderer this System works for. */ - this.isMaskData = true; - + function TextureSystem(renderer) { + var _this = _super.call(this, renderer) || this; + // TODO set to max textures... + /** + * Bound textures + * @member {PIXI.BaseTexture[]} + * @readonly + */ + _this.boundTextures = []; + /** + * Current location + * @member {number} + * @readonly + */ + _this.currentLocation = -1; + /** + * List of managed textures + * @member {PIXI.BaseTexture[]} + * @readonly + */ + _this.managedTextures = []; + /** + * Did someone temper with textures state? We'll overwrite them when we need to unbind something. + * @member {boolean} + * @private + */ + _this._unknownBoundTextures = false; + /** + * BaseTexture value that shows that we don't know what is bound + * @member {PIXI.BaseTexture} + * @readonly + */ + _this.unknownTexture = new BaseTexture(); + return _this; + } /** - * Stencil counter above the mask in stack - * @member {number} + * Sets up the renderer context and necessary buffers. + */ + TextureSystem.prototype.contextChange = function () { + var gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.webGLVersion = this.renderer.context.webGLVersion; + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.boundTextures.length = maxTextures; + for (var i = 0; i < maxTextures; i++) { + this.boundTextures[i] = null; + } + // TODO move this.. to a nice make empty textures class.. + this.emptyTextures = {}; + var emptyTexture2D = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D; + this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); + for (var i = 0; i < 6; i++) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + } + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + for (var i = 0; i < this.boundTextures.length; i++) { + this.bind(null, i); + } + }; + /** + * Bind a texture to a specific location + * + * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)` + * + * @param {PIXI.Texture|PIXI.BaseTexture} texture_ - Texture to bind + * @param {number} [location=0] - Location to bind at + */ + TextureSystem.prototype.bind = function (texture, location) { + if (location === void 0) { location = 0; } + var gl = this.gl; + if (texture) { + texture = texture.castToBaseTexture(); + if (texture.parentTextureArray) { + // cannot bind partial texture + // TODO: report a warning + return; + } + if (texture.valid) { + texture.touched = this.renderer.textureGC.count; + var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + if (this.boundTextures[location] !== texture) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(texture.target, glTexture.texture); + } + if (glTexture.dirtyId !== texture.dirtyId) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + this.updateTexture(texture); + } + this.boundTextures[location] = texture; + } + } + else { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture); + this.boundTextures[location] = null; + } + }; + /** + * Resets texture location and bound textures + * + * Actual `bind(null, i)` calls will be performed at next `unbind()` call + */ + TextureSystem.prototype.reset = function () { + this._unknownBoundTextures = true; + this.currentLocation = -1; + for (var i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.unknownTexture; + } + }; + /** + * Unbind a texture + * @param {PIXI.BaseTexture} texture - Texture to bind + */ + TextureSystem.prototype.unbind = function (texture) { + var _a = this, gl = _a.gl, boundTextures = _a.boundTextures; + if (this._unknownBoundTextures) { + this._unknownBoundTextures = false; + // someone changed webGL state, + // we have to be sure that our texture does not appear in multi-texture renderer samplers + for (var i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === this.unknownTexture) { + this.bind(null, i); + } + } + } + for (var i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === texture) { + if (this.currentLocation !== i) { + gl.activeTexture(gl.TEXTURE0 + i); + this.currentLocation = i; + } + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[texture.target].texture); + boundTextures[i] = null; + } + } + }; + /** + * Initialize a texture + * * @private + * @param {PIXI.BaseTexture} texture - Texture to initialize */ - this._stencilCounter = 0; + TextureSystem.prototype.initTexture = function (texture) { + var glTexture = new GLTexture(this.gl.createTexture()); + // guarantee an update.. + glTexture.dirtyId = -1; + texture._glTextures[this.CONTEXT_UID] = glTexture; + this.managedTextures.push(texture); + texture.on('dispose', this.destroyTexture, this); + return glTexture; + }; + TextureSystem.prototype.initTextureType = function (texture, glTexture) { + glTexture.internalFormat = texture.format; + glTexture.type = texture.type; + if (this.webGLVersion !== 2) { + return; + } + var gl = this.renderer.gl; + if (texture.type === gl.FLOAT + && texture.format === gl.RGBA) { + glTexture.internalFormat = gl.RGBA32F; + } + // that's WebGL1 HALF_FLOAT_OES + // we have to convert it to WebGL HALF_FLOAT + if (texture.type === constants.TYPES.HALF_FLOAT) { + glTexture.type = gl.HALF_FLOAT; + } + if (glTexture.type === gl.HALF_FLOAT + && texture.format === gl.RGBA) { + glTexture.internalFormat = gl.RGBA16F; + } + }; /** - * Scissor counter above the mask in stack - * @member {number} + * Update a texture + * * @private + * @param {PIXI.BaseTexture} texture - Texture to initialize */ - this._scissorCounter = 0; - + TextureSystem.prototype.updateTexture = function (texture) { + var glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; + } + var renderer = this.renderer; + this.initTextureType(texture, glTexture); + if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) ; + else { + // default, renderTexture-like logic + var width = texture.realWidth; + var height = texture.realHeight; + var gl = renderer.gl; + if (glTexture.width !== width + || glTexture.height !== height + || glTexture.dirtyId < 0) { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null); + } + } + // lets only update what changes.. + if (texture.dirtyStyleId !== glTexture.dirtyStyleId) { + this.updateTextureStyle(texture); + } + glTexture.dirtyId = texture.dirtyId; + }; /** - * Scissor operation above the mask in stack. - * Null if _scissorCounter is zero, rectangle instance if positive. - * @member {PIXI.Rectangle} + * Deletes the texture from WebGL + * + * @private + * @param {PIXI.BaseTexture|PIXI.Texture} texture_ - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. */ - this._scissorRect = null; - + TextureSystem.prototype.destroyTexture = function (texture, skipRemove) { + var gl = this.gl; + texture = texture.castToBaseTexture(); + if (texture._glTextures[this.CONTEXT_UID]) { + this.unbind(texture); + gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture); + texture.off('dispose', this.destroyTexture, this); + delete texture._glTextures[this.CONTEXT_UID]; + if (!skipRemove) { + var i = this.managedTextures.indexOf(texture); + if (i !== -1) { + utils.removeItems(this.managedTextures, i, 1); + } + } + } + }; /** - * Targeted element. Temporary variable set by MaskSystem - * @member {PIXI.DisplayObject} + * Update texture style such as mipmap flag + * * @private + * @param {PIXI.BaseTexture} texture - Texture to update */ - this._target = null; -}; - -/** - * resets the mask data after popMask() - */ -MaskData.prototype.reset = function reset () -{ - if (this.pooled) - { - this.maskObject = null; - - this.type = constants.MASK_TYPES.NONE; - - this.autoDetect = true; - } - - this._target = null; -}; - -/** - * copies counters from maskData above, called from pushMask() - * @param {PIXI.MaskData|null} maskAbove - */ -MaskData.prototype.copyCountersOrReset = function copyCountersOrReset (maskAbove) -{ - if (maskAbove) - { - this._stencilCounter = maskAbove._stencilCounter; - this._scissorCounter = maskAbove._scissorCounter; - this._scissorRect = maskAbove._scissorRect; - } - else - { - this._stencilCounter = 0; - this._scissorCounter = 0; - this._scissorRect = null; - } -}; - -/** - * @method compileProgram - * @private - * @memberof PIXI.glCore.shader - * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} - * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. - * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. - * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations - * @return {WebGLProgram} the shader program - */ -function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) -{ - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - - var program = gl.createProgram(); - - gl.attachShader(program, glVertShader); - gl.attachShader(program, glFragShader); - - // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if (attributeLocations) - { - for (var i in attributeLocations) - { - gl.bindAttribLocation(program, attributeLocations[i], i); + TextureSystem.prototype.updateTextureStyle = function (texture) { + var glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; } - } - - gl.linkProgram(program); - - // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) - { - console.error('Pixi.js Error: Could not initialize shader.'); - console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); - console.error('gl.getError()', gl.getError()); - - // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') - { - console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + if ((texture.mipmap === constants.MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) { + glTexture.mipmap = false; } - - gl.deleteProgram(program); - program = null; - } - - // clean up some shaders - gl.deleteShader(glVertShader); - gl.deleteShader(glFragShader); - - return program; -} - -/** - * @private - * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} - * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER - * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. - * @return {WebGLShader} the shader - */ -function compileShader(gl, type, src) -{ - var shader = gl.createShader(type); - - gl.shaderSource(shader, src); - gl.compileShader(shader); - - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) - { - console.warn(src); - console.error(gl.getShaderInfoLog(shader)); - - return null; - } - - return shader; -} + else { + glTexture.mipmap = texture.mipmap >= 1; + } + if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) { + glTexture.wrapMode = constants.WRAP_MODES.CLAMP; + } + else { + glTexture.wrapMode = texture.wrapMode; + } + if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) ; + else { + this.setStyle(texture, glTexture); + } + glTexture.dirtyStyleId = texture.dirtyStyleId; + }; + /** + * Set style for texture + * + * @private + * @param {PIXI.BaseTexture} texture - Texture to update + * @param {PIXI.GLTexture} glTexture + */ + TextureSystem.prototype.setStyle = function (texture, glTexture) { + var gl = this.gl; + if (glTexture.mipmap) { + gl.generateMipmap(texture.target); + } + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode); + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode); + if (glTexture.mipmap) { + /* eslint-disable max-len */ + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === constants.SCALE_MODES.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering; + if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === constants.SCALE_MODES.LINEAR) { + var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT)); + gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level); + } + } + else { + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === constants.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + } + gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === constants.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + }; + return TextureSystem; +}(System)); /** - * @method defaultValue - * @memberof PIXI.glCore.shader - * @param type {String} Type of value - * @param size {Number} - * @private + * Systems are individual components to the Renderer pipeline. + * @namespace PIXI.systems */ -function defaultValue(type, size) -{ - switch (type) - { - case 'float': - return 0; - - case 'vec2': - return new Float32Array(2 * size); - - case 'vec3': - return new Float32Array(3 * size); - - case 'vec4': - return new Float32Array(4 * size); - - case 'int': - case 'sampler2D': - case 'sampler2DArray': - return 0; - - case 'ivec2': - return new Int32Array(2 * size); - - case 'ivec3': - return new Int32Array(3 * size); - - case 'ivec4': - return new Int32Array(4 * size); - - case 'bool': - return false; - - case 'bvec2': - - return booleanArray(2 * size); - - case 'bvec3': - return booleanArray(3 * size); - - case 'bvec4': - return booleanArray(4 * size); - - case 'mat2': - return new Float32Array([1, 0, - 0, 1]); - - case 'mat3': - return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); - - case 'mat4': - return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); - } - - return null; -} - -function booleanArray(size) -{ - var array = new Array(size); - - for (var i = 0; i < array.length; i++) - { - array[i] = false; - } - - return array; -} -var unknownContext = {}; -var context = unknownContext; +var systems = ({ + FilterSystem: FilterSystem, + BatchSystem: BatchSystem, + ContextSystem: ContextSystem, + FramebufferSystem: FramebufferSystem, + GeometrySystem: GeometrySystem, + MaskSystem: MaskSystem, + ScissorSystem: ScissorSystem, + StencilSystem: StencilSystem, + ProjectionSystem: ProjectionSystem, + RenderTextureSystem: RenderTextureSystem, + ShaderSystem: ShaderSystem, + StateSystem: StateSystem, + TextureGCSystem: TextureGCSystem, + TextureSystem: TextureSystem +}); +var tempMatrix = new math.Matrix(); /** - * returns a little WebGL context to use for program inspection. + * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene. * - * @static - * @private - * @returns {WebGLRenderingContext} a gl context to test with + * @abstract + * @class + * @extends PIXI.utils.EventEmitter + * @memberof PIXI */ -function getTestContext() -{ - if (context === unknownContext || (context && context.isContextLost())) - { - var canvas = document.createElement('canvas'); - - var gl; - - if (settings.settings.PREFER_ENV >= constants.ENV.WEBGL2) - { - gl = canvas.getContext('webgl2', {}); - } - - if (!gl) - { - gl = canvas.getContext('webgl', {}) - || canvas.getContext('experimental-webgl', {}); - - if (!gl) - { - // fail, not able to get a context - gl = null; - } - else - { - // for shader testing.. - gl.getExtension('WEBGL_draw_buffers'); - } - } - - context = gl; - } - - return context; -} - -var maxFragmentPrecision; - -function getMaxFragmentPrecision() -{ - if (!maxFragmentPrecision) - { - maxFragmentPrecision = constants.PRECISION.MEDIUM; - var gl = getTestContext(); - - if (gl) - { - if (gl.getShaderPrecisionFormat) - { - var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); - - maxFragmentPrecision = shaderFragment.precision ? constants.PRECISION.HIGH : constants.PRECISION.MEDIUM; - } - } - } - - return maxFragmentPrecision; -} - -/** - * Sets the float precision on the shader, ensuring the device supports the request precision. - * If the precision is already present, it just ensures that the device is able to handle it. - * - * @private - * @param {string} src - The shader source - * @param {string} requestedPrecision - The request float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param {string} maxSupportedPrecision - The maximum precision the shader supports. - * - * @return {string} modified shader source - */ -function setPrecision(src, requestedPrecision, maxSupportedPrecision) -{ - if (src.substring(0, 9) !== 'precision') - { - // no precision supplied, so PixiJS will add the requested level. - var precision = requestedPrecision; - - // If highp is requested but not supported, downgrade precision to a level all devices support. - if (requestedPrecision === constants.PRECISION.HIGH && maxSupportedPrecision !== constants.PRECISION.HIGH) - { - precision = constants.PRECISION.MEDIUM; - } - - return ("precision " + precision + " float;\n" + src); - } - else if (maxSupportedPrecision !== constants.PRECISION.HIGH && src.substring(0, 15) === 'precision highp') - { - // precision was supplied, but at a level this device does not support, so downgrading to mediump. - return src.replace('precision highp', 'precision mediump'); - } - - return src; -} - -var GLSL_TO_SIZE = { - float: 1, - vec2: 2, - vec3: 3, - vec4: 4, - - int: 1, - ivec2: 2, - ivec3: 3, - ivec4: 4, - - bool: 1, - bvec2: 2, - bvec3: 3, - bvec4: 4, - - mat2: 4, - mat3: 9, - mat4: 16, - - sampler2D: 1, -}; - -/** - * @private - * @method mapSize - * @memberof PIXI.glCore.shader - * @param type {String} - * @return {Number} - */ -function mapSize(type) -{ - return GLSL_TO_SIZE[type]; -} - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - FLOAT: 'float', - FLOAT_VEC2: 'vec2', - FLOAT_VEC3: 'vec3', - FLOAT_VEC4: 'vec4', - - INT: 'int', - INT_VEC2: 'ivec2', - INT_VEC3: 'ivec3', - INT_VEC4: 'ivec4', - - BOOL: 'bool', - BOOL_VEC2: 'bvec2', - BOOL_VEC3: 'bvec3', - BOOL_VEC4: 'bvec4', - - FLOAT_MAT2: 'mat2', - FLOAT_MAT3: 'mat3', - FLOAT_MAT4: 'mat4', - - SAMPLER_2D: 'sampler2D', - SAMPLER_CUBE: 'samplerCube', - SAMPLER_2D_ARRAY: 'sampler2DArray', -}; - -function mapType(gl, type) -{ - if (!GL_TABLE) - { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); - - GL_TABLE = {}; - - for (var i = 0; i < typeNames.length; ++i) - { - var tn = typeNames[i]; - - GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; - } - } - - return GL_TABLE[type]; -} - -// cv = CachedValue -// v = value -// ud = uniformData -// uv = uniformValue -// l = location -var GLSL_TO_SINGLE_SETTERS_CACHED = { - - float: "\n if(cv !== v)\n {\n cv.v = v;\n gl.uniform1f(location, v)\n }", - - vec2: "\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(location, v[0], v[1])\n }", - - vec3: "\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }", - - vec4: 'gl.uniform4f(location, v[0], v[1], v[2], v[3])', - - int: 'gl.uniform1i(location, v)', - ivec2: 'gl.uniform2i(location, v[0], v[1])', - ivec3: 'gl.uniform3i(location, v[0], v[1], v[2])', - ivec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])', - - bool: 'gl.uniform1i(location, v)', - bvec2: 'gl.uniform2i(location, v[0], v[1])', - bvec3: 'gl.uniform3i(location, v[0], v[1], v[2])', - bvec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])', - - mat2: 'gl.uniformMatrix2fv(location, false, v)', - mat3: 'gl.uniformMatrix3fv(location, false, v)', - mat4: 'gl.uniformMatrix4fv(location, false, v)', - - sampler2D: 'gl.uniform1i(location, v)', - samplerCube: 'gl.uniform1i(location, v)', - sampler2DArray: 'gl.uniform1i(location, v)', -}; - -var GLSL_TO_ARRAY_SETTERS = { - - float: "gl.uniform1fv(location, v)", - - vec2: "gl.uniform2fv(location, v)", - vec3: "gl.uniform3fv(location, v)", - vec4: 'gl.uniform4fv(location, v)', - - mat4: 'gl.uniformMatrix4fv(location, false, v)', - mat3: 'gl.uniformMatrix3fv(location, false, v)', - mat2: 'gl.uniformMatrix2fv(location, false, v)', - - int: 'gl.uniform1iv(location, v)', - ivec2: 'gl.uniform2iv(location, v)', - ivec3: 'gl.uniform3iv(location, v)', - ivec4: 'gl.uniform4iv(location, v)', - - bool: 'gl.uniform1iv(location, v)', - bvec2: 'gl.uniform2iv(location, v)', - bvec3: 'gl.uniform3iv(location, v)', - bvec4: 'gl.uniform4iv(location, v)', - - sampler2D: 'gl.uniform1iv(location, v)', - samplerCube: 'gl.uniform1iv(location, v)', - sampler2DArray: 'gl.uniform1iv(location, v)', -}; - -function generateUniformsSync(group, uniformData) -{ - var textureCount = 0; - var func = "var v = null;\n var cv = null\n var gl = renderer.gl"; - - for (var i in group.uniforms) - { - var data = uniformData[i]; - - if (!data) - { - if (group.uniforms[i].group) - { - func += "\n renderer.shader.syncUniformGroup(uv." + i + ");\n "; - } - - continue; - } - - // TODO && uniformData[i].value !== 0 <-- do we still need this? - if (data.type === 'float' && data.size === 1) - { - func += "\n if(uv." + i + " !== ud." + i + ".value)\n {\n ud." + i + ".value = uv." + i + "\n gl.uniform1f(ud." + i + ".location, uv." + i + ")\n }\n"; - } - /* eslint-disable max-len */ - else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) - /* eslint-disable max-len */ - { - func += "\n renderer.texture.bind(uv." + i + ", " + textureCount + ");\n\n if(ud." + i + ".value !== " + textureCount + ")\n {\n ud." + i + ".value = " + textureCount + ";\n gl.uniform1i(ud." + i + ".location, " + textureCount + ");\n; // eslint-disable-line max-len\n }\n"; - - textureCount++; - } - else if (data.type === 'mat3' && data.size === 1) - { - if (group.uniforms[i].a !== undefined) - { - // TODO and some smart caching dirty ids here! - func += "\n gl.uniformMatrix3fv(ud." + i + ".location, false, uv." + i + ".toArray(true));\n \n"; - } - else - { - func += "\n gl.uniformMatrix3fv(ud." + i + ".location, false, uv." + i + ");\n \n"; - } - } - else if (data.type === 'vec2' && data.size === 1) - { - // TODO - do we need both here? - // maybe we can get away with only using points? - if (group.uniforms[i].x !== undefined) - { - func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud." + i + ".location, v.x, v.y);\n }\n"; - } - else - { - func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud." + i + ".location, v[0], v[1]);\n }\n \n"; - } - } - else if (data.type === 'vec4' && data.size === 1) - { - // TODO - do we need both here? - // maybe we can get away with only using points? - if (group.uniforms[i].width !== undefined) - { - func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud." + i + ".location, v.x, v.y, v.width, v.height)\n }\n"; - } - else - { - func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud." + i + ".location, v[0], v[1], v[2], v[3])\n }\n \n"; - } - } - else - { - var templateType = (data.size === 1) ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS; - - var template = templateType[data.type].replace('location', ("ud." + i + ".location")); - - func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n " + template + ";\n"; - } - } - - return new Function('ud', 'uv', 'renderer', func); // eslint-disable-line no-new-func -} - -var fragTemplate = [ - 'precision mediump float;', - 'void main(void){', - 'float test = 0.1;', - '%forloop%', - 'gl_FragColor = vec4(0.0);', - '}' ].join('\n'); - -function checkMaxIfStatementsInShader(maxIfs, gl) -{ - if (maxIfs === 0) - { - throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); - } - - var shader = gl.createShader(gl.FRAGMENT_SHADER); - - while (true) // eslint-disable-line no-constant-condition - { - var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); - - gl.shaderSource(shader, fragmentSrc); - gl.compileShader(shader); - - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) - { - maxIfs = (maxIfs / 2) | 0; - } - else - { - // valid! - break; +var AbstractRenderer = /** @class */ (function (_super) { + __extends(AbstractRenderer, _super); + /** + * @param {string} system - The name of the system this renderer is for. + * @param {object} [options] - The optional renderer parameters. + * @param {number} [options.width=800] - The width of the screen. + * @param {number} [options.height=600] - The height of the screen. + * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. + * @param {boolean} [options.transparent=false] - If the render view is transparent. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1. + * @param {boolean} [options.antialias=false] - Sets antialias + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the WebGL context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + */ + function AbstractRenderer(type, options) { + if (type === void 0) { type = constants.RENDERER_TYPE.UNKNOWN; } + var _this = _super.call(this) || this; + // Add the default render options + options = Object.assign({}, settings.settings.RENDER_OPTIONS, options); + // Deprecation notice for renderer roundPixels option + if (options.roundPixels) { + settings.settings.ROUND_PIXELS = options.roundPixels; + utils.deprecation('5.0.0', 'Renderer roundPixels option is deprecated, please use PIXI.settings.ROUND_PIXELS', 2); } + /** + * The supplied constructor options. + * + * @member {Object} + * @readOnly + */ + _this.options = options; + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = type; + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight). + * + * Its safe to use as filterArea or hitArea for the whole stage. + * + * @member {PIXI.Rectangle} + */ + _this.screen = new math.Rectangle(0, 0, options.width, options.height); + /** + * The canvas element that everything is drawn to. + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + /** + * The resolution / device pixel ratio of the renderer. + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || settings.settings.RESOLUTION; + /** + * Whether the render view is transparent. + * + * @member {boolean} + */ + _this.transparent = options.transparent; + /** + * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically. + * + * @member {boolean} + */ + _this.autoDensity = options.autoDensity || options.autoResize || false; + // autoResize is deprecated, provides fallback support + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example, if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + /** + * The background color as a number. + * + * @member {number} + * @protected + */ + _this._backgroundColor = 0x000000; + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @protected + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + /** + * The background color as a string. + * + * @member {string} + * @protected + */ + _this._backgroundColorString = '#000000'; + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @protected + */ + _this._lastObjectRendered = null; + /** + * Collection of plugins. + * @readonly + * @member {object} + */ + _this.plugins = {}; + return _this; } - - return maxIfs; -} - -function generateIfTestSrc(maxIfs) -{ - var src = ''; - - for (var i = 0; i < maxIfs; ++i) - { - if (i > 0) - { - src += '\nelse '; + /** + * Initialize the plugins. + * + * @protected + * @param {object} staticMap - The dictionary of statically saved plugins. + */ + AbstractRenderer.prototype.initPlugins = function (staticMap) { + for (var o in staticMap) { + this.plugins[o] = new (staticMap[o])(this); } - - if (i < maxIfs - 1) - { - src += "if(test == " + i + ".0){}"; + }; + Object.defineProperty(AbstractRenderer.prototype, "width", { + /** + * Same as view.width, actual number of pixels in the canvas by horizontal. + * + * @member {number} + * @readonly + * @default 800 + */ + get: function () { + return this.view.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AbstractRenderer.prototype, "height", { + /** + * Same as view.height, actual number of pixels in the canvas by vertical. + * + * @member {number} + * @readonly + * @default 600 + */ + get: function () { + return this.view.height; + }, + enumerable: false, + configurable: true + }); + /** + * Resizes the screen and canvas to the specified width and height. + * Canvas dimensions are multiplied by resolution. + * + * @param {number} screenWidth - The new width of the screen. + * @param {number} screenHeight - The new height of the screen. + */ + AbstractRenderer.prototype.resize = function (screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + if (this.autoDensity) { + this.view.style.width = screenWidth + "px"; + this.view.style.height = screenHeight + "px"; } - } - - return src; -} - -// Cache the result to prevent running this over and over -var unsafeEval; - -/** - * Not all platforms allow to generate function code (e.g., `new Function`). - * this provides the platform-level detection. - * - * @private - * @returns {boolean} - */ -function unsafeEvalSupported() -{ - if (typeof unsafeEval === 'boolean') - { - return unsafeEval; - } - - try - { - /* eslint-disable no-new-func */ - var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;'); - /* eslint-enable no-new-func */ - - unsafeEval = func({ a: 'b' }, 'a', 'b') === true; - } - catch (e) - { - unsafeEval = false; - } - - return unsafeEval; -} - -var defaultFragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"; - -var defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"; - -// import * as from '../systems/shader/shader'; - -var UID$3 = 0; - -var nameCache = {}; - -/** - * Helper class to create a shader program. - * - * @class - * @memberof PIXI - */ -var Program = function Program(vertexSrc, fragmentSrc, name) -{ - if ( name === void 0 ) name = 'pixi-shader'; - - this.id = UID$3++; - + /** + * Fired after view has been resized. + * + * @event PIXI.Renderer#resize + * @param {number} screenWidth - The new width of the screen. + * @param {number} screenHeight - The new height of the screen. + */ + this.emit('resize', screenWidth, screenHeight); + }; /** - * The vertex shader. + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. * - * @member {string} + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from. + * @param {PIXI.SCALE_MODES} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated. + * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered, + * if no region is specified, defaults to the local bounds of the displayObject. + * @return {PIXI.RenderTexture} A texture of the graphics object. */ - this.vertexSrc = vertexSrc || Program.defaultVertexSrc; - + AbstractRenderer.prototype.generateTexture = function (displayObject, scaleMode, resolution, region) { + region = region || displayObject.getLocalBounds(null, true); + // minimum texture size is 1x1, 0x0 will throw an error + if (region.width === 0) + { region.width = 1; } + if (region.height === 0) + { region.height = 1; } + var renderTexture = RenderTexture.create({ + width: region.width | 0, + height: region.height | 0, + scaleMode: scaleMode, + resolution: resolution, + }); + tempMatrix.tx = -region.x; + tempMatrix.ty = -region.y; + this.render(displayObject, renderTexture, false, tempMatrix, !!displayObject.parent); + return renderTexture; + }; /** - * The fragment shader. + * Removes everything from the renderer and optionally removes the Canvas DOM element. * - * @member {string} + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. */ - this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc; - - this.vertexSrc = this.vertexSrc.trim(); - this.fragmentSrc = this.fragmentSrc.trim(); - - if (this.vertexSrc.substring(0, 8) !== '#version') - { - name = name.replace(/\s+/g, '-'); - - if (nameCache[name]) - { - nameCache[name]++; - name += "-" + (nameCache[name]); + AbstractRenderer.prototype.destroy = function (removeView) { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; } - else - { - nameCache[name] = 1; + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); } - - this.vertexSrc = "#define SHADER_NAME " + name + "\n" + (this.vertexSrc); - this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + (this.fragmentSrc); - - this.vertexSrc = setPrecision(this.vertexSrc, settings.settings.PRECISION_VERTEX, constants.PRECISION.HIGH); - this.fragmentSrc = setPrecision(this.fragmentSrc, settings.settings.PRECISION_FRAGMENT, getMaxFragmentPrecision()); - } - - // currently this does not extract structs only default types - this.extractData(this.vertexSrc, this.fragmentSrc); - - // this is where we store shader references.. - this.glPrograms = {}; - - this.syncUniforms = null; -}; - -var staticAccessors = { defaultVertexSrc: { configurable: true },defaultFragmentSrc: { configurable: true } }; + var thisAny = this; + // null-ing all objects, that's a tradition! + thisAny.plugins = null; + thisAny.type = constants.RENDERER_TYPE.UNKNOWN; + thisAny.view = null; + thisAny.screen = null; + thisAny._tempDisplayObjectParent = null; + thisAny.options = null; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + this._lastObjectRendered = null; + }; + Object.defineProperty(AbstractRenderer.prototype, "backgroundColor", { + /** + * The background color to fill if not transparent + * + * @member {number} + */ + get: function () { + return this._backgroundColor; + }, + set: function (value) { + this._backgroundColor = value; + this._backgroundColorString = utils.hex2string(value); + utils.hex2rgb(value, this._backgroundColorRgba); + }, + enumerable: false, + configurable: true + }); + return AbstractRenderer; +}(utils.EventEmitter)); /** - * Extracts the data for a buy creating a small test program - * or reading the src directly. - * @protected + * The Renderer draws the scene and all its content onto a WebGL enabled canvas. * - * @param {string} [vertexSrc] - The source of the vertex shader. - * @param {string} [fragmentSrc] - The source of the fragment shader. - */ -Program.prototype.extractData = function extractData (vertexSrc, fragmentSrc) -{ - var gl = getTestContext(); - - if (gl) - { - var program = compileProgram(gl, vertexSrc, fragmentSrc); - - this.attributeData = this.getAttributeData(program, gl); - this.uniformData = this.getUniformData(program, gl); - - gl.deleteProgram(program); - } - else - { - this.uniformData = {}; - this.attributeData = {}; - } -}; - -/** - * returns the attribute data from the program - * @private + * This renderer should be used for browsers that support WebGL. * - * @param {WebGLProgram} [program] - the WebGL program - * @param {WebGLRenderingContext} [gl] - the WebGL context + * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything! * - * @returns {object} the attribute data for this program + * @class + * @memberof PIXI + * @extends PIXI.AbstractRenderer */ -Program.prototype.getAttributeData = function getAttributeData (program, gl) -{ - var attributes = {}; - var attributesArray = []; - - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - - for (var i = 0; i < totalAttributes; i++) - { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); - - /*eslint-disable */ - var data = { - type: type, - name: attribData.name, - size: mapSize(type), - location: 0, - }; - /* eslint-enable */ - - attributes[attribData.name] = data; - attributesArray.push(data); - } - - attributesArray.sort(function (a, b) { return (a.name > b.name) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow - - for (var i$1 = 0; i$1 < attributesArray.length; i$1++) - { - attributesArray[i$1].location = i$1; - } - - return attributes; -}; - -/** - * returns the uniform data from the program - * @private - * - * @param {webGL-program} [program] - the webgl program - * @param {context} [gl] - the WebGL context - * - * @returns {object} the uniform data for this program - */ -Program.prototype.getUniformData = function getUniformData (program, gl) -{ - var uniforms = {}; - - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - - // TODO expose this as a prop? - // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - - for (var i = 0; i < totalUniforms; i++) - { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ''); - - var isArray = uniformData.name.match(/\[.*?\]/, ''); - var type = mapType(gl, uniformData.type); - - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: defaultValue(type, uniformData.size), +var Renderer = /** @class */ (function (_super) { + __extends(Renderer, _super); + /** + * @param {object} [options] - The optional renderer parameters. + * @param {number} [options.width=800] - The width of the screen. + * @param {number} [options.height=600] - The height of the screen. + * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. + * @param {boolean} [options.transparent=false] - If the render view is transparent. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1. + * @param {boolean} [options.antialias=false] - Sets antialias. If not available natively then FXAA + * antialiasing is used. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the WebGL context. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {string} [options.powerPreference] - Parameter passed to WebGL context, set to "high-performance" + * for devices with dual graphics card. + * @param {object} [options.context] - If WebGL context already exists, all parameters must be taken from it. + * @public + */ + function Renderer(options) { + var _this = _super.call(this, constants.RENDERER_TYPE.WEBGL, options) || this; + // the options will have been modified here in the super constructor with pixi's default settings.. + options = _this.options; + /** + * WebGL context, set by the contextSystem (this.context) + * + * @readonly + * @member {WebGLRenderingContext} + */ + _this.gl = null; + _this.CONTEXT_UID = 0; + // TODO legacy! + /** + * Internal signal instances of **runner**, these + * are assigned to each system created. + * @see PIXI.Runner + * @name PIXI.Renderer#runners + * @private + * @type {object} + * @readonly + * @property {PIXI.Runner} destroy - Destroy runner + * @property {PIXI.Runner} contextChange - Context change runner + * @property {PIXI.Runner} reset - Reset runner + * @property {PIXI.Runner} update - Update runner + * @property {PIXI.Runner} postrender - Post-render runner + * @property {PIXI.Runner} prerender - Pre-render runner + * @property {PIXI.Runner} resize - Resize runner + */ + _this.runners = { + destroy: new runner.Runner('destroy'), + contextChange: new runner.Runner('contextChange'), + reset: new runner.Runner('reset'), + update: new runner.Runner('update'), + postrender: new runner.Runner('postrender'), + prerender: new runner.Runner('prerender'), + resize: new runner.Runner('resize'), }; - /* eslint-enable */ - } - - return uniforms; -}; - -/** - * The default vertex shader source - * - * @static - * @constant - * @member {string} - */ -staticAccessors.defaultVertexSrc.get = function () -{ - return defaultVertex; -}; - -/** - * The default fragment shader source - * - * @static - * @constant - * @member {string} - */ -staticAccessors.defaultFragmentSrc.get = function () -{ - return defaultFragment; -}; - -/** - * A short hand function to create a program based of a vertex and fragment shader - * this method will also check to see if there is a cached program. - * - * @param {string} [vertexSrc] - The source of the vertex shader. - * @param {string} [fragmentSrc] - The source of the fragment shader. - * @param {string} [name=pixi-shader] - Name for shader - * - * @returns {PIXI.Program} an shiny new Pixi shader! - */ -Program.from = function from (vertexSrc, fragmentSrc, name) -{ - var key = vertexSrc + fragmentSrc; - - var program = utils.ProgramCache[key]; - - if (!program) - { - utils.ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name); + /** + * Global uniforms + * @member {PIXI.UniformGroup} + */ + _this.globalUniforms = new UniformGroup({ + projectionMatrix: new math.Matrix(), + }, true); + /** + * Mask system instance + * @member {PIXI.systems.MaskSystem} mask + * @memberof PIXI.Renderer# + * @readonly + */ + _this.addSystem(MaskSystem, 'mask') + /** + * Context system instance + * @member {PIXI.systems.ContextSystem} context + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(ContextSystem, 'context') + /** + * State system instance + * @member {PIXI.systems.StateSystem} state + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(StateSystem, 'state') + /** + * Shader system instance + * @member {PIXI.systems.ShaderSystem} shader + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(ShaderSystem, 'shader') + /** + * Texture system instance + * @member {PIXI.systems.TextureSystem} texture + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(TextureSystem, 'texture') + /** + * Geometry system instance + * @member {PIXI.systems.GeometrySystem} geometry + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(GeometrySystem, 'geometry') + /** + * Framebuffer system instance + * @member {PIXI.systems.FramebufferSystem} framebuffer + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(FramebufferSystem, 'framebuffer') + /** + * Scissor system instance + * @member {PIXI.systems.ScissorSystem} scissor + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(ScissorSystem, 'scissor') + /** + * Stencil system instance + * @member {PIXI.systems.StencilSystem} stencil + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(StencilSystem, 'stencil') + /** + * Projection system instance + * @member {PIXI.systems.ProjectionSystem} projection + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(ProjectionSystem, 'projection') + /** + * Texture garbage collector system instance + * @member {PIXI.systems.TextureGCSystem} textureGC + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(TextureGCSystem, 'textureGC') + /** + * Filter system instance + * @member {PIXI.systems.FilterSystem} filter + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(FilterSystem, 'filter') + /** + * RenderTexture system instance + * @member {PIXI.systems.RenderTextureSystem} renderTexture + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(RenderTextureSystem, 'renderTexture') + /** + * Batch system instance + * @member {PIXI.systems.BatchSystem} batch + * @memberof PIXI.Renderer# + * @readonly + */ + .addSystem(BatchSystem, 'batch'); + _this.initPlugins(Renderer.__plugins); + /** + * The options passed in to create a new WebGL context. + */ + if (options.context) { + _this.context.initFromContext(options.context); + } + else { + _this.context.initFromOptions({ + alpha: !!_this.transparent, + antialias: options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer, + powerPreference: _this.options.powerPreference, + }); + } + /** + * Flag if we are rendering to the screen vs renderTexture + * @member {boolean} + * @readonly + * @default true + */ + _this.renderingToScreen = true; + utils.sayHello(_this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1'); + _this.resize(_this.options.width, _this.options.height); + return _this; } - - return program; -}; - -Object.defineProperties( Program, staticAccessors ); - -/** - * A helper class for shaders - * - * @class - * @memberof PIXI - */ -var Shader = function Shader(program, uniforms) -{ /** - * Program that the shader uses + * Create renderer if WebGL is available. Overrideable + * by the **@pixi/canvas-renderer** package to allow fallback. + * throws error if WebGL is not available. + * @static + * @private + */ + Renderer.create = function (options) { + if (utils.isWebGLSupported()) { + return new Renderer(options); + } + throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.'); + }; + /** + * Add a new system to the renderer. + * @param {Function} ClassRef - Class reference + * @param {string} [name] - Property name for system, if not specified + * will use a static `name` property on the class itself. This + * name will be assigned as s property on the Renderer so make + * sure it doesn't collide with properties on Renderer. + * @return {PIXI.Renderer} Return instance of renderer + */ + Renderer.prototype.addSystem = function (ClassRef, name) { + if (!name) { + name = ClassRef.name; + } + var system = new ClassRef(this); + if (this[name]) { + throw new Error("Whoops! The name \"" + name + "\" is already in use"); + } + this[name] = system; + for (var i in this.runners) { + this.runners[i].add(system); + } + /** + * Fired after rendering finishes. + * + * @event PIXI.Renderer#postrender + */ + /** + * Fired before rendering starts. + * + * @event PIXI.Renderer#prerender + */ + /** + * Fired when the WebGL context is set. + * + * @event PIXI.Renderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return this; + }; + /** + * Renders the object to its WebGL view * - * @member {PIXI.Program} + * @param {PIXI.DisplayObject} displayObject - The object to be rendered. + * @param {PIXI.RenderTexture} [renderTexture] - The render texture to render to. + * @param {boolean} [clear=true] - Should the canvas be cleared before the new render. + * @param {PIXI.Matrix} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform=false] - Should we skip the update transform pass? */ - this.program = program; - - // lets see whats been passed in - // uniforms should be converted to a uniform group - if (uniforms) - { - if (uniforms instanceof UniformGroup) - { - this.uniformGroup = uniforms; + Renderer.prototype.render = function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + this.runners.prerender.emit(); + this.emit('prerender'); + // apply a transform at a GPU level + this.projection.transform = transform; + // no point rendering if our context has been blown up! + if (this.context.isLost) { + return; } - else - { - this.uniformGroup = new UniformGroup(uniforms); + if (!renderTexture) { + this._lastObjectRendered = displayObject; } - } - else - { - this.uniformGroup = new UniformGroup({}); - } - - // time to build some getters and setters! - // I guess down the line this could sort of generate an instruction list rather than use dirty ids? - // does the trick for now though! - for (var i in program.uniformData) - { - if (this.uniformGroup.uniforms[i] instanceof Array) - { - this.uniformGroup.uniforms[i] = new Float32Array(this.uniformGroup.uniforms[i]); + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.enableTempParent(); + displayObject.updateTransform(); + displayObject.disableTempParent(cacheParent); + // displayObject.hitArea = //TODO add a temp hit area } - } -}; - -var prototypeAccessors$2 = { uniforms: { configurable: true } }; - -// TODO move to shader system.. -Shader.prototype.checkUniformExists = function checkUniformExists (name, group) -{ - if (group.uniforms[name]) - { - return true; - } - - for (var i in group.uniforms) - { - var uniform = group.uniforms[i]; - - if (uniform.group) - { - if (this.checkUniformExists(name, uniform)) - { - return true; - } + this.renderTexture.bind(renderTexture); + this.batch.currentRenderer.start(); + if (clear !== undefined ? clear : this.clearBeforeRender) { + this.renderTexture.clear(); } - } - - return false; -}; - -Shader.prototype.destroy = function destroy () -{ - // usage count on programs? - // remove if not used! - this.uniformGroup = null; -}; - -/** - * Shader uniform values, shortcut for `uniformGroup.uniforms` - * @readonly - * @member {object} - */ -prototypeAccessors$2.uniforms.get = function () -{ - return this.uniformGroup.uniforms; -}; + displayObject.render(this); + // apply transform.. + this.batch.currentRenderer.flush(); + if (renderTexture) { + renderTexture.baseTexture.update(); + } + this.runners.postrender.emit(); + // reset transform after render + this.projection.transform = null; + this.emit('postrender'); + }; + /** + * Resizes the WebGL view to the specified width and height. + * + * @param {number} screenWidth - The new width of the screen. + * @param {number} screenHeight - The new height of the screen. + */ + Renderer.prototype.resize = function (screenWidth, screenHeight) { + _super.prototype.resize.call(this, screenWidth, screenHeight); + this.runners.resize.emit(screenWidth, screenHeight); + }; + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.Renderer} Returns itself. + */ + Renderer.prototype.reset = function () { + this.runners.reset.emit(); + return this; + }; + /** + * Clear the frame buffer + */ + Renderer.prototype.clear = function () { + this.renderTexture.bind(); + this.renderTexture.clear(); + }; + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + Renderer.prototype.destroy = function (removeView) { + this.runners.destroy.emit(); + for (var r in this.runners) { + this.runners[r].destroy(); + } + // call base destroy + _super.prototype.destroy.call(this, removeView); + // TODO nullify all the managers.. + this.gl = null; + }; + /** + * Adds a plugin to the renderer. + * + * @method + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + Renderer.registerPlugin = function (pluginName, ctor) { + Renderer.__plugins = Renderer.__plugins || {}; + Renderer.__plugins[pluginName] = ctor; + }; + return Renderer; +}(AbstractRenderer)); /** - * A short hand function to create a shader based of a vertex and fragment shader - * - * @param {string} [vertexSrc] - The source of the vertex shader. - * @param {string} [fragmentSrc] - The source of the fragment shader. - * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by + * the browser then this function will return a canvas renderer * - * @returns {PIXI.Shader} an shiny new Pixi shader! + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1 + * @param {boolean} [options.antialias=false] - sets antialias + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this + * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise + * it is ignored. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @return {PIXI.Renderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ -Shader.from = function from (vertexSrc, fragmentSrc, uniforms) -{ - var program = Program.from(vertexSrc, fragmentSrc); - - return new Shader(program, uniforms); -}; - -Object.defineProperties( Shader.prototype, prototypeAccessors$2 ); +function autoDetectRenderer(options) { + return Renderer.create(options); +} -/* eslint-disable max-len */ +var _default = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; -var BLEND = 0; -var OFFSET = 1; -var CULLING = 2; -var DEPTH_TEST = 3; -var WINDING = 4; +var defaultFilter = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; /** - * This is a WebGL state, and is is passed The WebGL StateManager. - * - * Each mesh rendered may require WebGL to be in a different state. - * For example you may want different blend mode or to enable polygon offsets + * Used by the batcher to draw batches. + * Each one of these contains all information required to draw a bound geometry. * * @class * @memberof PIXI */ -var State = function State() -{ - this.data = 0; - - this.blendMode = constants.BLEND_MODES.NORMAL; - this.polygonOffset = 0; - - this.blend = true; - // this.depthTest = true; -}; - -var prototypeAccessors$3 = { blend: { configurable: true },offsets: { configurable: true },culling: { configurable: true },depthTest: { configurable: true },clockwiseFrontFace: { configurable: true },blendMode: { configurable: true },polygonOffset: { configurable: true } }; - -/** - * Activates blending of the computed fragment color values - * - * @member {boolean} - */ -prototypeAccessors$3.blend.get = function () -{ - return !!(this.data & (1 << BLEND)); -}; - -prototypeAccessors$3.blend.set = function (value) // eslint-disable-line require-jsdoc -{ - if (!!(this.data & (1 << BLEND)) !== value) - { - this.data ^= (1 << BLEND); +var BatchDrawCall = /** @class */ (function () { + function BatchDrawCall() { + this.texArray = null; + this.blend = 0; + this.type = constants.DRAW_MODES.TRIANGLES; + this.start = 0; + this.size = 0; + /** + * data for uniforms or custom webgl state + * @member {object} + */ + this.data = null; } -}; + return BatchDrawCall; +}()); /** - * Activates adding an offset to depth values of polygon's fragments + * Used by the batcher to build texture batches. + * Holds list of textures and their respective locations. * - * @member {boolean} - * @default false + * @class + * @memberof PIXI */ -prototypeAccessors$3.offsets.get = function () -{ - return !!(this.data & (1 << OFFSET)); -}; - -prototypeAccessors$3.offsets.set = function (value) // eslint-disable-line require-jsdoc -{ - if (!!(this.data & (1 << OFFSET)) !== value) - { - this.data ^= (1 << OFFSET); +var BatchTextureArray = /** @class */ (function () { + function BatchTextureArray() { + /** + * inside textures array + * @member {PIXI.BaseTexture[]} + */ + this.elements = []; + /** + * Respective locations for textures + * @member {number[]} + */ + this.ids = []; + /** + * number of filled elements + * @member {number} + */ + this.count = 0; } -}; + BatchTextureArray.prototype.clear = function () { + for (var i = 0; i < this.count; i++) { + this.elements[i] = null; + } + this.count = 0; + }; + return BatchTextureArray; +}()); /** - * Activates culling of polygons. + * Flexible wrapper around `ArrayBuffer` that also provides + * typed array views on demand. * - * @member {boolean} - * @default false + * @class + * @memberof PIXI */ -prototypeAccessors$3.culling.get = function () -{ - return !!(this.data & (1 << CULLING)); -}; - -prototypeAccessors$3.culling.set = function (value) // eslint-disable-line require-jsdoc -{ - if (!!(this.data & (1 << CULLING)) !== value) - { - this.data ^= (1 << CULLING); +var ViewableBuffer = /** @class */ (function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function ViewableBuffer(size) { + /** + * Underlying `ArrayBuffer` that holds all the data + * and is of capacity `size`. + * + * @member {ArrayBuffer} + */ + this.rawBinaryData = new ArrayBuffer(size); + /** + * View on the raw binary data as a `Uint32Array`. + * + * @member {Uint32Array} + */ + this.uint32View = new Uint32Array(this.rawBinaryData); + /** + * View on the raw binary data as a `Float32Array`. + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.rawBinaryData); } -}; + Object.defineProperty(ViewableBuffer.prototype, "int8View", { + /** + * View on the raw binary data as a `Int8Array`. + * + * @member {Int8Array} + */ + get: function () { + if (!this._int8View) { + this._int8View = new Int8Array(this.rawBinaryData); + } + return this._int8View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "uint8View", { + /** + * View on the raw binary data as a `Uint8Array`. + * + * @member {Uint8Array} + */ + get: function () { + if (!this._uint8View) { + this._uint8View = new Uint8Array(this.rawBinaryData); + } + return this._uint8View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "int16View", { + /** + * View on the raw binary data as a `Int16Array`. + * + * @member {Int16Array} + */ + get: function () { + if (!this._int16View) { + this._int16View = new Int16Array(this.rawBinaryData); + } + return this._int16View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "uint16View", { + /** + * View on the raw binary data as a `Uint16Array`. + * + * @member {Uint16Array} + */ + get: function () { + if (!this._uint16View) { + this._uint16View = new Uint16Array(this.rawBinaryData); + } + return this._uint16View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "int32View", { + /** + * View on the raw binary data as a `Int32Array`. + * + * @member {Int32Array} + */ + get: function () { + if (!this._int32View) { + this._int32View = new Int32Array(this.rawBinaryData); + } + return this._int32View; + }, + enumerable: false, + configurable: true + }); + /** + * Returns the view of the given type. + * + * @param {string} type - One of `int8`, `uint8`, `int16`, + * `uint16`, `int32`, `uint32`, and `float32`. + * @return {object} typed array of given type + */ + ViewableBuffer.prototype.view = function (type) { + return this[type + "View"]; + }; + /** + * Destroys all buffer references. Do not use after calling + * this. + */ + ViewableBuffer.prototype.destroy = function () { + this.rawBinaryData = null; + this._int8View = null; + this._uint8View = null; + this._int16View = null; + this._uint16View = null; + this._int32View = null; + this.uint32View = null; + this.float32View = null; + }; + ViewableBuffer.sizeOf = function (type) { + switch (type) { + case 'int8': + case 'uint8': + return 1; + case 'int16': + case 'uint16': + return 2; + case 'int32': + case 'uint32': + case 'float32': + return 4; + default: + throw new Error(type + " isn't a valid view type"); + } + }; + return ViewableBuffer; +}()); /** - * Activates depth comparisons and updates to the depth buffer. + * Renderer dedicated to drawing and batching sprites. * - * @member {boolean} - * @default false - */ -prototypeAccessors$3.depthTest.get = function () -{ - return !!(this.data & (1 << DEPTH_TEST)); -}; - -prototypeAccessors$3.depthTest.set = function (value) // eslint-disable-line require-jsdoc -{ - if (!!(this.data & (1 << DEPTH_TEST)) !== value) - { - this.data ^= (1 << DEPTH_TEST); - } -}; - -/** - * Specifies whether or not front or back-facing polygons can be culled. - * @member {boolean} - * @default false - */ -prototypeAccessors$3.clockwiseFrontFace.get = function () -{ - return !!(this.data & (1 << WINDING)); -}; - -prototypeAccessors$3.clockwiseFrontFace.set = function (value) // eslint-disable-line require-jsdoc -{ - if (!!(this.data & (1 << WINDING)) !== value) - { - this.data ^= (1 << WINDING); - } -}; - -/** - * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * Setting this mode to anything other than NO_BLEND will automatically switch blending on. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - * @see PIXI.BLEND_MODES - */ -prototypeAccessors$3.blendMode.get = function () -{ - return this._blendMode; -}; - -prototypeAccessors$3.blendMode.set = function (value) // eslint-disable-line require-jsdoc -{ - this.blend = (value !== constants.BLEND_MODES.NONE); - this._blendMode = value; -}; - -/** - * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill. - * - * @member {number} - * @default 0 - */ -prototypeAccessors$3.polygonOffset.get = function () -{ - return this._polygonOffset; -}; - -prototypeAccessors$3.polygonOffset.set = function (value) // eslint-disable-line require-jsdoc -{ - this.offsets = !!value; - this._polygonOffset = value; -}; - -State.for2d = function for2d () -{ - var state = new State(); - - state.depthTest = false; - state.blend = true; - - return state; -}; - -Object.defineProperties( State.prototype, prototypeAccessors$3 ); - -var defaultVertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; - -var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"; - -/** - * Filter is a special type of WebGL shader that is applied to the screen. - * - * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the - * {@link PIXI.filters.BlurFilter BlurFilter}. - * - * ### Usage - * Filters can be applied to any DisplayObject or Container. - * PixiJS' `FilterSystem` renders the container into temporary Framebuffer, - * then filter renders it to the screen. - * Multiple filters can be added to the `filters` array property and stacked on each other. - * - * ``` - * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 }); - * const container = new PIXI.Container(); - * container.filters = [filter]; - * ``` - * - * ### Previous Version Differences - * - * In PixiJS **v3**, a filter was always applied to _whole screen_. - * - * In PixiJS **v4**, a filter can be applied _only part of the screen_. - * Developers had to create a set of uniforms to deal with coordinates. - * - * In PixiJS **v5** combines _both approaches_. - * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers, - * bringing those extra uniforms into account. - * - * Also be aware that we have changed default vertex shader, please consult - * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. - * - * ### Built-in Uniforms - * - * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`, - * and `projectionMatrix` uniform maps it to the gl viewport. - * - * **uSampler** - * - * The most important uniform is the input texture that container was rendered into. - * _Important note: as with all Framebuffers in PixiJS, both input and output are - * premultiplied by alpha._ - * - * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`. - * Use it to sample the input. - * - * ``` - * const fragment = ` - * varying vec2 vTextureCoord; - * uniform sampler2D uSampler; - * void main(void) - * { - * gl_FragColor = texture2D(uSampler, vTextureCoord); - * } - * `; - * - * const myFilter = new PIXI.Filter(null, fragment); - * ``` - * - * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}. - * - * **outputFrame** - * - * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates. - * It's the same as `renderer.screen` for a fullscreen filter. - * Only a part of `outputFrame.zw` size of temporary Framebuffer is used, - * `(0, 0, outputFrame.width, outputFrame.height)`, - * - * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute. - * To calculate vertex position in screen space using normalized (0-1) space: - * - * ``` - * vec4 filterVertexPosition( void ) - * { - * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy; - * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); - * } - * ``` - * - * **inputSize** - * - * Temporary framebuffer is different, it can be either the size of screen, either power-of-two. - * The `inputSize.xy` are size of temporary framebuffer that holds input. - * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader. - * - * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter. - * - * To calculate input normalized coordinate, you have to map it to filter normalized space. - * Multiply by `outputFrame.zw` to get input coordinate. - * Divide by `inputSize.xy` to get input normalized coordinate. - * - * ``` - * vec2 filterTextureCoord( void ) - * { - * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy - * } - * ``` - * **resolution** - * - * The `resolution` is the ratio of screen (CSS) pixels to real pixels. - * - * **inputPixel** - * - * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution` - * `inputPixel.zw` is inverted `inputPixel.xy`. - * - * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}. - * - * **inputClamp** - * - * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour. - * For displacements, coordinates has to be clamped. - * - * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer - * `inputClamp.zw` is bottom-right pixel center. - * - * ``` - * vec4 color = texture2D(uSampler, clamp(modifigedTextureCoord, inputClamp.xy, inputClamp.zw)) - * ``` - * OR - * ``` - * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw)) - * ``` - * - * ### Additional Information - * - * Complete documentation on Filter usage is located in the - * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. - * - * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded - * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository. + * This is the default batch renderer. It buffers objects + * with texture-based geometries and renders them in + * batches. It uploads multiple textures to the GPU to + * reduce to the number of draw calls. * * @class + * @protected * @memberof PIXI - * @extends PIXI.Shader + * @extends PIXI.ObjectRenderer */ -var Filter = /*@__PURE__*/(function (Shader) { - function Filter(vertexSrc, fragmentSrc, uniforms) - { - var program = Program.from(vertexSrc || Filter.defaultVertexSrc, - fragmentSrc || Filter.defaultFragmentSrc); - - Shader.call(this, program, uniforms); - +var AbstractBatchRenderer = /** @class */ (function (_super) { + __extends(AbstractBatchRenderer, _super); + /** + * This will hook onto the renderer's `contextChange` + * and `prerender` signals. + * + * @param {PIXI.Renderer} renderer - The renderer this works for. + */ + function AbstractBatchRenderer(renderer) { + var _this = _super.call(this, renderer) || this; /** - * The padding of the filter. Some filters require extra space to breath such as a blur. - * Increasing this will add extra width and height to the bounds of the object that the - * filter is applied to. + * This is used to generate a shader that can + * color each vertex based on a `aTextureId` + * attribute that points to an texture in `uSampler`. + * + * This enables the objects with different textures + * to be drawn in the same draw call. + * + * You can customize your shader by creating your + * custom shader generator. + * + * @member {PIXI.BatchShaderGenerator} + * @protected + */ + _this.shaderGenerator = null; + /** + * The class that represents the geometry of objects + * that are going to be batched with this. + * + * @member {object} + * @default PIXI.BatchGeometry + * @protected + */ + _this.geometryClass = null; + /** + * Size of data being buffered per vertex in the + * attribute buffers (in floats). By default, the + * batch-renderer plugin uses 6: + * + * | aVertexPosition | 2 | + * |-----------------|---| + * | aTextureCoords | 2 | + * | aColor | 1 | + * | aTextureId | 1 | * * @member {number} + * @readonly */ - this.padding = 0; - + _this.vertexSize = null; /** - * The resolution of the filter. Setting this to be lower will lower the quality but - * increase the performance of the filter. + * The WebGL state in which this renderer will work. + * + * @member {PIXI.State} + * @readonly + */ + _this.state = State.for2d(); + /** + * The number of bufferable objects before a flush + * occurs automatically. * * @member {number} + * @default settings.SPRITE_BATCH_SIZE * 4 */ - this.resolution = settings.settings.FILTER_RESOLUTION; - + _this.size = settings.settings.SPRITE_BATCH_SIZE * 4; /** - * If enabled is true the filter is applied, if false it will not. + * Total count of all vertices used by the currently + * buffered objects. * - * @member {boolean} + * @member {number} + * @private */ - this.enabled = true; - + _this._vertexCount = 0; /** - * If enabled, PixiJS will fit the filter area into boundaries for better performance. - * Switch it off if it does not work for specific shader. + * Total count of all indices used by the currently + * buffered objects. * - * @member {boolean} + * @member {number} + * @private */ - this.autoFit = true; - + _this._indexCount = 0; /** - * Legacy filters use position and uvs from attributes - * @member {boolean} - * @readonly + * Buffer of objects that are yet to be rendered. + * + * @member {PIXI.DisplayObject[]} + * @private */ - this.legacy = !!this.program.attributeData.aTextureCoord; - + _this._bufferedElements = []; /** - * The WebGL state the filter requires to render - * @member {PIXI.State} + * Data for texture batch builder, helps to save a bit of CPU on a pass. + * @type {PIXI.BaseTexture[]} + * @private + */ + _this._bufferedTextures = []; + /** + * Number of elements that are buffered and are + * waiting to be flushed. + * + * @member {number} + * @private + */ + _this._bufferSize = 0; + /** + * This shader is generated by `this.shaderGenerator`. + * + * It is generated specifically to handle the required + * number of textures being batched together. + * + * @member {PIXI.Shader} + * @protected + */ + _this._shader = null; + /** + * Pool of `this.geometryClass` geometry objects + * that store buffers. They are used to pass data + * to the shader on each draw call. + * + * These are never re-allocated again, unless a + * context change occurs; however, the pool may + * be expanded if required. + * + * @member {PIXI.Geometry[]} + * @private + * @see PIXI.AbstractBatchRenderer.contextChange + */ + _this._packedGeometries = []; + /** + * Size of `this._packedGeometries`. It can be expanded + * if more than `this._packedGeometryPoolSize` flushes + * occur in a single frame. + * + * @member {number} + * @private + */ + _this._packedGeometryPoolSize = 2; + /** + * A flush may occur multiple times in a single + * frame. On iOS devices or when + * `settings.CAN_UPLOAD_SAME_BUFFER` is false, the + * batch renderer does not upload data to the same + * `WebGLBuffer` for performance reasons. + * + * This is the index into `packedGeometries` that points to + * geometry holding the most recent buffers. + * + * @member {number} + * @private + */ + _this._flushId = 0; + /** + * Pool of `ViewableBuffer` objects that are sorted in + * order of increasing size. The flush method uses + * the buffer with the least size above the amount + * it requires. These are used for passing attributes. + * + * The first buffer has a size of 8; each subsequent + * buffer has double capacity of its previous. + * + * @member {PIXI.ViewableBuffer[]} + * @private + * @see PIXI.AbstractBatchRenderer#getAttributeBuffer + */ + _this._aBuffers = {}; + /** + * Pool of `Uint16Array` objects that are sorted in + * order of increasing size. The flush method uses + * the buffer with the least size above the amount + * it requires. These are used for passing indices. + * + * The first buffer has a size of 12; each subsequent + * buffer has double capacity of its previous. + * + * @member {Uint16Array[]} + * @private + * @see PIXI.AbstractBatchRenderer#getIndexBuffer + */ + _this._iBuffers = {}; + /** + * Maximum number of textures that can be uploaded to + * the GPU under the current context. It is initialized + * properly in `this.contextChange`. + * + * @member {number} + * @see PIXI.AbstractBatchRenderer#contextChange + * @readonly */ - this.state = new State(); + _this.MAX_TEXTURES = 1; + _this.renderer.on('prerender', _this.onPrerender, _this); + renderer.runners.contextChange.add(_this); + _this._dcIndex = 0; + _this._aIndex = 0; + _this._iIndex = 0; + _this._attributeBuffer = null; + _this._indexBuffer = null; + _this._tempBoundTextures = []; + return _this; } - - if ( Shader ) Filter.__proto__ = Shader; - Filter.prototype = Object.create( Shader && Shader.prototype ); - Filter.prototype.constructor = Filter; - - var prototypeAccessors = { blendMode: { configurable: true } }; - var staticAccessors = { defaultVertexSrc: { configurable: true },defaultFragmentSrc: { configurable: true } }; - /** - * Applies the filter + * Handles the `contextChange` signal. * - * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from - * @param {PIXI.RenderTexture} input - The input render target. - * @param {PIXI.RenderTexture} output - The target to output to. - * @param {boolean} clear - Should the output be cleared before rendering to it - * @param {object} [currentState] - It's current state of filter. - * There are some useful properties in the currentState : - * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + * It calculates `this.MAX_TEXTURES` and allocating the + * packed-geometry object pool. */ - Filter.prototype.apply = function apply (filterManager, input, output, clear, currentState) - { - // do as you please! - - filterManager.applyFilter(this, input, output, clear, currentState); - - // or just do a regular render.. + AbstractBatchRenderer.prototype.contextChange = function () { + var gl = this.renderer.gl; + if (settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY) { + this.MAX_TEXTURES = 1; + } + else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings.settings.SPRITE_MAX_TEXTURES); + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl); + } + this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES); + // we use the second shader as the first one depending on your browser + // may omit aTextureId as it is not used by the shader so is optimized out. + for (var i = 0; i < this._packedGeometryPoolSize; i++) { + /* eslint-disable max-len */ + this._packedGeometries[i] = new (this.geometryClass)(); + } + this.initFlushBuffers(); }; - /** - * Sets the blendmode of the filter - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL + * Makes sure that static and dynamic flush pooled objects have correct dimensions */ - prototypeAccessors.blendMode.get = function () - { - return this.state.blendMode; - }; - - prototypeAccessors.blendMode.set = function (value) // eslint-disable-line require-jsdoc - { - this.state.blendMode = value; + AbstractBatchRenderer.prototype.initFlushBuffers = function () { + var _drawCallPool = AbstractBatchRenderer._drawCallPool, _textureArrayPool = AbstractBatchRenderer._textureArrayPool; + // max draw calls + var MAX_SPRITES = this.size / 4; + // max texture arrays + var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1; + while (_drawCallPool.length < MAX_SPRITES) { + _drawCallPool.push(new BatchDrawCall()); + } + while (_textureArrayPool.length < MAX_TA) { + _textureArrayPool.push(new BatchTextureArray()); + } + for (var i = 0; i < this.MAX_TEXTURES; i++) { + this._tempBoundTextures[i] = null; + } }; - /** - * The default vertex shader source + * Handles the `prerender` signal. * - * @static - * @type {string} - * @constant + * It ensures that flushes start from the first geometry + * object again. */ - staticAccessors.defaultVertexSrc.get = function () - { - return defaultVertex$1; + AbstractBatchRenderer.prototype.onPrerender = function () { + this._flushId = 0; }; - /** - * The default fragment shader source + * Buffers the "batchable" object. It need not be rendered + * immediately. * - * @static - * @type {string} - * @constant + * @param {PIXI.DisplayObject} element - the element to render when + * using this renderer */ - staticAccessors.defaultFragmentSrc.get = function () - { - return defaultFragment$1; + AbstractBatchRenderer.prototype.render = function (element) { + if (!element._texture.valid) { + return; + } + if (this._vertexCount + (element.vertexData.length / 2) > this.size) { + this.flush(); + } + this._vertexCount += element.vertexData.length / 2; + this._indexCount += element.indices.length; + this._bufferedTextures[this._bufferSize] = element._texture.baseTexture; + this._bufferedElements[this._bufferSize++] = element; + }; + AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function () { + var _a = this, textures = _a._bufferedTextures, MAX_TEXTURES = _a.MAX_TEXTURES; + var textureArrays = AbstractBatchRenderer._textureArrayPool; + var batch = this.renderer.batch; + var boundTextures = this._tempBoundTextures; + var touch = this.renderer.textureGC.count; + var TICK = ++BaseTexture._globalBatch; + var countTexArrays = 0; + var texArray = textureArrays[0]; + var start = 0; + batch.copyBoundTextures(boundTextures, MAX_TEXTURES); + for (var i = 0; i < this._bufferSize; ++i) { + var tex = textures[i]; + textures[i] = null; + if (tex._batchEnabled === TICK) { + continue; + } + if (texArray.count >= MAX_TEXTURES) { + batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); + this.buildDrawCalls(texArray, start, i); + start = i; + texArray = textureArrays[++countTexArrays]; + ++TICK; + } + tex._batchEnabled = TICK; + tex.touched = touch; + texArray.elements[texArray.count++] = tex; + } + if (texArray.count > 0) { + batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); + this.buildDrawCalls(texArray, start, this._bufferSize); + ++countTexArrays; + ++TICK; + } + // Clean-up + for (var i = 0; i < boundTextures.length; i++) { + boundTextures[i] = null; + } + BaseTexture._globalBatch = TICK; }; - - Object.defineProperties( Filter.prototype, prototypeAccessors ); - Object.defineProperties( Filter, staticAccessors ); - - return Filter; -}(Shader)); - -/** - * Used for caching shader IDs - * - * @static - * @type {object} - * @protected - */ -Filter.SOURCE_KEY_MAP = {}; - -var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n"; - -var fragment = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n"; - -var tempMat = new math.Matrix(); - -/** - * Class controls uv mapping from Texture normal space to BaseTexture normal space. - * - * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite. - * - * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture. - * If you want to add support for texture region of certain feature or filter, that's what you're looking for. - * - * Takes track of Texture changes through `_lastTextureID` private field. - * Use `update()` method call to track it from outside. - * - * @see PIXI.Texture - * @see PIXI.Mesh - * @see PIXI.TilingSprite - * @class - * @memberof PIXI - */ -var TextureMatrix = function TextureMatrix(texture, clampMargin) -{ - this._texture = texture; - - /** - * Matrix operation that converts texture region coords to texture coords - * @member {PIXI.Matrix} - * @readonly - */ - this.mapCoord = new math.Matrix(); - - /** - * Clamp region for normalized coords, left-top pixel center in xy , bottom-right in zw. - * Calculated based on clampOffset. - * @member {Float32Array} - * @readonly - */ - this.uClampFrame = new Float32Array(4); - /** - * Normalized clamp offset. - * Calculated based on clampOffset. - * @member {Float32Array} - * @readonly + * Populating drawcalls for rendering + * + * @param {PIXI.BatchTextureArray} texArray + * @param {number} start + * @param {number} finish */ - this.uClampOffset = new Float32Array(2); - - /** - * Tracks Texture frame changes - * @member {number} - * @protected + AbstractBatchRenderer.prototype.buildDrawCalls = function (texArray, start, finish) { + var _a = this, elements = _a._bufferedElements, _attributeBuffer = _a._attributeBuffer, _indexBuffer = _a._indexBuffer, vertexSize = _a.vertexSize; + var drawCalls = AbstractBatchRenderer._drawCallPool; + var dcIndex = this._dcIndex; + var aIndex = this._aIndex; + var iIndex = this._iIndex; + var drawCall = drawCalls[dcIndex]; + drawCall.start = this._iIndex; + drawCall.texArray = texArray; + for (var i = start; i < finish; ++i) { + var sprite = elements[i]; + var tex = sprite._texture.baseTexture; + var spriteBlendMode = utils.premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode]; + elements[i] = null; + if (start < i && drawCall.blend !== spriteBlendMode) { + drawCall.size = iIndex - drawCall.start; + start = i; + drawCall = drawCalls[++dcIndex]; + drawCall.texArray = texArray; + drawCall.start = iIndex; + } + this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); + aIndex += sprite.vertexData.length / 2 * vertexSize; + iIndex += sprite.indices.length; + drawCall.blend = spriteBlendMode; + } + if (start < finish) { + drawCall.size = iIndex - drawCall.start; + ++dcIndex; + } + this._dcIndex = dcIndex; + this._aIndex = aIndex; + this._iIndex = iIndex; + }; + /** + * Bind textures for current rendering + * + * @param {PIXI.BatchTextureArray} texArray */ - this._updateID = -1; - + AbstractBatchRenderer.prototype.bindAndClearTexArray = function (texArray) { + var textureSystem = this.renderer.texture; + for (var j = 0; j < texArray.count; j++) { + textureSystem.bind(texArray.elements[j], texArray.ids[j]); + texArray.elements[j] = null; + } + texArray.count = 0; + }; + AbstractBatchRenderer.prototype.updateGeometry = function () { + var _a = this, packedGeometries = _a._packedGeometries, attributeBuffer = _a._attributeBuffer, indexBuffer = _a._indexBuffer; + if (!settings.settings.CAN_UPLOAD_SAME_BUFFER) { /* Usually on iOS devices, where the browser doesn't + like uploads to the same buffer in a single frame. */ + if (this._packedGeometryPoolSize <= this._flushId) { + this._packedGeometryPoolSize++; + packedGeometries[this._flushId] = new (this.geometryClass)(); + } + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.bind(packedGeometries[this._flushId]); + this.renderer.geometry.updateBuffers(); + this._flushId++; + } + else { + // lets use the faster option, always use buffer number 0 + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.updateBuffers(); + } + }; + AbstractBatchRenderer.prototype.drawBatches = function () { + var dcCount = this._dcIndex; + var _a = this.renderer, gl = _a.gl, stateSystem = _a.state; + var drawCalls = AbstractBatchRenderer._drawCallPool; + var curTexArray = null; + // Upload textures and do the draw calls + for (var i = 0; i < dcCount; i++) { + var _b = drawCalls[i], texArray = _b.texArray, type = _b.type, size = _b.size, start = _b.start, blend = _b.blend; + if (curTexArray !== texArray) { + curTexArray = texArray; + this.bindAndClearTexArray(texArray); + } + this.state.blendMode = blend; + stateSystem.set(this.state); + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); + } + }; + /** + * Renders the content _now_ and empties the current batch. + */ + AbstractBatchRenderer.prototype.flush = function () { + if (this._vertexCount === 0) { + return; + } + this._attributeBuffer = this.getAttributeBuffer(this._vertexCount); + this._indexBuffer = this.getIndexBuffer(this._indexCount); + this._aIndex = 0; + this._iIndex = 0; + this._dcIndex = 0; + this.buildTexturesAndDrawCalls(); + this.updateGeometry(); + this.drawBatches(); + // reset elements buffer for the next flush + this._bufferSize = 0; + this._vertexCount = 0; + this._indexCount = 0; + }; + /** + * Starts a new sprite batch. + */ + AbstractBatchRenderer.prototype.start = function () { + this.renderer.state.set(this.state); + this.renderer.shader.bind(this._shader); + if (settings.settings.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.geometry.bind(this._packedGeometries[this._flushId]); + } + }; + /** + * Stops and flushes the current batch. + */ + AbstractBatchRenderer.prototype.stop = function () { + this.flush(); + }; + /** + * Destroys this `AbstractBatchRenderer`. It cannot be used again. + */ + AbstractBatchRenderer.prototype.destroy = function () { + for (var i = 0; i < this._packedGeometryPoolSize; i++) { + if (this._packedGeometries[i]) { + this._packedGeometries[i].destroy(); + } + } + this.renderer.off('prerender', this.onPrerender, this); + this._aBuffers = null; + this._iBuffers = null; + this._packedGeometries = null; + this._attributeBuffer = null; + this._indexBuffer = null; + if (this._shader) { + this._shader.destroy(); + this._shader = null; + } + _super.prototype.destroy.call(this); + }; /** - * Changes frame clamping - * Works with TilingSprite and Mesh - * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * Fetches an attribute buffer from `this._aBuffers` that + * can hold atleast `size` floats. * - * @default 0 - * @member {number} + * @param {number} size - minimum capacity required + * @return {ViewableBuffer} - buffer than can hold atleast `size` floats + * @private */ - this.clampOffset = 0; - + AbstractBatchRenderer.prototype.getAttributeBuffer = function (size) { + // 8 vertices is enough for 2 quads + var roundedP2 = utils.nextPow2(Math.ceil(size / 8)); + var roundedSizeIndex = utils.log2(roundedP2); + var roundedSize = roundedP2 * 8; + if (this._aBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + var buffer = this._aBuffers[roundedSize]; + if (!buffer) { + this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4); + } + return buffer; + }; /** - * Changes frame clamping - * Works with TilingSprite and Mesh - * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * Fetches an index buffer from `this._iBuffers` that can + * have at least `size` capacity. * - * @default 0.5 - * @member {number} + * @param {number} size - minimum required capacity + * @return {Uint16Array} - buffer that can fit `size` + * indices. + * @private */ - this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin; - + AbstractBatchRenderer.prototype.getIndexBuffer = function (size) { + // 12 indices is enough for 2 quads + var roundedP2 = utils.nextPow2(Math.ceil(size / 12)); + var roundedSizeIndex = utils.log2(roundedP2); + var roundedSize = roundedP2 * 12; + if (this._iBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + var buffer = this._iBuffers[roundedSizeIndex]; + if (!buffer) { + this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize); + } + return buffer; + }; /** - * If texture size is the same as baseTexture - * @member {boolean} - * @default false - * @readonly + * Takes the four batching parameters of `element`, interleaves + * and pushes them into the batching attribute/index buffers given. + * + * It uses these properties: `vertexData` `uvs`, `textureId` and + * `indicies`. It also uses the "tint" of the base-texture, if + * present. + * + * @param {PIXI.Sprite} element - element being rendered + * @param {PIXI.ViewableBuffer} attributeBuffer - attribute buffer. + * @param {Uint16Array} indexBuffer - index buffer + * @param {number} aIndex - number of floats already in the attribute buffer + * @param {number} iIndex - number of indices already in `indexBuffer` */ - this.isSimple = false; -}; - -var prototypeAccessors$4 = { texture: { configurable: true } }; - -/** - * texture property - * @member {PIXI.Texture} - */ -prototypeAccessors$4.texture.get = function () -{ - return this._texture; -}; - -prototypeAccessors$4.texture.set = function (value) // eslint-disable-line require-jsdoc -{ - this._texture = value; - this._updateID = -1; -}; + AbstractBatchRenderer.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) { + var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View; + var packedVertices = aIndex / this.vertexSize; + var uvs = element.uvs; + var indicies = element.indices; + var vertexData = element.vertexData; + var textureId = element._texture.baseTexture._batchLocation; + var alpha = Math.min(element.worldAlpha, 1.0); + var argb = (alpha < 1.0 + && element._texture.baseTexture.alphaMode) + ? utils.premultiplyTint(element._tintRGB, alpha) + : element._tintRGB + (alpha * 255 << 24); + // lets not worry about tint! for now.. + for (var i = 0; i < vertexData.length; i += 2) { + float32View[aIndex++] = vertexData[i]; + float32View[aIndex++] = vertexData[i + 1]; + float32View[aIndex++] = uvs[i]; + float32View[aIndex++] = uvs[i + 1]; + uint32View[aIndex++] = argb; + float32View[aIndex++] = textureId; + } + for (var i = 0; i < indicies.length; i++) { + indexBuffer[iIndex++] = packedVertices + indicies[i]; + } + }; + /** + * Pool of `BatchDrawCall` objects that `flush` used + * to create "batches" of the objects being rendered. + * + * These are never re-allocated again. + * Shared between all batch renderers because it can be only one "flush" working at the moment. + * + * @static + * @member {PIXI.BatchDrawCall[]} + */ + AbstractBatchRenderer._drawCallPool = []; + /** + * Pool of `BatchDrawCall` objects that `flush` used + * to create "batches" of the objects being rendered. + * + * These are never re-allocated again. + * Shared between all batch renderers because it can be only one "flush" working at the moment. + * + * @static + * @member {PIXI.BatchTextureArray[]} + */ + AbstractBatchRenderer._textureArrayPool = []; + return AbstractBatchRenderer; +}(ObjectRenderer)); /** - * Multiplies uvs array to transform - * @param {Float32Array} uvs mesh uvs - * @param {Float32Array} [out=uvs] output - * @returns {Float32Array} output + * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer + * + * @class + * @memberof PIXI */ -TextureMatrix.prototype.multiplyUvs = function multiplyUvs (uvs, out) -{ - if (out === undefined) - { - out = uvs; - } - - var mat = this.mapCoord; - - for (var i = 0; i < uvs.length; i += 2) - { - var x = uvs[i]; - var y = uvs[i + 1]; - - out[i] = (x * mat.a) + (y * mat.c) + mat.tx; - out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty; +var BatchShaderGenerator = /** @class */ (function () { + /** + * @param {string} vertexSrc - Vertex shader + * @param {string} fragTemplate - Fragment shader template + */ + function BatchShaderGenerator(vertexSrc, fragTemplate) { + /** + * Reference to the vertex shader source. + * + * @member {string} + */ + this.vertexSrc = vertexSrc; + /** + * Reference to the fragement shader template. Must contain "%count%" and "%forloop%". + * + * @member {string} + */ + this.fragTemplate = fragTemplate; + this.programCache = {}; + this.defaultGroupCache = {}; + if (fragTemplate.indexOf('%count%') < 0) { + throw new Error('Fragment template must contain "%count%".'); + } + if (fragTemplate.indexOf('%forloop%') < 0) { + throw new Error('Fragment template must contain "%forloop%".'); + } } - - return out; -}; + BatchShaderGenerator.prototype.generateShader = function (maxTextures) { + if (!this.programCache[maxTextures]) { + var sampleValues = new Int32Array(maxTextures); + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true); + var fragmentSrc = this.fragTemplate; + fragmentSrc = fragmentSrc.replace(/%count%/gi, "" + maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); + this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc); + } + var uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new math.Matrix(), + default: this.defaultGroupCache[maxTextures], + }; + return new Shader(this.programCache[maxTextures], uniforms); + }; + BatchShaderGenerator.prototype.generateSampleSrc = function (maxTextures) { + var src = ''; + src += '\n'; + src += '\n'; + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + if (i < maxTextures - 1) { + src += "if(vTextureId < " + i + ".5)"; + } + src += '\n{'; + src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);"; + src += '\n}'; + } + src += '\n'; + src += '\n'; + return src; + }; + return BatchShaderGenerator; +}()); /** - * updates matrices if texture was changed - * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case - * @returns {boolean} whether or not it was updated + * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects). + * + * @class + * @memberof PIXI */ -TextureMatrix.prototype.update = function update (forceUpdate) -{ - var tex = this._texture; - - if (!tex || !tex.valid) - { - return false; - } - - if (!forceUpdate - && this._updateID === tex._updateID) - { - return false; - } - - this._updateID = tex._updateID; - - var uvs = tex._uvs; - - this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); - - var orig = tex.orig; - var trim = tex.trim; - - if (trim) - { - tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, - -trim.x / trim.width, -trim.y / trim.height); - this.mapCoord.append(tempMat); +var BatchGeometry = /** @class */ (function (_super) { + __extends(BatchGeometry, _super); + /** + * @param {boolean} [_static=false] - Optimization flag, where `false` + * is updated every frame, `true` doesn't change frame-to-frame. + */ + function BatchGeometry(_static) { + if (_static === void 0) { _static = false; } + var _this = _super.call(this) || this; + /** + * Buffer used for position, color, texture IDs + * + * @member {PIXI.Buffer} + * @protected + */ + _this._buffer = new Buffer(null, _static, false); + /** + * Index buffer data + * + * @member {PIXI.Buffer} + * @protected + */ + _this._indexBuffer = new Buffer(null, _static, true); + _this.addAttribute('aVertexPosition', _this._buffer, 2, false, constants.TYPES.FLOAT) + .addAttribute('aTextureCoord', _this._buffer, 2, false, constants.TYPES.FLOAT) + .addAttribute('aColor', _this._buffer, 4, true, constants.TYPES.UNSIGNED_BYTE) + .addAttribute('aTextureId', _this._buffer, 1, true, constants.TYPES.FLOAT) + .addIndex(_this._indexBuffer); + return _this; } + return BatchGeometry; +}(Geometry)); - var texBase = tex.baseTexture; - var frame = this.uClampFrame; - var margin = this.clampMargin / texBase.resolution; - var offset = this.clampOffset; - - frame[0] = (tex._frame.x + margin + offset) / texBase.width; - frame[1] = (tex._frame.y + margin + offset) / texBase.height; - frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; - frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; - this.uClampOffset[0] = offset / texBase.realWidth; - this.uClampOffset[1] = offset / texBase.realHeight; - - this.isSimple = tex._frame.width === texBase.width - && tex._frame.height === texBase.height - && tex.rotate === 0; - - return true; -}; +var defaultVertex$2 = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"; -Object.defineProperties( TextureMatrix.prototype, prototypeAccessors$4 ); +var defaultFragment$2 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"; /** - * This handles a Sprite acting as a mask, as opposed to a Graphic. - * - * WebGL only. - * * @class - * @extends PIXI.Filter * @memberof PIXI + * @hideconstructor */ -var SpriteMaskFilter = /*@__PURE__*/(function (Filter) { - function SpriteMaskFilter(sprite) - { - var maskMatrix = new math.Matrix(); - - Filter.call(this, vertex, fragment); - - sprite.renderable = false; - +var BatchPluginFactory = /** @class */ (function () { + function BatchPluginFactory() { + } + /** + * Create a new BatchRenderer plugin for Renderer. this convenience can provide an easy way + * to extend BatchRenderer with all the necessary pieces. + * @example + * const fragment = ` + * varying vec2 vTextureCoord; + * varying vec4 vColor; + * varying float vTextureId; + * uniform sampler2D uSamplers[%count%]; + * + * void main(void){ + * vec4 color; + * %forloop% + * gl_FragColor = vColor * vec4(color.a - color.rgb, color.a); + * } + * `; + * const InvertBatchRenderer = PIXI.BatchPluginFactory.create({ fragment }); + * PIXI.Renderer.registerPlugin('invert', InvertBatchRenderer); + * const sprite = new PIXI.Sprite(); + * sprite.pluginName = 'invert'; + * + * @static + * @param {object} [options] + * @param {string} [options.vertex=PIXI.BatchPluginFactory.defaultVertexSrc] - Vertex shader source + * @param {string} [options.fragment=PIXI.BatchPluginFactory.defaultFragmentTemplate] - Fragment shader template + * @param {number} [options.vertexSize=6] - Vertex size + * @param {object} [options.geometryClass=PIXI.BatchGeometry] + * @return {*} New batch renderer plugin + */ + BatchPluginFactory.create = function (options) { + var _a = Object.assign({ + vertex: defaultVertex$2, + fragment: defaultFragment$2, + geometryClass: BatchGeometry, + vertexSize: 6, + }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass; + return /** @class */ (function (_super) { + __extends(BatchPlugin, _super); + function BatchPlugin(renderer) { + var _this = _super.call(this, renderer) || this; + _this.shaderGenerator = new BatchShaderGenerator(vertex, fragment); + _this.geometryClass = geometryClass; + _this.vertexSize = vertexSize; + return _this; + } + return BatchPlugin; + }(AbstractBatchRenderer)); + }; + Object.defineProperty(BatchPluginFactory, "defaultVertexSrc", { /** - * Sprite mask - * @member {PIXI.Sprite} + * The default vertex shader source + * + * @static + * @type {string} + * @constant */ - this.maskSprite = sprite; - + get: function () { + return defaultVertex$2; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BatchPluginFactory, "defaultFragmentTemplate", { /** - * Mask matrix - * @member {PIXI.Matrix} + * The default fragment shader source + * + * @static + * @type {string} + * @constant */ - this.maskMatrix = maskMatrix; - } + get: function () { + return defaultFragment$2; + }, + enumerable: false, + configurable: true + }); + return BatchPluginFactory; +}()); +// Setup the default BatchRenderer plugin, this is what +// we'll actually export at the root level +var BatchRenderer = BatchPluginFactory.create(); - if ( Filter ) SpriteMaskFilter.__proto__ = Filter; - SpriteMaskFilter.prototype = Object.create( Filter && Filter.prototype ); - SpriteMaskFilter.prototype.constructor = SpriteMaskFilter; +exports.AbstractBatchRenderer = AbstractBatchRenderer; +exports.AbstractRenderer = AbstractRenderer; +exports.Attribute = Attribute; +exports.BaseRenderTexture = BaseRenderTexture; +exports.BaseTexture = BaseTexture; +exports.BatchDrawCall = BatchDrawCall; +exports.BatchGeometry = BatchGeometry; +exports.BatchPluginFactory = BatchPluginFactory; +exports.BatchRenderer = BatchRenderer; +exports.BatchShaderGenerator = BatchShaderGenerator; +exports.BatchTextureArray = BatchTextureArray; +exports.Buffer = Buffer; +exports.Filter = Filter; +exports.FilterState = FilterState; +exports.Framebuffer = Framebuffer; +exports.GLFramebuffer = GLFramebuffer; +exports.GLProgram = GLProgram; +exports.GLTexture = GLTexture; +exports.Geometry = Geometry; +exports.IGLUniformData = IGLUniformData; +exports.MaskData = MaskData; +exports.ObjectRenderer = ObjectRenderer; +exports.Program = Program; +exports.Quad = Quad; +exports.QuadUv = QuadUv; +exports.RenderTexture = RenderTexture; +exports.RenderTexturePool = RenderTexturePool; +exports.Renderer = Renderer; +exports.Shader = Shader; +exports.SpriteMaskFilter = SpriteMaskFilter; +exports.State = State; +exports.System = System; +exports.Texture = Texture; +exports.TextureMatrix = TextureMatrix; +exports.TextureUvs = TextureUvs; +exports.UniformGroup = UniformGroup; +exports.ViewableBuffer = ViewableBuffer; +exports.autoDetectRenderer = autoDetectRenderer; +exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader; +exports.defaultFilterVertex = defaultFilter; +exports.defaultVertex = _default; +exports.resources = index; +exports.systems = systems; +exports.uniformParsers = uniformParsers; - /** - * Applies the filter - * - * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from - * @param {PIXI.RenderTexture} input - The input render target. - * @param {PIXI.RenderTexture} output - The target to output to. - * @param {boolean} clear - Should the output be cleared before rendering to it. - */ - SpriteMaskFilter.prototype.apply = function apply (filterManager, input, output, clear) - { - var maskSprite = this.maskSprite; - var tex = this.maskSprite.texture; - if (!tex.valid) - { - return; - } - if (!tex.transform) - { - // margin = 0.0, let it bleed a bit, shader code becomes easier - // assuming that atlas textures were made with 1-pixel padding - tex.transform = new TextureMatrix(tex, 0.0); - } - tex.transform.update(); +},{"@pixi/constants":7,"@pixi/math":20,"@pixi/runner":29,"@pixi/settings":30,"@pixi/ticker":37,"@pixi/utils":38}],9:[function(require,module,exports){ +/*! + * @pixi/display - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/display is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0; - this.uniforms.mask = tex; - // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend` - this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite) - .prepend(tex.transform.mapCoord); - this.uniforms.alpha = maskSprite.worldAlpha; - this.uniforms.maskClamp = tex.transform.uClampFrame; +Object.defineProperty(exports, '__esModule', { value: true }); - filterManager.applyFilter(this, input, output, clear); - }; +var settings = require('@pixi/settings'); +var math = require('@pixi/math'); +var utils = require('@pixi/utils'); - return SpriteMaskFilter; -}(Filter)); +/** + * Sets the default value for the container property 'sortableChildren'. + * If set to true, the container will sort its children by zIndex value + * when updateTransform() is called, or manually if sortChildren() is called. + * + * This actually changes the order of elements in the array, so should be treated + * as a basic solution that is not performant compared to other solutions, + * such as @link https://github.com/pixijs/pixi-display + * + * Also be aware of that this may not work nicely with the addChildAt() function, + * as the zIndex sorting may cause the child to automatically sorted to another position. + * + * @static + * @constant + * @name SORTABLE_CHILDREN + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ +settings.settings.SORTABLE_CHILDREN = false; /** - * System plugin to the renderer to manage masks. + * 'Builder' pattern for bounds rectangles. + * + * This could be called an Axis-Aligned Bounding Box. + * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems. * * @class - * @extends PIXI.System - * @memberof PIXI.systems + * @memberof PIXI */ -var MaskSystem = /*@__PURE__*/(function (System) { - function MaskSystem(renderer) - { - System.call(this, renderer); - +var Bounds = /** @class */ (function () { + function Bounds() { /** - * Target to mask - * @member {PIXI.DisplayObject} - * @readonly + * @member {number} + * @default 0 */ - this.scissorRenderTarget = null; - + this.minX = Infinity; /** - * Enable scissor - * @member {boolean} - * @readonly + * @member {number} + * @default 0 */ - this.enableScissor = false; - + this.minY = Infinity; /** - * Pool of used sprite mask filters - * @member {PIXI.SpriteMaskFilter[]} - * @readonly + * @member {number} + * @default 0 */ - this.alphaMaskPool = []; - + this.maxX = -Infinity; /** - * Pool of mask data - * @member {PIXI.MaskData[]} - * @readonly + * @member {number} + * @default 0 */ - this.maskDataPool = []; - - this.maskStack = []; - + this.maxY = -Infinity; + this.rect = null; /** - * Current index of alpha mask pool + * It is updated to _boundsID of corresponding object to keep bounds in sync with content. + * Updated from outside, thus public modifier. + * * @member {number} - * @default 0 - * @readonly + * @public */ - this.alphaMaskIndex = 0; + this.updateID = -1; } - - if ( System ) MaskSystem.__proto__ = System; - MaskSystem.prototype = Object.create( System && System.prototype ); - MaskSystem.prototype.constructor = MaskSystem; - /** - * Changes the mask stack that is used by this System. + * Checks if bounds are empty. * - * @param {PIXI.MaskData[]} maskStack - The mask stack + * @return {boolean} True if empty. */ - MaskSystem.prototype.setMaskStack = function setMaskStack (maskStack) - { - this.maskStack = maskStack; - this.renderer.scissor.setMaskStack(maskStack); - this.renderer.stencil.setMaskStack(maskStack); + Bounds.prototype.isEmpty = function () { + return this.minX > this.maxX || this.minY > this.maxY; }; - /** - * Applies the Mask and adds it to the current filter stack. - * Renderer batch must be flushed beforehand. + * Clears the bounds and resets. * - * @param {PIXI.DisplayObject} target - Display Object to push the mask to - * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskData - The masking data. */ - MaskSystem.prototype.push = function push (target, maskData) - { - if (!maskData.isMaskData) - { - var d = this.maskDataPool.pop() || new MaskData(); - - d.pooled = true; - d.maskObject = maskData; - maskData = d; - } - - if (maskData.autoDetect) - { - this.detect(maskData); - } - - maskData.copyCountersOrReset(this.maskStack[this.maskStack.length - 1]); - maskData._target = target; - - switch (maskData.type) - { - case constants.MASK_TYPES.SCISSOR: - this.maskStack.push(maskData); - this.renderer.scissor.push(maskData); - break; - case constants.MASK_TYPES.STENCIL: - this.maskStack.push(maskData); - this.renderer.stencil.push(maskData); - break; - case constants.MASK_TYPES.SPRITE: - maskData.copyCountersOrReset(null); - this.pushSpriteMask(maskData); - this.maskStack.push(maskData); - break; - default: - break; + Bounds.prototype.clear = function () { + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + Bounds.prototype.getRectangle = function (rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return math.Rectangle.EMPTY; } + rect = rect || new math.Rectangle(0, 0, 1, 1); + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + return rect; }; - /** - * Removes the last mask from the mask stack and doesn't return it. - * Renderer batch must be flushed beforehand. + * This function should be inlined when its possible. * - * @param {PIXI.DisplayObject} target - Display Object to pop the mask from - */ - MaskSystem.prototype.pop = function pop (target) - { - var maskData = this.maskStack.pop(); - - if (!maskData || maskData._target !== target) - { - // TODO: add an assert when we have it - - return; - } - - switch (maskData.type) - { - case constants.MASK_TYPES.SCISSOR: - this.renderer.scissor.pop(); - break; - case constants.MASK_TYPES.STENCIL: - this.renderer.stencil.pop(maskData.maskObject); - break; - case constants.MASK_TYPES.SPRITE: - this.popSpriteMask(); - break; - default: - break; - } - - maskData.reset(); - - if (maskData.pooled) - { - this.maskDataPool.push(maskData); - } - }; - - /** - * Sets type of MaskData based on its maskObject - * @param {PIXI.MaskData} maskData + * @param {PIXI.IPointData} point - The point to add. */ - MaskSystem.prototype.detect = function detect (maskData) - { - var maskObject = maskData.maskObject; - - if (maskObject.isSprite) - { - maskData.type = constants.MASK_TYPES.SPRITE; - - return; - } - maskData.type = constants.MASK_TYPES.STENCIL; - // detect scissor in graphics - if (this.enableScissor - && maskObject.isFastRect - && maskObject.isFastRect()) - { - var matrix = maskObject.worldTransform; - - // TODO: move the check to the matrix itself - // we are checking that its orthogonal and x rotation is 0 90 180 or 270 - - var rotX = Math.atan2(matrix.b, matrix.a); - var rotXY = Math.atan2(matrix.d, matrix.c); - - // use the nearest degree to 0.01 - rotX = Math.round(rotX * (180 / Math.PI) * 100); - rotXY = Math.round(rotXY * (180 / Math.PI) * 100) - rotX; - - rotX = ((rotX % 9000) + 9000) % 9000; - rotXY = ((rotXY % 18000) + 18000) % 18000; - - if (rotX === 0 && rotXY === 9000) - { - maskData.type = constants.MASK_TYPES.SCISSOR; - } - } + Bounds.prototype.addPoint = function (point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); }; - /** - * Applies the Mask and adds it to the current filter stack. + * Adds a quad, not transformed * - * @param {PIXI.MaskData} maskData - Sprite to be used as the mask - */ - MaskSystem.prototype.pushSpriteMask = function pushSpriteMask (maskData) - { - var maskObject = maskData.maskObject; - var target = maskData._target; - var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; - - if (!alphaMaskFilter) - { - alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter(maskObject)]; - } - - alphaMaskFilter[0].resolution = this.renderer.resolution; - alphaMaskFilter[0].maskSprite = maskObject; - - var stashFilterArea = target.filterArea; - - target.filterArea = maskObject.getBounds(true); - this.renderer.filter.push(target, alphaMaskFilter); - target.filterArea = stashFilterArea; - - this.alphaMaskIndex++; - }; - - /** - * Removes the last filter from the filter stack and doesn't return it. - */ - MaskSystem.prototype.popSpriteMask = function popSpriteMask () - { - this.renderer.filter.pop(); - this.alphaMaskIndex--; - }; - - return MaskSystem; -}(System)); - -/** - * System plugin to the renderer to manage masks of certain type - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ -var AbstractMaskSystem = /*@__PURE__*/(function (System) { - function AbstractMaskSystem(renderer) - { - System.call(this, renderer); - - /** - * The mask stack - * @member {PIXI.MaskData[]} - */ - this.maskStack = []; - - /** - * Constant for gl.enable - * @member {number} - * @private - */ - this.glConst = 0; - } - - if ( System ) AbstractMaskSystem.__proto__ = System; - AbstractMaskSystem.prototype = Object.create( System && System.prototype ); - AbstractMaskSystem.prototype.constructor = AbstractMaskSystem; - - /** - * gets count of masks of certain type - * @returns {number} + * @param {Float32Array} vertices - The verts to add. */ - AbstractMaskSystem.prototype.getStackLength = function getStackLength () - { - return this.maskStack.length; + Bounds.prototype.addQuad = function (vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + var x = vertices[0]; + var y = vertices[1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; }; - /** - * Changes the mask stack that is used by this System. + * Adds sprite frame, transformed. * - * @param {PIXI.MaskData[]} maskStack - The mask stack - */ - AbstractMaskSystem.prototype.setMaskStack = function setMaskStack (maskStack) - { - var ref = this.renderer; - var gl = ref.gl; - var curStackLen = this.getStackLength(); - - this.maskStack = maskStack; - - var newStackLen = this.getStackLength(); - - if (newStackLen !== curStackLen) - { - if (newStackLen === 0) - { - gl.disable(this.glConst); - } - else - { - gl.enable(this.glConst); - this._useCurrent(); - } - } - }; - - /** - * Setup renderer to use the current mask data. - * @private + * @param {PIXI.Transform} transform - transform to apply + * @param {number} x0 - left X of frame + * @param {number} y0 - top Y of frame + * @param {number} x1 - right X of frame + * @param {number} y1 - bottom Y of frame */ - AbstractMaskSystem.prototype._useCurrent = function _useCurrent () - { - // OVERWRITE; + Bounds.prototype.addFrame = function (transform, x0, y0, x1, y1) { + this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1); }; - /** - * Destroys the mask stack. + * Adds sprite frame, multiplied by matrix * + * @param {PIXI.Matrix} matrix - matrix to apply + * @param {number} x0 - left X of frame + * @param {number} y0 - top Y of frame + * @param {number} x1 - right X of frame + * @param {number} y1 - bottom Y of frame */ - AbstractMaskSystem.prototype.destroy = function destroy () - { - System.prototype.destroy.call(this, this); - - this.maskStack = null; - }; - - return AbstractMaskSystem; -}(System)); - -/** - * System plugin to the renderer to manage scissor rects (used for masks). - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ -var ScissorSystem = /*@__PURE__*/(function (AbstractMaskSystem) { - function ScissorSystem(renderer) - { - AbstractMaskSystem.call(this, renderer); - - this.glConst = WebGLRenderingContext.SCISSOR_TEST; - } - - if ( AbstractMaskSystem ) ScissorSystem.__proto__ = AbstractMaskSystem; - ScissorSystem.prototype = Object.create( AbstractMaskSystem && AbstractMaskSystem.prototype ); - ScissorSystem.prototype.constructor = ScissorSystem; - - ScissorSystem.prototype.getStackLength = function getStackLength () - { - var maskData = this.maskStack[this.maskStack.length - 1]; - - if (maskData) - { - return maskData._scissorCounter; - } - - return 0; + Bounds.prototype.addFrameMatrix = function (matrix, x0, y0, x1, y1) { + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + var x = (a * x0) + (c * y0) + tx; + var y = (b * x0) + (d * y0) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x1) + (c * y0) + tx; + y = (b * x1) + (d * y0) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x0) + (c * y1) + tx; + y = (b * x0) + (d * y1) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x1) + (c * y1) + tx; + y = (b * x1) + (d * y1) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; }; - /** - * Applies the Mask and adds it to the current stencil stack. @alvin + * Adds screen vertices from array * - * @param {PIXI.MaskData} maskData - The mask data + * @param {Float32Array} vertexData - calculated vertices + * @param {number} beginOffset - begin offset + * @param {number} endOffset - end offset, excluded */ - ScissorSystem.prototype.push = function push (maskData) - { - var maskObject = maskData.maskObject; - - maskObject.renderable = true; - - var prevData = maskData._scissorRect; - var bounds = maskObject.getBounds(true); - var ref = this.renderer; - var gl = ref.gl; - - maskObject.renderable = false; - - if (prevData) - { - bounds.fit(prevData); - } - else - { - gl.enable(gl.SCISSOR_TEST); + Bounds.prototype.addVertexData = function (vertexData, beginOffset, endOffset) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + for (var i = beginOffset; i < endOffset; i += 2) { + var x = vertexData[i]; + var y = vertexData[i + 1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Add an array of mesh vertices + * + * @param {PIXI.Transform} transform - mesh transform + * @param {Float32Array} vertices - mesh coordinates in array + * @param {number} beginOffset - begin offset + * @param {number} endOffset - end offset, excluded + */ + Bounds.prototype.addVertices = function (transform, vertices, beginOffset, endOffset) { + this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset); + }; + /** + * Add an array of mesh vertices. + * + * @param {PIXI.Matrix} matrix - mesh matrix + * @param {Float32Array} vertices - mesh coordinates in array + * @param {number} beginOffset - begin offset + * @param {number} endOffset - end offset, excluded + * @param {number} [padX=0] - x padding + * @param {number} [padY=0] - y padding + */ + Bounds.prototype.addVerticesMatrix = function (matrix, vertices, beginOffset, endOffset, padX, padY) { + if (padX === void 0) { padX = 0; } + if (padY === void 0) { padY = padX; } + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + minX = Math.min(minX, x - padX); + maxX = Math.max(maxX, x + padX); + minY = Math.min(minY, y - padY); + maxY = Math.max(maxY, y + padY); } - - maskData._scissorCounter++; - maskData._scissorRect = bounds; - this._useCurrent(); + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; }; - /** - * Pops scissor mask. MaskData is already removed from stack + * Adds other Bounds. + * + * @param {PIXI.Bounds} bounds - The Bounds to be added */ - ScissorSystem.prototype.pop = function pop () - { - var ref = this.renderer; - var gl = ref.gl; - - if (this.getStackLength() > 0) - { - this._useCurrent(); - } - else - { - gl.disable(gl.SCISSOR_TEST); - } + Bounds.prototype.addBounds = function (bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; }; - /** - * Setup renderer to use the current scissor data. - * @private + * Adds other Bounds, masked with Bounds. + * + * @param {PIXI.Bounds} bounds - The Bounds to be added. + * @param {PIXI.Bounds} mask - TODO */ - ScissorSystem.prototype._useCurrent = function _useCurrent () - { - var rect = this.maskStack[this.maskStack.length - 1]._scissorRect; - var rt = this.renderer.renderTexture.current; - var ref = this.renderer.projection; - var transform = ref.transform; - var sourceFrame = ref.sourceFrame; - var destinationFrame = ref.destinationFrame; - var resolution = rt ? rt.resolution : this.renderer.resolution; - var x = ((rect.x - sourceFrame.x) * resolution) + destinationFrame.x; - var y = ((rect.y - sourceFrame.y) * resolution) + destinationFrame.y; - var width = rect.width * resolution; - var height = rect.height * resolution; - - if (transform) - { - x += transform.tx * resolution; - y += transform.ty * resolution; - } - if (!rt) - { - // flipY. In future we'll have it over renderTextures as an option - y = this.renderer.height - height - y; - } - - this.renderer.gl.scissor(x, y, width, height); - }; - - return ScissorSystem; -}(AbstractMaskSystem)); - -/** - * System plugin to the renderer to manage stencils (used for masks). - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ -var StencilSystem = /*@__PURE__*/(function (AbstractMaskSystem) { - function StencilSystem(renderer) - { - AbstractMaskSystem.call(this, renderer); - - this.glConst = WebGLRenderingContext.STENCIL_TEST; - } - - if ( AbstractMaskSystem ) StencilSystem.__proto__ = AbstractMaskSystem; - StencilSystem.prototype = Object.create( AbstractMaskSystem && AbstractMaskSystem.prototype ); - StencilSystem.prototype.constructor = StencilSystem; - - StencilSystem.prototype.getStackLength = function getStackLength () - { - var maskData = this.maskStack[this.maskStack.length - 1]; - - if (maskData) - { - return maskData._stencilCounter; + Bounds.prototype.addBoundsMask = function (bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; } - - return 0; }; - /** - * Applies the Mask and adds it to the current stencil stack. + * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty. * - * @param {PIXI.MaskData} maskData - The mask data + * @param {PIXI.Bounds} bounds - other bounds + * @param {PIXI.Matrix} matrix - multiplicator */ - StencilSystem.prototype.push = function push (maskData) - { - var maskObject = maskData.maskObject; - var ref = this.renderer; - var gl = ref.gl; - var prevMaskCount = maskData._stencilCounter; - - if (prevMaskCount === 0) - { - // force use stencil texture in current framebuffer - this.renderer.framebuffer.forceStencil(); - gl.enable(gl.STENCIL_TEST); - } - - maskData._stencilCounter++; - - // Increment the reference stencil value where the new mask overlaps with the old ones. - gl.colorMask(false, false, false, false); - gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); - - maskObject.renderable = true; - maskObject.render(this.renderer); - this.renderer.batch.flush(); - maskObject.renderable = false; - - this._useCurrent(); + Bounds.prototype.addBoundsMatrix = function (bounds, matrix) { + this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); }; - /** - * Pops stencil mask. MaskData is already removed from stack + * Adds other Bounds, masked with Rectangle. * - * @param {PIXI.DisplayObject} maskObject - object of popped mask data + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO */ - StencilSystem.prototype.pop = function pop (maskObject) - { - var gl = this.renderer.gl; - - if (this.getStackLength() === 0) - { - // the stack is empty! - gl.disable(gl.STENCIL_TEST); - gl.clear(gl.STENCIL_BUFFER_BIT); - gl.clearStencil(0); - } - else - { - // Decrement the reference stencil value where the popped mask overlaps with the other ones - gl.colorMask(false, false, false, false); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); - - maskObject.renderable = true; - maskObject.render(this.renderer); - this.renderer.batch.flush(); - maskObject.renderable = false; - - this._useCurrent(); + Bounds.prototype.addBoundsArea = function (bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width); + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height); + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; } }; - - /** - * Setup renderer to use the current stencil data. - * @private - */ - StencilSystem.prototype._useCurrent = function _useCurrent () - { - var gl = this.renderer.gl; - - gl.colorMask(true, true, true, true); - gl.stencilFunc(gl.EQUAL, this.getStackLength(), this._getBitwiseMask()); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - }; - /** - * Fill 1s equal to the number of acitve stencil masks. - * @private - * @return {number} The bitwise mask. + * Pads bounds object, making it grow in all directions. + * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. + * + * @param {number} [paddingX=0] - The horizontal padding amount. + * @param {number} [paddingY=0] - The vertical padding amount. */ - StencilSystem.prototype._getBitwiseMask = function _getBitwiseMask () - { - return (1 << this.getStackLength()) - 1; - }; + Bounds.prototype.pad = function (paddingX, paddingY) { + if (paddingX === void 0) { paddingX = 0; } + if (paddingY === void 0) { paddingY = paddingX; } + if (!this.isEmpty()) { + this.minX -= paddingX; + this.maxX += paddingX; + this.minY -= paddingY; + this.maxY += paddingY; + } + }; + /** + * Adds padded frame. (x0, y0) should be strictly less than (x1, y1) + * + * @param {number} x0 - left X of frame + * @param {number} y0 - top Y of frame + * @param {number} x1 - right X of frame + * @param {number} y1 - bottom Y of frame + * @param {number} padX - padding X + * @param {number} padY - padding Y + */ + Bounds.prototype.addFramePad = function (x0, y0, x1, y1, padX, padY) { + x0 -= padX; + y0 -= padY; + x1 += padX; + y1 += padY; + this.minX = this.minX < x0 ? this.minX : x0; + this.maxX = this.maxX > x1 ? this.maxX : x1; + this.minY = this.minY < y0 ? this.minY : y0; + this.maxY = this.maxY > y1 ? this.maxY : y1; + }; + return Bounds; +}()); - return StencilSystem; -}(AbstractMaskSystem)); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} /** - * System plugin to the renderer to manage the projection matrix. + * The base class for all objects that are rendered on the screen. + * + * This is an abstract class and should not be used on its own; rather it should b e extended. * * @class - * @extends PIXI.System - * @memberof PIXI.systems + * @extends PIXI.utils.EventEmitter + * @memberof PIXI */ - -var ProjectionSystem = /*@__PURE__*/(function (System) { - function ProjectionSystem(renderer) - { - System.call(this, renderer); - +var DisplayObject = /** @class */ (function (_super) { + __extends(DisplayObject, _super); + function DisplayObject() { + var _this = _super.call(this) || this; + _this.tempDisplayObjectParent = null; + // TODO: need to create Transform from factory /** - * Destination frame - * @member {PIXI.Rectangle} - * @readonly + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing. + * + * @member {PIXI.Transform} */ - this.destinationFrame = null; - + _this.transform = new math.Transform(); /** - * Source frame - * @member {PIXI.Rectangle} - * @readonly + * The opacity of the object. + * + * @member {number} */ - this.sourceFrame = null; - + _this.alpha = 1; /** - * Default destination frame - * @member {PIXI.Rectangle} - * @readonly + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually. + * + * @member {boolean} */ - this.defaultFrame = null; - + _this.visible = true; /** - * Project matrix - * @member {PIXI.Matrix} + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually. + * + * @member {boolean} + */ + _this.renderable = true; + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + */ + _this.parent = null; + /** + * The multiplied alpha of the displayObject. + * + * @member {number} * @readonly */ - this.projectionMatrix = new math.Matrix(); - + _this.worldAlpha = 1; /** - * A transform that will be appended to the projection matrix - * if null, nothing will be applied - * @member {PIXI.Matrix} + * Which index in the children array the display component was before the previous zIndex sort. + * Used by containers to help sort objects with the same zIndex, by using previous array index as the decider. + * + * @member {number} + * @protected */ - this.transform = null; - } - - if ( System ) ProjectionSystem.__proto__ = System; - ProjectionSystem.prototype = Object.create( System && System.prototype ); - ProjectionSystem.prototype.constructor = ProjectionSystem; - - /** - * Updates the projection matrix based on a projection frame (which is a rectangle) - * - * @param {PIXI.Rectangle} destinationFrame - The destination frame. - * @param {PIXI.Rectangle} sourceFrame - The source frame. - * @param {Number} resolution - Resolution - * @param {boolean} root - If is root - */ - ProjectionSystem.prototype.update = function update (destinationFrame, sourceFrame, resolution, root) - { - this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; - this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; - - this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root); - - if (this.transform) - { - this.projectionMatrix.append(this.transform); - } - - var renderer = this.renderer; - - renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix; - renderer.globalUniforms.update(); - - // this will work for now - // but would be sweet to stick and even on the global uniforms.. - if (renderer.shader.shader) - { - renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals); - } - }; - - /** - * Updates the projection matrix based on a projection frame (which is a rectangle) - * - * @param {PIXI.Rectangle} destinationFrame - The destination frame. - * @param {PIXI.Rectangle} sourceFrame - The source frame. - * @param {Number} resolution - Resolution - * @param {boolean} root - If is root - */ - ProjectionSystem.prototype.calculateProjection = function calculateProjection (destinationFrame, sourceFrame, resolution, root) - { - var pm = this.projectionMatrix; - - // I don't think we will need this line.. - // pm.identity(); - - if (!root) - { - pm.a = (1 / destinationFrame.width * 2) * resolution; - pm.d = (1 / destinationFrame.height * 2) * resolution; - - pm.tx = -1 - (sourceFrame.x * pm.a); - pm.ty = -1 - (sourceFrame.y * pm.d); - } - else - { - pm.a = (1 / destinationFrame.width * 2) * resolution; - pm.d = (-1 / destinationFrame.height * 2) * resolution; - - pm.tx = -1 - (sourceFrame.x * pm.a); - pm.ty = 1 - (sourceFrame.y * pm.d); - } - }; - - /** - * Sets the transform of the active render target to the given matrix - * - * @param {PIXI.Matrix} matrix - The transformation matrix - */ - ProjectionSystem.prototype.setTransform = function setTransform ()// matrix) - { - // this._activeRenderTarget.transform = matrix; - }; - - return ProjectionSystem; -}(System)); - -var tempRect = new math.Rectangle(); - -/** - * System plugin to the renderer to manage render textures. - * - * Should be added after FramebufferSystem - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - -var RenderTextureSystem = /*@__PURE__*/(function (System) { - function RenderTextureSystem(renderer) - { - System.call(this, renderer); - + _this._lastSortedIndex = 0; /** - * The clear background color as rgba - * @member {number[]} + * The zIndex of the displayObject. + * A higher value will mean it will be rendered on top of other displayObjects within the same container. + * + * @member {number} + * @protected */ - this.clearColor = renderer._backgroundColorRgba; - - // TODO move this property somewhere else! + _this._zIndex = 0; /** - * List of masks for the StencilSystem - * @member {PIXI.Graphics[]} - * @readonly + * The area the filter is applied to. This is used as more of an optimization + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle. + * + * Also works as an interaction mask. + * + * @member {?PIXI.Rectangle} */ - this.defaultMaskStack = []; - - // empty render texture? + _this.filterArea = null; /** - * Render texture - * @member {PIXI.RenderTexture} - * @readonly + * Sets the filters for the displayObject. + * * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to `'null'`. + * + * @member {?PIXI.Filter[]} */ - this.current = null; - + _this.filters = null; /** - * Source frame - * @member {PIXI.Rectangle} - * @readonly + * Currently enabled filters + * @member {PIXI.Filter[]} + * @protected */ - this.sourceFrame = new math.Rectangle(); - + _this._enabledFilters = null; /** - * Destination frame - * @member {PIXI.Rectangle} - * @readonly + * The bounds object, this is used to calculate and store the bounds of the displayObject. + * + * @member {PIXI.Bounds} */ - this.destinationFrame = new math.Rectangle(); + _this._bounds = new Bounds(); + /** + * Local bounds object, swapped with `_bounds` when using `getLocalBounds()`. + * + * @member {PIXI.Bounds} + */ + _this._localBounds = null; + /** + * Flags the cached bounds as dirty. + * + * @member {number} + * @protected + */ + _this._boundsID = 0; + /** + * Cache of this display-object's bounds-rectangle. + * + * @member {PIXI.Bounds} + * @protected + */ + _this._boundsRect = null; + /** + * Cache of this display-object's local-bounds rectangle. + * + * @member {PIXI.Bounds} + * @protected + */ + _this._localBoundsRect = null; + /** + * The original, cached mask of the object. + * + * @member {PIXI.Container|PIXI.MaskData|null} + * @protected + */ + _this._mask = null; + /** + * Fired when this DisplayObject is added to a Container. + * + * @event PIXI.DisplayObject#added + * @param {PIXI.Container} container - The container added to. + */ + /** + * Fired when this DisplayObject is removed from a Container. + * + * @event PIXI.DisplayObject#removed + * @param {PIXI.Container} container - The container removed from. + */ + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @protected + */ + _this._destroyed = false; + /** + * used to fast check if a sprite is.. a sprite! + * @member {boolean} + */ + _this.isSprite = false; + /** + * Does any other displayObject use this object as a mask? + * @member {boolean} + */ + _this.isMask = false; + return _this; } - - if ( System ) RenderTextureSystem.__proto__ = System; - RenderTextureSystem.prototype = Object.create( System && System.prototype ); - RenderTextureSystem.prototype.constructor = RenderTextureSystem; - /** - * Bind the current render texture - * @param {PIXI.RenderTexture} [renderTexture] - RenderTexture to bind, by default its `null`, the screen - * @param {PIXI.Rectangle} [sourceFrame] - part of screen that is mapped to the renderTexture - * @param {PIXI.Rectangle} [destinationFrame] - part of renderTexture, by default it has the same size as sourceFrame + * Mixes all enumerable properties and methods from a source object to DisplayObject. + * + * @param {object} source - The source of properties and methods to mix in. */ - RenderTextureSystem.prototype.bind = function bind (renderTexture, sourceFrame, destinationFrame) - { - if ( renderTexture === void 0 ) renderTexture = null; - - this.current = renderTexture; - - var renderer = this.renderer; - - var resolution; - - if (renderTexture) - { - var baseTexture = renderTexture.baseTexture; - - resolution = baseTexture.resolution; - - if (!destinationFrame) - { - tempRect.width = baseTexture.realWidth; - tempRect.height = baseTexture.realHeight; - - destinationFrame = tempRect; - } - - if (!sourceFrame) - { - sourceFrame = destinationFrame; - } - - this.renderer.framebuffer.bind(baseTexture.framebuffer, destinationFrame); - - this.renderer.projection.update(destinationFrame, sourceFrame, resolution, false); - this.renderer.mask.setMaskStack(baseTexture.maskStack); - } - else - { - resolution = this.renderer.resolution; - - // TODO these validation checks happen deeper down.. - // thing they can be avoided.. - if (!destinationFrame) - { - tempRect.width = renderer.width; - tempRect.height = renderer.height; - - destinationFrame = tempRect; - } - - if (!sourceFrame) - { - sourceFrame = destinationFrame; - } - - renderer.framebuffer.bind(null, destinationFrame); - - // TODO store this.. - this.renderer.projection.update(destinationFrame, sourceFrame, resolution, true); - this.renderer.mask.setMaskStack(this.defaultMaskStack); - } - - this.sourceFrame.copyFrom(sourceFrame); - - this.destinationFrame.x = destinationFrame.x / resolution; - this.destinationFrame.y = destinationFrame.y / resolution; - - this.destinationFrame.width = destinationFrame.width / resolution; - this.destinationFrame.height = destinationFrame.height / resolution; - - if (sourceFrame === destinationFrame) - { - this.sourceFrame.copyFrom(this.destinationFrame); + DisplayObject.mixin = function (source) { + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(DisplayObject.prototype, Object.getOwnPropertyDescriptors(source)); + // get all the enumerable property keys + var keys = Object.keys(source); + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); } }; - /** - * Erases the render texture and fills the drawing area with a colour - * - * @param {number[]} [clearColor] - The color as rgba, default to use the renderer backgroundColor - * @return {PIXI.Renderer} Returns itself. + * Recursively updates transform of all objects from the root to this one + * internal function for toLocal() */ - RenderTextureSystem.prototype.clear = function clear (clearColor) - { - if (this.current) - { - clearColor = clearColor || this.current.baseTexture.clearColor; + DisplayObject.prototype._recursivePostUpdateTransform = function () { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); } - else - { - clearColor = clearColor || this.clearColor; + else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); } - - this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); - }; - - RenderTextureSystem.prototype.resize = function resize ()// screenWidth, screenHeight) - { - // resize the root only! - this.bind(null); }; - /** - * Resets renderTexture state + * Updates the object transform for rendering. + * + * TODO - Optimization pass! */ - RenderTextureSystem.prototype.reset = function reset () - { - this.bind(null); + DisplayObject.prototype.updateTransform = function () { + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; }; - - return RenderTextureSystem; -}(System)); - -/** - * Helper class to create a WebGL Program - * - * @class - * @memberof PIXI - */ -var GLProgram = function GLProgram(program, uniformData) -{ /** - * The shader program + * Retrieves the bounds of the displayObject as a rectangle object. * - * @member {WebGLProgram} - */ - this.program = program; - - /** - * holds the uniform data which contains uniform locations - * and current uniform values used for caching and preventing unneeded GPU commands - * @member {Object} + * @param {boolean} [skipUpdate] - Setting to `true` will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost. + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. + * @return {PIXI.Rectangle} The rectangular bounding area. */ - this.uniformData = uniformData; - + DisplayObject.prototype.getBounds = function (skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } + else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + if (this._bounds.updateID !== this._boundsID) { + this.calculateBounds(); + this._bounds.updateID = this._boundsID; + } + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new math.Rectangle(); + } + rect = this._boundsRect; + } + return this._bounds.getRectangle(rect); + }; /** - * uniformGroups holds the various upload functions for the shader. Each uniform group - * and program have a unique upload function generated. - * @member {Object} + * Retrieves the local bounds of the displayObject as a rectangle object. + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. + * @return {PIXI.Rectangle} The rectangular bounding area. */ - this.uniformGroups = {}; -}; - -/** - * Destroys this program - */ -GLProgram.prototype.destroy = function destroy () -{ - this.uniformData = null; - this.uniformGroups = null; - this.program = null; -}; - -var UID$4 = 0; - -/** - * System plugin to the renderer to manage shaders. - * - * @class - * @memberof PIXI.systems - * @extends PIXI.System - */ -var ShaderSystem = /*@__PURE__*/(function (System) { - function ShaderSystem(renderer) - { - System.call(this, renderer); - - // Validation check that this environment support `new Function` - this.systemCheck(); - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = null; - - this.shader = null; - this.program = null; - - /** - * Cache to holds the generated functions. Stored against UniformObjects unique signature - * @type {Object} - * @private - */ - this.cache = {}; - - this.id = UID$4++; - } - - if ( System ) ShaderSystem.__proto__ = System; - ShaderSystem.prototype = Object.create( System && System.prototype ); - ShaderSystem.prototype.constructor = ShaderSystem; - + DisplayObject.prototype.getLocalBounds = function (rect) { + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new math.Rectangle(); + } + rect = this._localBoundsRect; + } + if (!this._localBounds) { + this._localBounds = new Bounds(); + } + var transformRef = this.transform; + var parentRef = this.parent; + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + var worldBounds = this._bounds; + var worldBoundsID = this._boundsID; + this._bounds = this._localBounds; + var bounds = this.getBounds(false, rect); + this.parent = parentRef; + this.transform = transformRef; + this._bounds = worldBounds; + this._bounds.updateID += this._boundsID - worldBoundsID; // reflect side-effects + return bounds; + }; /** - * Overrideable function by `@pixi/unsafe-eval` to silence - * throwing an error if platform doesn't support unsafe-evals. + * Calculates the global position of the display object. * - * @private + * @param {PIXI.IPointData} position - The world origin to calculate from. + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point). + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object. */ - ShaderSystem.prototype.systemCheck = function systemCheck () - { - if (!unsafeEvalSupported()) - { - throw new Error('Current environment does not allow unsafe-eval, ' - + 'please use @pixi/unsafe-eval module to enable support.'); + DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) { + if (skipUpdate === void 0) { skipUpdate = false; } + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else { + this.displayObjectUpdateTransform(); + } } + // don't need to update the lot + return this.worldTransform.apply(position, point); }; - - ShaderSystem.prototype.contextChange = function contextChange (gl) - { - this.gl = gl; - this.reset(); - }; - /** - * Changes the current shader to the one given in parameter + * Calculates the local position of the display object relative to another point. * - * @param {PIXI.Shader} shader - the new shader - * @param {boolean} dontSync - false if the shader should automatically sync its uniforms. - * @returns {PIXI.GLProgram} the glProgram that belongs to the shader. + * @param {PIXI.IPointData} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from. + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point). + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object */ - ShaderSystem.prototype.bind = function bind (shader, dontSync) - { - shader.uniforms.globals = this.renderer.globalUniforms; - - var program = shader.program; - var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateShader(shader); - - this.shader = shader; - - // TODO - some current Pixi plugins bypass this.. so it not safe to use yet.. - if (this.program !== program) - { - this.program = program; - this.gl.useProgram(glProgram.program); + DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); } - - if (!dontSync) - { - this.syncUniformGroup(shader.uniformGroup); + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else { + this.displayObjectUpdateTransform(); + } } - - return glProgram; + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); }; - /** - * Uploads the uniforms values to the currently bound shader. + * Set the parent Container of this DisplayObject. * - * @param {object} uniforms - the uniforms values that be applied to the current shader + * @param {PIXI.Container} container - The Container to add this DisplayObject to. + * @return {PIXI.Container} The Container that this DisplayObject was added to. */ - ShaderSystem.prototype.setUniforms = function setUniforms (uniforms) - { - var shader = this.shader.program; - var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID]; - - shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer); - }; - - ShaderSystem.prototype.syncUniformGroup = function syncUniformGroup (group) - { - var glProgram = this.getglProgram(); - - if (!group.static || group.dirtyId !== glProgram.uniformGroups[group.id]) - { - glProgram.uniformGroups[group.id] = group.dirtyId; - - this.syncUniforms(group, glProgram); + DisplayObject.prototype.setParent = function (container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); } + container.addChild(this); + return container; }; - /** - * Overrideable by the @pixi/unsafe-eval package to use static - * syncUnforms instead. + * Convenience function to set the position, scale, skew and pivot at once. * - * @private + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance */ - ShaderSystem.prototype.syncUniforms = function syncUniforms (group, glProgram) - { - var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); - - syncFunc(glProgram.uniformData, group.uniforms, this.renderer); - }; - - ShaderSystem.prototype.createSyncGroups = function createSyncGroups (group) - { - var id = this.getSignature(group, this.shader.program.uniformData); - - if (!this.cache[id]) - { - this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData); - } - - group.syncUniforms[this.shader.program.id] = this.cache[id]; - - return group.syncUniforms[this.shader.program.id]; + DisplayObject.prototype.setTransform = function (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (scaleX === void 0) { scaleX = 1; } + if (scaleY === void 0) { scaleY = 1; } + if (rotation === void 0) { rotation = 0; } + if (skewX === void 0) { skewX = 0; } + if (skewY === void 0) { skewY = 0; } + if (pivotX === void 0) { pivotX = 0; } + if (pivotY === void 0) { pivotY = 0; } + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + return this; }; - /** - * Takes a uniform group and data and generates a unique signature for them. + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy()`. * - * @param {PIXI.UniformGroup} group the uniform group to get signature of - * @param {Object} uniformData uniform information generated by the shader - * @returns {String} Unique signature of the uniform group - * @private */ - ShaderSystem.prototype.getSignature = function getSignature (group, uniformData) - { - var uniforms = group.uniforms; - - var strings = []; - - for (var i in uniforms) - { - strings.push(i); - - if (uniformData[i]) - { - strings.push(uniformData[i].type); - } + DisplayObject.prototype.destroy = function (_options) { + if (this.parent) { + this.parent.removeChild(this); } - - return strings.join('-'); + this.removeAllListeners(); + this.transform = null; + this.parent = null; + this._bounds = null; + this._mask = null; + this.filters = null; + this.filterArea = null; + this.hitArea = null; + this.interactive = false; + this.interactiveChildren = false; + this._destroyed = true; }; - + Object.defineProperty(DisplayObject.prototype, "_tempDisplayObjectParent", { + /** + * @protected + * @member {PIXI.Container} + */ + get: function () { + if (this.tempDisplayObjectParent === null) { + // eslint-disable-next-line no-use-before-define + this.tempDisplayObjectParent = new TemporaryDisplayObject(); + } + return this.tempDisplayObjectParent; + }, + enumerable: false, + configurable: true + }); /** - * Returns the underlying GLShade rof the currently bound shader. - * This can be handy for when you to have a little more control over the setting of your uniforms. + * Used in Renderer, cacheAsBitmap and other places where you call an `updateTransform` on root * - * @return {PIXI.GLProgram} the glProgram for the currently bound Shader for this context + * ``` + * const cacheParent = elem.enableTempParent(); + * elem.updateTransform(); + * elem.disableTempParent(cacheParent); + * ``` + * + * @returns {PIXI.DisplayObject} current parent */ - ShaderSystem.prototype.getglProgram = function getglProgram () - { - if (this.shader) - { - return this.shader.program.glPrograms[this.renderer.CONTEXT_UID]; - } - - return null; + DisplayObject.prototype.enableTempParent = function () { + var myParent = this.parent; + this.parent = this._tempDisplayObjectParent; + return myParent; }; - /** - * Generates a glProgram version of the Shader provided. - * - * @private - * @param {PIXI.Shader} shader the shader that the glProgram will be based on. - * @return {PIXI.GLProgram} A shiny new glProgram! + * Pair method for `enableTempParent` + * @param {PIXI.DisplayObject} cacheParent actual parent of element */ - ShaderSystem.prototype.generateShader = function generateShader (shader) - { - var gl = this.gl; - - var program = shader.program; - - var attribMap = {}; - - for (var i in program.attributeData) - { - attribMap[i] = program.attributeData[i].location; - } - - var shaderProgram = compileProgram(gl, program.vertexSrc, program.fragmentSrc, attribMap); - var uniformData = {}; - - for (var i$1 in program.uniformData) - { - var data = program.uniformData[i$1]; - - uniformData[i$1] = { - location: gl.getUniformLocation(shaderProgram, i$1), - value: defaultValue(data.type, data.size), - }; - } - - var glProgram = new GLProgram(shaderProgram, uniformData); - - program.glPrograms[this.renderer.CONTEXT_UID] = glProgram; - - return glProgram; - }; - - /** - * Resets ShaderSystem state, does not affect WebGL state - */ - ShaderSystem.prototype.reset = function reset () - { - this.program = null; - this.shader = null; - }; - - /** - * Destroys this System and removes all its textures - */ - ShaderSystem.prototype.destroy = function destroy () - { - // TODO implement destroy method for ShaderSystem - this.destroyed = true; + DisplayObject.prototype.disableTempParent = function (cacheParent) { + this.parent = cacheParent; }; - - return ShaderSystem; -}(System)); - -/** - * Maps gl blend combinations to WebGL. - * - * @memberof PIXI - * @function mapWebGLBlendModesToPixi - * @private - * @param {WebGLRenderingContext} gl - The rendering context. - * @param {number[][]} [array=[]] - The array to output into. - * @return {number[][]} Mapped modes. - */ -function mapWebGLBlendModesToPixi(gl, array) -{ - if ( array === void 0 ) array = []; - - // TODO - premultiply alpha would be different. - // add a boolean for that! - array[constants.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; - array[constants.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.NONE] = [0, 0]; - - // not-premultiplied blend modes - array[constants.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; - array[constants.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - - // composite operations - array[constants.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO]; - array[constants.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO]; - array[constants.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE]; - array[constants.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA]; - array[constants.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA]; - array[constants.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA]; - array[constants.BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; - - // SUBTRACT from flash - array[constants.BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD]; - - return array; -} - -var BLEND$1 = 0; -var OFFSET$1 = 1; -var CULLING$1 = 2; -var DEPTH_TEST$1 = 3; -var WINDING$1 = 4; - -/** - * System plugin to the renderer to manage WebGL state machines. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ -var StateSystem = /*@__PURE__*/(function (System) { - function StateSystem(renderer) - { - System.call(this, renderer); - + Object.defineProperty(DisplayObject.prototype, "x", { /** - * GL context - * @member {WebGLRenderingContext} - * @readonly + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} */ - this.gl = null; - + get: function () { + return this.position.x; + }, + set: function (value) { + this.transform.position.x = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "y", { /** - * State ID + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * * @member {number} + */ + get: function () { + return this.position.y; + }, + set: function (value) { + this.transform.position.y = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "worldTransform", { + /** + * Current transform of the object based on world (parent) factors. + * + * @member {PIXI.Matrix} * @readonly */ - this.stateId = 0; - + get: function () { + return this.transform.worldTransform; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "localTransform", { /** - * Polygon offset - * @member {number} + * Current transform of the object based on local factors: position, scale, other stuff. + * + * @member {PIXI.Matrix} * @readonly */ - this.polygonOffset = 0; - + get: function () { + return this.transform.localTransform; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "position", { /** - * Blend mode + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + get: function () { + return this.transform.position; + }, + set: function (value) { + this.transform.position.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "scale", { + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + get: function () { + return this.transform.scale; + }, + set: function (value) { + this.transform.scale.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "pivot", { + /** + * The pivot point of the displayObject that it rotates around. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + get: function () { + return this.transform.pivot; + }, + set: function (value) { + this.transform.pivot.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "skew", { + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + get: function () { + return this.transform.skew; + }, + set: function (value) { + this.transform.skew.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "rotation", { + /** + * The rotation of the object in radians. + * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + * * @member {number} - * @default PIXI.BLEND_MODES.NONE - * @readonly */ - this.blendMode = constants.BLEND_MODES.NONE; - + get: function () { + return this.transform.rotation; + }, + set: function (value) { + this.transform.rotation = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "angle", { /** - * Whether current blend equation is different - * @member {boolean} - * @protected + * The angle of the object in degrees. + * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + * + * @member {number} */ - this._blendEq = false; - + get: function () { + return this.transform.rotation * math.RAD_TO_DEG; + }, + set: function (value) { + this.transform.rotation = value * math.DEG_TO_RAD; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "zIndex", { /** - * Collection of calls - * @member {function[]} - * @readonly + * The zIndex of the displayObject. + * If a container has the sortableChildren property set to true, children will be automatically + * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, + * and thus rendered on top of other displayObjects within the same container. + * + * @member {number} */ - this.map = []; - - // map functions for when we set state.. - this.map[BLEND$1] = this.setBlend; - this.map[OFFSET$1] = this.setOffset; - this.map[CULLING$1] = this.setCullFace; - this.map[DEPTH_TEST$1] = this.setDepthTest; - this.map[WINDING$1] = this.setFrontFace; - + get: function () { + return this._zIndex; + }, + set: function (value) { + this._zIndex = value; + if (this.parent) { + this.parent.sortDirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "worldVisible", { /** - * Collection of check calls - * @member {function[]} + * Indicates if the object is globally visible. + * + * @member {boolean} * @readonly */ - this.checks = []; + get: function () { + var item = this; + do { + if (!item.visible) { + return false; + } + item = item.parent; + } while (item); + return true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "mask", { + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PixiJS a regular mask must be a + * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it + * utilities shape clipping. To remove a mask, set this property to `null`. + * + * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask. + * @example + * const graphics = new PIXI.Graphics(); + * graphics.beginFill(0xFF3300); + * graphics.drawRect(50, 250, 100, 100); + * graphics.endFill(); + * + * const sprite = new PIXI.Sprite(texture); + * sprite.mask = graphics; + * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Container|PIXI.MaskData|null} + */ + get: function () { + return this._mask; + }, + set: function (value) { + if (this._mask) { + var maskObject = (this._mask.maskObject || this._mask); + maskObject.renderable = true; + maskObject.isMask = false; + } + this._mask = value; + if (this._mask) { + var maskObject = (this._mask.maskObject || this._mask); + maskObject.renderable = false; + maskObject.isMask = true; + } + }, + enumerable: false, + configurable: true + }); + return DisplayObject; +}(utils.EventEmitter)); +var TemporaryDisplayObject = /** @class */ (function (_super) { + __extends(TemporaryDisplayObject, _super); + function TemporaryDisplayObject() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.sortDirty = null; + return _this; + } + return TemporaryDisplayObject; +}(DisplayObject)); +/** + * DisplayObject default updateTransform, does not update children of container. + * Will crash if there's no parent element. + * + * @memberof PIXI.DisplayObject# + * @function displayObjectUpdateTransform + */ +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; +function sortChildren(a, b) { + if (a.zIndex === b.zIndex) { + return a._lastSortedIndex - b._lastSortedIndex; + } + return a.zIndex - b.zIndex; +} +/** + * A Container represents a collection of display objects. + * + * It is the base class of all display objects that act as a container for other objects (like Sprites). + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = /** @class */ (function (_super) { + __extends(Container, _super); + function Container() { + var _this = _super.call(this) || this; /** - * Default WebGL State - * @member {PIXI.State} + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} * @readonly */ - this.defaultState = new State(); - this.defaultState.blend = true; - this.defaultState.depth = true; + _this.children = []; + /** + * If set to true, the container will sort its children by zIndex value + * when updateTransform() is called, or manually if sortChildren() is called. + * + * This actually changes the order of elements in the array, so should be treated + * as a basic solution that is not performant compared to other solutions, + * such as @link https://github.com/pixijs/pixi-display + * + * Also be aware of that this may not work nicely with the addChildAt() function, + * as the zIndex sorting may cause the child to automatically sorted to another position. + * + * @see PIXI.settings.SORTABLE_CHILDREN + * + * @member {boolean} + */ + _this.sortableChildren = settings.settings.SORTABLE_CHILDREN; + /** + * Should children be sorted by zIndex at the next updateTransform call. + * Will get automatically set to true if a new child is added, or if a child's zIndex changes. + * + * @member {boolean} + */ + _this.sortDirty = false; + return _this; + /** + * Fired when a DisplayObject is added to this Container. + * + * @event PIXI.Container#childAdded + * @param {PIXI.DisplayObject} child - The child added to the Container. + * @param {PIXI.Container} container - The container that added the child. + * @param {number} index - The children's index of the added child. + */ + /** + * Fired when a DisplayObject is removed from this Container. + * + * @event PIXI.DisplayObject#removedFrom + * @param {PIXI.DisplayObject} child - The child removed from the Container. + * @param {PIXI.Container} container - The container that removed removed the child. + * @param {number} index - The former children's index of the removed child + */ } - - if ( System ) StateSystem.__proto__ = System; - StateSystem.prototype = Object.create( System && System.prototype ); - StateSystem.prototype.constructor = StateSystem; - - StateSystem.prototype.contextChange = function contextChange (gl) - { - this.gl = gl; - - this.blendModes = mapWebGLBlendModesToPixi(gl); - - this.set(this.defaultState); - - this.reset(); + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @protected + */ + Container.prototype.onChildrenChange = function (_length) { + /* empty */ }; - /** - * Sets the current state + * Adds one or more children to the container. * - * @param {*} state - The state to set. + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. */ - StateSystem.prototype.set = function set (state) - { - state = state || this.defaultState; - - // TODO maybe to an object check? ( this.state === state )? - if (this.stateId !== state.data) - { - var diff = this.stateId ^ state.data; - var i = 0; - - // order from least to most common - while (diff) - { - if (diff & 1) - { - // state change! - this.map[i].call(this, !!(state.data & (1 << i))); - } + Container.prototype.addChild = function () { + var arguments$1 = arguments; - diff = diff >> 1; - i++; + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments$1[_i]; + } + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the array and add all children + for (var i = 0; i < children.length; i++) { + // eslint-disable-next-line prefer-rest-params + this.addChild(children[i]); } - - this.stateId = state.data; } - - // based on the above settings we check for specific modes.. - // for example if blend is active we check and set the blend modes - // or of polygon offset is active we check the poly depth. - for (var i$1 = 0; i$1 < this.checks.length; i$1++) - { - this.checks[i$1](this, state); + else { + var child = children[0]; + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + this.children.push(child); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + this.emit('childAdded', child, this, this.children.length - 1); + child.emit('added', this); } + return children[0]; }; - /** - * Sets the state, when previous state is unknown + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown * - * @param {*} state - The state to set + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. */ - StateSystem.prototype.forceState = function forceState (state) - { - state = state || this.defaultState; - for (var i = 0; i < this.map.length; i++) - { - this.map[i].call(this, !!(state.data & (1 << i))); + Container.prototype.addChildAt = function (child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + "addChildAt: The index " + index + " supplied is out of bounds " + this.children.length); } - for (var i$1 = 0; i$1 < this.checks.length; i$1++) - { - this.checks[i$1](this, state); + if (child.parent) { + child.parent.removeChild(child); } - - this.stateId = state.data; + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + this.children.splice(index, 0, child); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + this.emit('childAdded', child, this, index); + return child; }; - /** - * Enables or disabled blending. + * Swaps the position of 2 Display Objects within this container. * - * @param {boolean} value - Turn on or off webgl blending. + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap */ - StateSystem.prototype.setBlend = function setBlend (value) - { - this.updateCheck(StateSystem.checkBlendMode, value); - - this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + Container.prototype.swapChildren = function (child, child2) { + if (child === child2) { + return; + } + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); }; - /** - * Enables or disable polygon offset fill + * Returns the index position of a child DisplayObject instance * - * @param {boolean} value - Turn on or off webgl polygon offset testing. + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify */ - StateSystem.prototype.setOffset = function setOffset (value) - { - this.updateCheck(StateSystem.checkPolygonOffset, value); - - this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL); + Container.prototype.getChildIndex = function (child) { + var index = this.children.indexOf(child); + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + return index; }; - /** - * Sets whether to enable or disable depth test. + * Changes the position of an existing child in the display object container * - * @param {boolean} value - Turn on or off webgl depth testing. + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object */ - StateSystem.prototype.setDepthTest = function setDepthTest (value) - { - this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + Container.prototype.setChildIndex = function (child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error("The index " + index + " supplied is out of bounds " + this.children.length); + } + var currentIndex = this.getChildIndex(child); + utils.removeItems(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + this.onChildrenChange(index); }; - /** - * Sets whether to enable or disable cull face. + * Returns the child at the specified index * - * @param {boolean} value - Turn on or off webgl cull face. + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. */ - StateSystem.prototype.setCullFace = function setCullFace (value) - { - this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + Container.prototype.getChildAt = function (index) { + if (index < 0 || index >= this.children.length) { + throw new Error("getChildAt: Index (" + index + ") does not exist."); + } + return this.children[index]; }; - /** - * Sets the gl front face. + * Removes one or more children from the container. * - * @param {boolean} value - true is clockwise and false is counter-clockwise + * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. */ - StateSystem.prototype.setFrontFace = function setFrontFace (value) - { - this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); - }; + Container.prototype.removeChild = function () { + var arguments$1 = arguments; + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments$1[_i]; + } + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the arguments property and remove all children + for (var i = 0; i < children.length; i++) { + this.removeChild(children[i]); + } + } + else { + var child = children[0]; + var index = this.children.indexOf(child); + if (index === -1) + { return null; } + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + utils.removeItems(this.children, index, 1); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + this.emit('childRemoved', child, this, index); + } + return children[0]; + }; /** - * Sets the blend mode. + * Removes a child from the specified index position. * - * @param {number} value - The blend mode to set to. + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. */ - StateSystem.prototype.setBlendMode = function setBlendMode (value) - { - if (value === this.blendMode) - { - return; - } - - this.blendMode = value; - - var mode = this.blendModes[value]; - var gl = this.gl; - - if (mode.length === 2) - { - gl.blendFunc(mode[0], mode[1]); - } - else - { - gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); - } - if (mode.length === 6) - { - this._blendEq = true; - gl.blendEquationSeparate(mode[4], mode[5]); + Container.prototype.removeChildAt = function (index) { + var child = this.getChildAt(index); + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + utils.removeItems(this.children, index, 1); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + this.emit('childRemoved', child, this, index); + return child; + }; + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {PIXI.DisplayObject[]} List of removed children + */ + Container.prototype.removeChildren = function (beginIndex, endIndex) { + if (beginIndex === void 0) { beginIndex = 0; } + if (endIndex === void 0) { endIndex = this.children.length; } + var begin = beginIndex; + var end = endIndex; + var range = end - begin; + var removed; + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + this._boundsID++; + this.onChildrenChange(beginIndex); + for (var i = 0; i < removed.length; ++i) { + removed[i].emit('removed', this); + this.emit('childRemoved', removed[i], this, i); + } + return removed; } - else if (this._blendEq) - { - this._blendEq = false; - gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + else if (range === 0 && this.children.length === 0) { + return []; } + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); }; - /** - * Sets the polygon offset. - * - * @param {number} value - the polygon offset - * @param {number} scale - the polygon offset scale + * Sorts children by zIndex. Previous order is mantained for 2 children with the same zIndex. */ - StateSystem.prototype.setPolygonOffset = function setPolygonOffset (value, scale) - { - this.gl.polygonOffset(value, scale); + Container.prototype.sortChildren = function () { + var sortRequired = false; + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + child._lastSortedIndex = i; + if (!sortRequired && child.zIndex !== 0) { + sortRequired = true; + } + } + if (sortRequired && this.children.length > 1) { + this.children.sort(sortChildren); + } + this.sortDirty = false; }; - - // used /** - * Resets all the logic and disables the vaos + * Updates the transform on all children of this container for rendering */ - StateSystem.prototype.reset = function reset () - { - this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); - - this.forceState(0); - - this._blendEq = true; - this.blendMode = -1; - this.setBlendMode(0); + Container.prototype.updateTransform = function () { + if (this.sortableChildren && this.sortDirty) { + this.sortChildren(); + } + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } }; - /** - * checks to see which updates should be checked based on which settings have been activated. - * For example, if blend is enabled then we should check the blend modes each time the state is changed - * or if polygon fill is activated then we need to check if the polygon offset changes. - * The idea is that we only check what we have too. + * Recalculates the bounds of the container. * - * @param {Function} func the checking function to add or remove - * @param {boolean} value should the check function be added or removed. */ - StateSystem.prototype.updateCheck = function updateCheck (func, value) - { - var index = this.checks.indexOf(func); - - if (value && index === -1) - { - this.checks.push(func); - } - else if (!value && index !== -1) - { - this.checks.splice(index, 1); + Container.prototype.calculateBounds = function () { + this._bounds.clear(); + this._calculateBounds(); + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + if (!child.visible || !child.renderable) { + continue; + } + child.calculateBounds(); + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + var maskObject = (child._mask.maskObject || child._mask); + maskObject.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, maskObject._bounds); + } + else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } + else { + this._bounds.addBounds(child._bounds); + } } + this._bounds.updateID = this._boundsID; }; - /** - * A private little wrapper function that we call to check the blend mode. + * Retrieves the local bounds of the displayObject as a rectangle object. * - * @static - * @private - * @param {PIXI.StateSystem} System the System to perform the state check on - * @param {PIXI.State} state the state that the blendMode will pulled from + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. + * @param {boolean} [skipChildrenUpdate=false] - Setting to `true` will stop re-calculation of children transforms, + * it was default behaviour of pixi 4.0-5.2 and caused many problems to users. + * @return {PIXI.Rectangle} The rectangular bounding area. */ - StateSystem.checkBlendMode = function checkBlendMode (system, state) - { - system.setBlendMode(state.blendMode); + Container.prototype.getLocalBounds = function (rect, skipChildrenUpdate) { + if (skipChildrenUpdate === void 0) { skipChildrenUpdate = false; } + var result = _super.prototype.getLocalBounds.call(this, rect); + if (!skipChildrenUpdate) { + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } + } + return result; }; - /** - * A private little wrapper function that we call to check the polygon offset. + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). * - * @static - * @private - * @param {PIXI.StateSystem} System the System to perform the state check on - * @param {PIXI.State} state the state that the blendMode will pulled from + * @protected */ - StateSystem.checkPolygonOffset = function checkPolygonOffset (system, state) - { - system.setPolygonOffset(state.polygonOffset, 0); + Container.prototype._calculateBounds = function () { + // FILL IN// }; - - return StateSystem; -}(System)); - -/** - * System plugin to the renderer to manage texture garbage collection on the GPU, - * ensuring that it does not get clogged up with textures that are no longer being used. - * - * @class - * @memberof PIXI.systems - * @extends PIXI.System - */ -var TextureGCSystem = /*@__PURE__*/(function (System) { - function TextureGCSystem(renderer) - { - System.call(this, renderer); - - /** - * Count - * @member {number} - * @readonly - */ - this.count = 0; - - /** - * Check count - * @member {number} - * @readonly - */ - this.checkCount = 0; - - /** - * Maximum idle time, in seconds - * @member {number} - * @see PIXI.settings.GC_MAX_IDLE - */ - this.maxIdle = settings.settings.GC_MAX_IDLE; - - /** - * Maximum number of item to check - * @member {number} - * @see PIXI.settings.GC_MAX_CHECK_COUNT - */ - this.checkCountMax = settings.settings.GC_MAX_CHECK_COUNT; - - /** - * Current garabage collection mode - * @member {PIXI.GC_MODES} - * @see PIXI.settings.GC_MODE - */ - this.mode = settings.settings.GC_MODE; - } - - if ( System ) TextureGCSystem.__proto__ = System; - TextureGCSystem.prototype = Object.create( System && System.prototype ); - TextureGCSystem.prototype.constructor = TextureGCSystem; - /** - * Checks to see when the last time a texture was used - * if the texture has not been used for a specified amount of time it will be removed from the GPU + * Renders the object using the WebGL renderer + * + * @param {PIXI.Renderer} renderer - The renderer */ - TextureGCSystem.prototype.postrender = function postrender () - { - if (!this.renderer.renderingToScreen) - { + Container.prototype.render = function (renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { return; } - - this.count++; - - if (this.mode === constants.GC_MODES.MANUAL) - { - return; + // do a quick check to see if this element has a mask or a filter. + if (this._mask || (this.filters && this.filters.length)) { + this.renderAdvanced(renderer); } - - this.checkCount++; - - if (this.checkCount > this.checkCountMax) - { - this.checkCount = 0; - - this.run(); + else { + this._render(renderer); + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].render(renderer); + } } }; - /** - * Checks to see when the last time a texture was used - * if the texture has not been used for a specified amount of time it will be removed from the GPU + * Render the object using the WebGL renderer and advanced features. + * + * @protected + * @param {PIXI.Renderer} renderer - The renderer */ - TextureGCSystem.prototype.run = function run () - { - var tm = this.renderer.texture; - var managedTextures = tm.managedTextures; - var wasRemoved = false; - - for (var i = 0; i < managedTextures.length; i++) - { - var texture = managedTextures[i]; - - // only supports non generated textures at the moment! - if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) - { - tm.destroyTexture(texture, true); - managedTextures[i] = null; - wasRemoved = true; + Container.prototype.renderAdvanced = function (renderer) { + renderer.batch.flush(); + var filters = this.filters; + var mask = this._mask; + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; } - } - - if (wasRemoved) - { - var j = 0; - - for (var i$1 = 0; i$1 < managedTextures.length; i$1++) - { - if (managedTextures[i$1] !== null) - { - managedTextures[j++] = managedTextures[i$1]; + this._enabledFilters.length = 0; + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); } } - - managedTextures.length = j; + if (this._enabledFilters.length) { + renderer.filter.push(this, this._enabledFilters); + } + } + if (mask) { + renderer.mask.push(this, this._mask); + } + // add this object to the batch, only rendered if it has a texture. + this._render(renderer); + // now loop through the children and make sure they get rendered + for (var i = 0, j = this.children.length; i < j; i++) { + this.children[i].render(renderer); + } + renderer.batch.flush(); + if (mask) { + renderer.mask.pop(this); + } + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filter.pop(); } }; - /** - * Removes all the textures within the specified displayObject and its children from the GPU + * To be overridden by the subclasses. * - * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + * @protected + * @param {PIXI.Renderer} renderer - The renderer */ - TextureGCSystem.prototype.unload = function unload (displayObject) - { - var tm = this.renderer.textureSystem; - - // only destroy non generated textures - if (displayObject._texture && displayObject._texture._glRenderTargets) - { - tm.destroyTexture(displayObject._texture); - } - - for (var i = displayObject.children.length - 1; i >= 0; i--) - { - this.unload(displayObject.children[i]); + Container.prototype._render = function (_renderer) { + // this is where content itself gets rendered... + }; + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Container.prototype.destroy = function (options) { + _super.prototype.destroy.call(this); + this.sortDirty = false; + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + var oldChildren = this.removeChildren(0, this.children.length); + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } } }; + Object.defineProperty(Container.prototype, "width", { + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + get: function () { + return this.scale.x * this.getLocalBounds().width; + }, + set: function (value) { + var width = this.getLocalBounds().width; + if (width !== 0) { + this.scale.x = value / width; + } + else { + this.scale.x = 1; + } + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Container.prototype, "height", { + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + get: function () { + return this.scale.y * this.getLocalBounds().height; + }, + set: function (value) { + var height = this.getLocalBounds().height; + if (height !== 0) { + this.scale.y = value / height; + } + else { + this.scale.y = 1; + } + this._height = value; + }, + enumerable: false, + configurable: true + }); + return Container; +}(DisplayObject)); +/** + * Container default updateTransform, does update children of container. + * Will crash if there's no parent element. + * + * @memberof PIXI.Container# + * @function containerUpdateTransform + */ +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; - return TextureGCSystem; -}(System)); +exports.Bounds = Bounds; +exports.Container = Container; +exports.DisplayObject = DisplayObject; +exports.TemporaryDisplayObject = TemporaryDisplayObject; + + +},{"@pixi/math":20,"@pixi/settings":30,"@pixi/utils":38}],10:[function(require,module,exports){ +/*! + * @pixi/extract - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/extract is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var utils = require('@pixi/utils'); +var math = require('@pixi/math'); +var core = require('@pixi/core'); +var TEMP_RECT = new math.Rectangle(); +var BYTES_PER_PIXEL = 4; /** - * Internal texture for WebGL context + * This class provides renderer-specific plugins for exporting content from a renderer. + * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels). + * + * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property. + * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. + * @example + * // Create a new app (will auto-add extract plugin to renderer) + * const app = new PIXI.Application(); + * + * // Draw a red circle + * const graphics = new PIXI.Graphics() + * .beginFill(0xFF0000) + * .drawCircle(0, 0, 50); + * + * // Render the graphics as an HTMLImageElement + * const image = app.renderer.plugins.extract.image(graphics); + * document.body.appendChild(image); * @class * @memberof PIXI */ -var GLTexture = function GLTexture(texture) -{ +var Extract = /** @class */ (function () { /** - * The WebGL texture - * @member {WebGLTexture} + * @param {PIXI.Renderer} renderer - A reference to the current renderer */ - this.texture = texture; - + function Extract(renderer) { + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.Extract} extract + * @memberof PIXI.Renderer# + * @see PIXI.Extract + */ + renderer.extract = this; + } /** - * Width of texture that was used in texImage2D - * @member {number} + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp". + * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92. + * @return {HTMLImageElement} HTML Image of the target */ - this.width = -1; - + Extract.prototype.image = function (target, format, quality) { + var image = new Image(); + image.src = this.base64(target, format, quality); + return image; + }; /** - * Height of texture that was used in texImage2D - * @member {number} + * Will return a a base64 encoded string of this target. It works by calling + * `Extract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp". + * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92. + * @return {string} A base64 encoded string of the texture. */ - this.height = -1; - + Extract.prototype.base64 = function (target, format, quality) { + return this.canvas(target).toDataURL(format, quality); + }; /** - * Texture contents dirty flag - * @member {number} + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. */ - this.dirtyId = -1; - + Extract.prototype.canvas = function (target) { + var renderer = this.renderer; + var resolution; + var frame; + var flipY = false; + var renderTexture; + var generated = false; + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } + else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + if (renderTexture) { + resolution = renderTexture.baseTexture.resolution; + frame = renderTexture.frame; + flipY = false; + renderer.renderTexture.bind(renderTexture); + } + else { + resolution = this.renderer.resolution; + flipY = true; + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + renderer.renderTexture.bind(null); + } + var width = Math.floor((frame.width * resolution) + 1e-4); + var height = Math.floor((frame.height * resolution) + 1e-4); + var canvasBuffer = new utils.CanvasRenderTarget(width, height, 1); + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + Extract.arrayPostDivide(webglPixels, canvasData.data); + canvasBuffer.context.putImageData(canvasData, 0, 0); + // pulling pixels + if (flipY) { + var target_1 = new utils.CanvasRenderTarget(canvasBuffer.width, canvasBuffer.height, 1); + target_1.context.scale(1, -1); + // we can't render to itself because we should be empty before render. + target_1.context.drawImage(canvasBuffer.canvas, 0, -height); + canvasBuffer.destroy(); + canvasBuffer = target_1; + } + if (generated) { + renderTexture.destroy(true); + } + // send the canvas back.. + return canvasBuffer.canvas; + }; + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @return {Uint8Array} One-dimensional array containing the pixel data of the entire texture + */ + Extract.prototype.pixels = function (target) { + var renderer = this.renderer; + var resolution; + var frame; + var renderTexture; + var generated = false; + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } + else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + if (renderTexture) { + resolution = renderTexture.baseTexture.resolution; + frame = renderTexture.frame; + // bind the buffer + renderer.renderTexture.bind(renderTexture); + } + else { + resolution = renderer.resolution; + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + renderer.renderTexture.bind(null); + } + var width = frame.width * resolution; + var height = frame.height * resolution; + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + if (generated) { + renderTexture.destroy(true); + } + Extract.arrayPostDivide(webglPixels, webglPixels); + return webglPixels; + }; /** - * Texture style dirty flag - * @member {number} + * Destroys the extract + * */ - this.dirtyStyleId = -1; - + Extract.prototype.destroy = function () { + this.renderer.extract = null; + this.renderer = null; + }; /** - * Whether mip levels has to be generated - * @member {boolean} + * Takes premultiplied pixel data and produces regular pixel data + * + * @private + * @param pixels {number[] | Uint8Array | Uint8ClampedArray} array of pixel data + * @param out {number[] | Uint8Array | Uint8ClampedArray} output array */ - this.mipmap = false; + Extract.arrayPostDivide = function (pixels, out) { + for (var i = 0; i < pixels.length; i += 4) { + var alpha = out[i + 3] = pixels[i + 3]; + if (alpha !== 0) { + out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0)); + out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0)); + out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0)); + } + else { + out[i] = pixels[i]; + out[i + 1] = pixels[i + 1]; + out[i + 2] = pixels[i + 2]; + } + } + }; + return Extract; +}()); - /** - * WrapMode copied from baseTexture - * @member {number} - */ - this.wrapMode = 33071; +exports.Extract = Extract; - /** - * Type copied from baseTexture - * @member {number} - */ - this.type = 6408; - /** - * Type copied from baseTexture - * @member {number} - */ - this.internalFormat = 5121; -}; +},{"@pixi/core":8,"@pixi/math":20,"@pixi/utils":38}],11:[function(require,module,exports){ +/*! + * @pixi/filter-alpha - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/filter-alpha is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var core = require('@pixi/core'); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var fragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"; /** - * System plugin to the renderer to manage textures. + * Simplest filter - applies alpha. + * + * Use this instead of Container's alpha property to avoid visual layering of individual elements. + * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. + * If elements are not opaque, they will blend with each other anyway. + * + * Very handy if you want to use common features of all filters: + * + * 1. Assign a blendMode to this filter, blend all elements inside display object with background. + * + * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. * * @class - * @extends PIXI.System - * @memberof PIXI.systems + * @extends PIXI.Filter + * @memberof PIXI.filters */ -var TextureSystem = /*@__PURE__*/(function (System) { - function TextureSystem(renderer) - { - System.call(this, renderer); - - // TODO set to max textures... - /** - * Bound textures - * @member {PIXI.BaseTexture[]} - * @readonly - */ - this.boundTextures = []; +var AlphaFilter = /** @class */ (function (_super) { + __extends(AlphaFilter, _super); + /** + * @param {number} [alpha=1] - Amount of alpha from 0 to 1, where 0 is transparent + */ + function AlphaFilter(alpha) { + if (alpha === void 0) { alpha = 1.0; } + var _this = _super.call(this, core.defaultVertex, fragment, { uAlpha: 1 }) || this; + _this.alpha = alpha; + return _this; + } + Object.defineProperty(AlphaFilter.prototype, "alpha", { /** - * Current location + * Coefficient for alpha multiplication + * * @member {number} - * @readonly - */ - this.currentLocation = -1; - - /** - * List of managed textures - * @member {PIXI.BaseTexture[]} - * @readonly - */ - this.managedTextures = []; - - /** - * Did someone temper with textures state? We'll overwrite them when we need to unbind something. - * @member {boolean} - * @private + * @default 1 */ - this._unknownBoundTextures = false; + get: function () { + return this.uniforms.uAlpha; + }, + set: function (value) { + this.uniforms.uAlpha = value; + }, + enumerable: false, + configurable: true + }); + return AlphaFilter; +}(core.Filter)); - /** - * BaseTexture value that shows that we don't know what is bound - * @member {PIXI.BaseTexture} - * @readonly - */ - this.unknownTexture = new BaseTexture(); - } +exports.AlphaFilter = AlphaFilter; - if ( System ) TextureSystem.__proto__ = System; - TextureSystem.prototype = Object.create( System && System.prototype ); - TextureSystem.prototype.constructor = TextureSystem; - /** - * Sets up the renderer context and necessary buffers. - */ - TextureSystem.prototype.contextChange = function contextChange () - { - var gl = this.gl = this.renderer.gl; - - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - - this.webGLVersion = this.renderer.context.webGLVersion; - - var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - - this.boundTextures.length = maxTextures; - - for (var i = 0; i < maxTextures; i++) - { - this.boundTextures[i] = null; - } - - // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {}; +},{"@pixi/core":8}],12:[function(require,module,exports){ +/*! + * @pixi/filter-blur - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/filter-blur is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - var emptyTexture2D = new GLTexture(gl.createTexture()); +Object.defineProperty(exports, '__esModule', { value: true }); - gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); +var core = require('@pixi/core'); +var settings = require('@pixi/settings'); - this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D; - this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture()); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} - gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); +var vertTemplate = "\n attribute vec2 aVertexPosition;\n\n uniform mat3 projectionMatrix;\n\n uniform float strength;\n\n varying vec2 vBlurTexCoords[%size%];\n\n uniform vec4 inputSize;\n uniform vec4 outputFrame;\n\n vec4 filterVertexPosition( void )\n {\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n }\n\n vec2 filterTextureCoord( void )\n {\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n }\n\n void main(void)\n {\n gl_Position = filterVertexPosition();\n\n vec2 textureCoord = filterTextureCoord();\n %blur%\n }"; +function generateBlurVertSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + var vertSource = vertTemplate; + var blurLoop = ''; + var template; + if (x) { + template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } + else { + template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i.toString()); + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + ".0"); + blurLoop += blur; + blurLoop += '\n'; + } + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize.toString()); + return vertSource; +} - for (var i$1 = 0; i$1 < 6; i$1++) - { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i$1, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448], +}; +var fragTemplate = [ + 'varying vec2 vBlurTexCoords[%size%];', + 'uniform sampler2D uSampler;', + 'void main(void)', + '{', + ' gl_FragColor = vec4(0.0);', + ' %blur%', + '}' ].join('\n'); +function generateBlurFragSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + var fragSource = fragTemplate; + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value; + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i.toString()); + value = i; + if (i >= halfLength) { + value = kernelSize - i - 1; } + blur = blur.replace('%value%', kernel[value].toString()); + blurLoop += blur; + blurLoop += '\n'; + } + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize.toString()); + return fragSource; +} - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - - for (var i$2 = 0; i$2 < this.boundTextures.length; i$2++) - { - this.bind(null, i$2); - } - }; +/** + * Different types of environments for WebGL. + * + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ +var ENV; +(function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; +})(ENV || (ENV = {})); +/** + * Constant to identify the Renderer Type. + * + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE; +(function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; +})(RENDERER_TYPE || (RENDERER_TYPE = {})); +/** + * Bitwise OR of masks that indicate the buffers to be cleared. + * + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ +var BUFFER_BITS; +(function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; +})(BUFFER_BITS || (BUFFER_BITS = {})); +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + * @property {number} NORMAL_NPM + * @property {number} ADD_NPM + * @property {number} SCREEN_NPM + * @property {number} NONE + * @property {number} SRC_IN + * @property {number} SRC_OUT + * @property {number} SRC_ATOP + * @property {number} DST_OVER + * @property {number} DST_IN + * @property {number} DST_OUT + * @property {number} DST_ATOP + * @property {number} SUBTRACT + * @property {number} SRC_OVER + * @property {number} ERASE + * @property {number} XOR + */ +var BLEND_MODES; +(function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; +})(BLEND_MODES || (BLEND_MODES = {})); +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES; +(function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; +})(DRAW_MODES || (DRAW_MODES = {})); +/** + * Various GL texture/resources formats. + * + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} RGBA=6408 + * @property {number} RGB=6407 + * @property {number} ALPHA=6406 + * @property {number} LUMINANCE=6409 + * @property {number} LUMINANCE_ALPHA=6410 + * @property {number} DEPTH_COMPONENT=6402 + * @property {number} DEPTH_STENCIL=34041 + */ +var FORMATS; +(function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; +})(FORMATS || (FORMATS = {})); +/** + * Various GL target types. + * + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} TEXTURE_2D=3553 + * @property {number} TEXTURE_CUBE_MAP=34067 + * @property {number} TEXTURE_2D_ARRAY=35866 + * @property {number} TEXTURE_CUBE_MAP_POSITIVE_X=34069 + * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_X=34070 + * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Y=34071 + * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Y=34072 + * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Z=34073 + * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Z=34074 + */ +var TARGETS; +(function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; +})(TARGETS || (TARGETS = {})); +/** + * Various GL data format types. + * + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} UNSIGNED_BYTE=5121 + * @property {number} UNSIGNED_SHORT=5123 + * @property {number} UNSIGNED_SHORT_5_6_5=33635 + * @property {number} UNSIGNED_SHORT_4_4_4_4=32819 + * @property {number} UNSIGNED_SHORT_5_5_5_1=32820 + * @property {number} FLOAT=5126 + * @property {number} HALF_FLOAT=36193 + */ +var TYPES; +(function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; +})(TYPES || (TYPES = {})); +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES; +(function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; +})(SCALE_MODES || (SCALE_MODES = {})); +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES; +(function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; +})(WRAP_MODES || (WRAP_MODES = {})); +/** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + */ +var MIPMAP_MODES; +(function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; +})(MIPMAP_MODES || (MIPMAP_MODES = {})); +/** + * How to treat textures with premultiplied alpha + * + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ +var ALPHA_MODES; +(function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; +})(ALPHA_MODES || (ALPHA_MODES = {})); +/** + * How to clear renderTextures in filter + * + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Preserve the information in the texture, blend above + * @property {number} CLEAR - Must use `gl.clear` operation + * @property {number} BLIT - Clear or blit it, depends on device and level of paranoia + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ +var CLEAR_MODES; +(function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; +})(CLEAR_MODES || (CLEAR_MODES = {})); +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES; +(function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; +})(GC_MODES || (GC_MODES = {})); +/** + * Constants that specify float precision in shaders. + * + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION; +(function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; +})(PRECISION || (PRECISION = {})); +/** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + */ +var MASK_TYPES; +(function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; +})(MASK_TYPES || (MASK_TYPES = {})); +/** + * Constants for multi-sampling antialiasing. + * + * @see PIXI.Framebuffer#multisample + * + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ +var MSAA_QUALITY; +(function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; +})(MSAA_QUALITY || (MSAA_QUALITY = {})); +/** + * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilterPass = /** @class */ (function (_super) { + __extends(BlurFilterPass, _super); /** - * Bind a texture to a specific location - * - * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)` - * - * @param {PIXI.Texture|PIXI.BaseTexture} texture - Texture to bind - * @param {number} [location=0] - Location to bind at + * @param {boolean} horizontal - Do pass along the x-axis (`true`) or y-axis (`false`). + * @param {number} [strength=8] - The strength of the blur filter. + * @param {number} [quality=4] - The quality of the blur filter. + * @param {number} [resolution=1] - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. */ - TextureSystem.prototype.bind = function bind (texture, location) - { - if ( location === void 0 ) location = 0; - - var ref = this; - var gl = ref.gl; - - if (texture) - { - texture = texture.baseTexture || texture; - - if (texture.valid) - { - texture.touched = this.renderer.textureGC.count; - - var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); - - if (this.boundTextures[location] !== texture) - { - if (this.currentLocation !== location) - { - this.currentLocation = location; - gl.activeTexture(gl.TEXTURE0 + location); - } - gl.bindTexture(texture.target, glTexture.texture); - } - - if (glTexture.dirtyId !== texture.dirtyId) - { - if (this.currentLocation !== location) - { - this.currentLocation = location; - gl.activeTexture(gl.TEXTURE0 + location); - } - this.updateTexture(texture); - } - - this.boundTextures[location] = texture; - } - } - else - { - if (this.currentLocation !== location) - { - this.currentLocation = location; - gl.activeTexture(gl.TEXTURE0 + location); - } - - gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture); - this.boundTextures[location] = null; - } - }; - + function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) { + if (strength === void 0) { strength = 8; } + if (quality === void 0) { quality = 4; } + if (resolution === void 0) { resolution = settings.settings.RESOLUTION; } + if (kernelSize === void 0) { kernelSize = 5; } + var _this = this; + var vertSrc = generateBlurVertSource(kernelSize, horizontal); + var fragSrc = generateBlurFragSource(kernelSize); + _this = _super.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc) || this; + _this.horizontal = horizontal; + _this.resolution = resolution; + _this._quality = 0; + _this.quality = quality; + _this.blur = strength; + return _this; + } /** - * Resets texture location and bound textures + * Applies the filter. * - * Actual `bind(null, i)` calls will be performed at next `unbind()` call + * @param {PIXI.systems.FilterSystem} filterManager - The manager. + * @param {PIXI.RenderTexture} input - The input target. + * @param {PIXI.RenderTexture} output - The output target. + * @param {PIXI.CLEAR_MODES} clearMode - How to clear */ - TextureSystem.prototype.reset = function reset () - { - this._unknownBoundTextures = true; - this.currentLocation = -1; - - for (var i = 0; i < this.boundTextures.length; i++) - { - this.boundTextures[i] = this.unknownTexture; + BlurFilterPass.prototype.apply = function (filterManager, input, output, clearMode) { + if (output) { + if (this.horizontal) { + this.uniforms.strength = (1 / output.width) * (output.width / input.width); + } + else { + this.uniforms.strength = (1 / output.height) * (output.height / input.height); + } } - }; - - /** - * Unbind a texture - * @param {PIXI.Texture|PIXI.BaseTexture} texture - Texture to bind - */ - TextureSystem.prototype.unbind = function unbind (texture) - { - var ref = this; - var gl = ref.gl; - var boundTextures = ref.boundTextures; - - if (this._unknownBoundTextures) - { - this._unknownBoundTextures = false; - // someone changed webGL state, - // we have to be sure that our texture does not appear in multi-texture renderer samplers - for (var i = 0; i < boundTextures.length; i++) - { - if (boundTextures[i] === this.unknownTexture) - { - this.bind(null, i); - } + else { + if (this.horizontal) // eslint-disable-line + { + this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width); + } + else { + this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line } } - - for (var i$1 = 0; i$1 < boundTextures.length; i$1++) - { - if (boundTextures[i$1] === texture) - { - if (this.currentLocation !== i$1) - { - gl.activeTexture(gl.TEXTURE0 + i$1); - this.currentLocation = i$1; - } - - gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[texture.target].texture); - boundTextures[i$1] = null; + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clearMode); + } + else { + var renderTarget = filterManager.getFilterTexture(); + var renderer = filterManager.renderer; + var flip = input; + var flop = renderTarget; + this.state.blend = false; + filterManager.applyFilter(this, flip, flop, CLEAR_MODES.CLEAR); + for (var i = 1; i < this.passes - 1; i++) { + filterManager.bindAndClear(flip, CLEAR_MODES.BLIT); + this.uniforms.uSampler = flop; + var temp = flop; + flop = flip; + flip = temp; + renderer.shader.bind(this); + renderer.geometry.draw(5); } + this.state.blend = true; + filterManager.applyFilter(this, flop, output, clearMode); + filterManager.returnFilterTexture(renderTarget); } }; + Object.defineProperty(BlurFilterPass.prototype, "blur", { + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + get: function () { + return this.strength; + }, + set: function (value) { + this.padding = 1 + (Math.abs(value) * 2); + this.strength = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilterPass.prototype, "quality", { + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + get: function () { + return this._quality; + }, + set: function (value) { + this._quality = value; + this.passes = value; + }, + enumerable: false, + configurable: true + }); + return BlurFilterPass; +}(core.Filter)); +/** + * The BlurFilter applies a Gaussian blur to an object. + * + * The strength of the blur can be set for the x-axis and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = /** @class */ (function (_super) { + __extends(BlurFilter, _super); + /** + * @param {number} [strength=8] - The strength of the blur filter. + * @param {number} [quality=4] - The quality of the blur filter. + * @param {number} [resolution=1] - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + if (strength === void 0) { strength = 8; } + if (quality === void 0) { quality = 4; } + if (resolution === void 0) { resolution = settings.settings.RESOLUTION; } + if (kernelSize === void 0) { kernelSize = 5; } + var _this = _super.call(this) || this; + _this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize); + _this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize); + _this.resolution = resolution; + _this.quality = quality; + _this.blur = strength; + _this.repeatEdgePixels = false; + return _this; + } /** - * Initialize a texture + * Applies the filter. * - * @private - * @param {PIXI.BaseTexture} texture - Texture to initialize + * @param {PIXI.systems.FilterSystem} filterManager - The manager. + * @param {PIXI.RenderTexture} input - The input target. + * @param {PIXI.RenderTexture} output - The output target. + * @param {PIXI.CLEAR_MODES} clearMode - How to clear */ - TextureSystem.prototype.initTexture = function initTexture (texture) - { - var glTexture = new GLTexture(this.gl.createTexture()); - - // guarantee an update.. - glTexture.dirtyId = -1; - - texture._glTextures[this.CONTEXT_UID] = glTexture; - - this.managedTextures.push(texture); - texture.on('dispose', this.destroyTexture, this); - - return glTexture; - }; - - TextureSystem.prototype.initTextureType = function initTextureType (texture, glTexture) - { - glTexture.internalFormat = texture.format; - glTexture.type = texture.type; - if (this.webGLVersion !== 2) - { - return; - } - var gl = this.renderer.gl; - - if (texture.type === gl.FLOAT - && texture.format === gl.RGBA) - { - glTexture.internalFormat = gl.RGBA32F; + BlurFilter.prototype.apply = function (filterManager, input, output, clearMode) { + var xStrength = Math.abs(this.blurXFilter.strength); + var yStrength = Math.abs(this.blurYFilter.strength); + if (xStrength && yStrength) { + var renderTarget = filterManager.getFilterTexture(); + this.blurXFilter.apply(filterManager, input, renderTarget, CLEAR_MODES.CLEAR); + this.blurYFilter.apply(filterManager, renderTarget, output, clearMode); + filterManager.returnFilterTexture(renderTarget); } - // that's WebGL1 HALF_FLOAT_OES - // we have to convert it to WebGL HALF_FLOAT - if (texture.type === constants.TYPES.HALF_FLOAT) - { - glTexture.type = gl.HALF_FLOAT; + else if (yStrength) { + this.blurYFilter.apply(filterManager, input, output, clearMode); } - if (glTexture.type === gl.HALF_FLOAT - && texture.format === gl.RGBA) - { - glTexture.internalFormat = gl.RGBA16F; + else { + this.blurXFilter.apply(filterManager, input, output, clearMode); } }; - - /** - * Update a texture - * - * @private - * @param {PIXI.BaseTexture} texture - Texture to initialize - */ - TextureSystem.prototype.updateTexture = function updateTexture (texture) - { - var glTexture = texture._glTextures[this.CONTEXT_UID]; - - if (!glTexture) - { - return; + BlurFilter.prototype.updatePadding = function () { + if (this._repeatEdgePixels) { + this.padding = 0; } - - var renderer = this.renderer; - - this.initTextureType(texture, glTexture); - - if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) - ; - else - { - // default, renderTexture-like logic - var width = texture.realWidth; - var height = texture.realHeight; - var gl = renderer.gl; - - if (glTexture.width !== width - || glTexture.height !== height - || glTexture.dirtyId < 0) - { - glTexture.width = width; - glTexture.height = height; - - gl.texImage2D(texture.target, 0, - glTexture.internalFormat, - width, - height, - 0, - texture.format, - glTexture.type, - null); - } - } - - // lets only update what changes.. - if (texture.dirtyStyleId !== glTexture.dirtyStyleId) - { - this.updateTextureStyle(texture); - } - glTexture.dirtyId = texture.dirtyId; - }; - - /** - * Deletes the texture from WebGL - * - * @private - * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy - * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. - */ - TextureSystem.prototype.destroyTexture = function destroyTexture (texture, skipRemove) - { - var ref = this; - var gl = ref.gl; - - texture = texture.baseTexture || texture; - - if (texture._glTextures[this.CONTEXT_UID]) - { - this.unbind(texture); - - gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture); - texture.off('dispose', this.destroyTexture, this); - - delete texture._glTextures[this.CONTEXT_UID]; - - if (!skipRemove) - { - var i = this.managedTextures.indexOf(texture); - - if (i !== -1) - { - utils.removeItems(this.managedTextures, i, 1); - } - } - } - }; - - /** - * Update texture style such as mipmap flag - * - * @private - * @param {PIXI.BaseTexture} texture - Texture to update - */ - TextureSystem.prototype.updateTextureStyle = function updateTextureStyle (texture) - { - var glTexture = texture._glTextures[this.CONTEXT_UID]; - - if (!glTexture) - { - return; - } - - if ((texture.mipmap === constants.MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) - { - glTexture.mipmap = 0; - } - else - { - glTexture.mipmap = texture.mipmap >= 1; - } - - if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) - { - glTexture.wrapMode = constants.WRAP_MODES.CLAMP; - } - else - { - glTexture.wrapMode = texture.wrapMode; - } - - if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) - ; - else - { - this.setStyle(texture, glTexture); - } - - glTexture.dirtyStyleId = texture.dirtyStyleId; - }; - - /** - * Set style for texture - * - * @private - * @param {PIXI.BaseTexture} texture - Texture to update - * @param {PIXI.GLTexture} glTexture - */ - TextureSystem.prototype.setStyle = function setStyle (texture, glTexture) - { - var gl = this.gl; - - if (glTexture.mipmap) - { - gl.generateMipmap(texture.target); - } - - gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode); - gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode); - - if (glTexture.mipmap) - { - /* eslint-disable max-len */ - gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - /* eslint-disable max-len */ - - var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering; - - if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === constants.SCALE_MODES.LINEAR) - { - var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT)); - - gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level); - } - } - else - { - gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); + else { + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; } - - gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); }; - - return TextureSystem; -}(System)); - -/** - * Systems are individual components to the Renderer pipeline. - * @namespace PIXI.systems - */ - -var systems = ({ - FilterSystem: FilterSystem, - BatchSystem: BatchSystem, - ContextSystem: ContextSystem, - FramebufferSystem: FramebufferSystem, - GeometrySystem: GeometrySystem, - MaskSystem: MaskSystem, - ScissorSystem: ScissorSystem, - StencilSystem: StencilSystem, - ProjectionSystem: ProjectionSystem, - RenderTextureSystem: RenderTextureSystem, - ShaderSystem: ShaderSystem, - StateSystem: StateSystem, - TextureGCSystem: TextureGCSystem, - TextureSystem: TextureSystem -}); - -var tempMatrix = new math.Matrix(); - -/** - * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} - * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene. - * - * @abstract - * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI - */ -var AbstractRenderer = /*@__PURE__*/(function (EventEmitter) { - function AbstractRenderer(system, options) - { - EventEmitter.call(this); - - // Add the default render options - options = Object.assign({}, settings.settings.RENDER_OPTIONS, options); - - // Deprecation notice for renderer roundPixels option - if (options.roundPixels) - { - settings.settings.ROUND_PIXELS = options.roundPixels; - utils.deprecation('5.0.0', 'Renderer roundPixels option is deprecated, please use PIXI.settings.ROUND_PIXELS', 2); - } - + Object.defineProperty(BlurFilter.prototype, "blur", { /** - * The supplied constructor options. - * - * @member {Object} - * @readOnly - */ - this.options = options; - - /** - * The type of the renderer. + * Sets the strength of both the blurX and blurY properties simultaneously * * @member {number} - * @default PIXI.RENDERER_TYPE.UNKNOWN - * @see PIXI.RENDERER_TYPE - */ - this.type = constants.RENDERER_TYPE.UNKNOWN; - - /** - * Measurements of the screen. (0, 0, screenWidth, screenHeight). - * - * Its safe to use as filterArea or hitArea for the whole stage. - * - * @member {PIXI.Rectangle} - */ - this.screen = new math.Rectangle(0, 0, options.width, options.height); - - /** - * The canvas element that everything is drawn to. - * - * @member {HTMLCanvasElement} + * @default 2 */ - this.view = options.view || document.createElement('canvas'); - + get: function () { + return this.blurXFilter.blur; + }, + set: function (value) { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "quality", { /** - * The resolution / device pixel ratio of the renderer. + * Sets the number of passes for blur. More passes means higher quaility bluring. * * @member {number} * @default 1 */ - this.resolution = options.resolution || settings.settings.RESOLUTION; - - /** - * Whether the render view is transparent. - * - * @member {boolean} - */ - this.transparent = options.transparent; - - /** - * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically. - * - * @member {boolean} - */ - this.autoDensity = options.autoDensity || options.autoResize || false; - // autoResize is deprecated, provides fallback support - + get: function () { + return this.blurXFilter.quality; + }, + set: function (value) { + this.blurXFilter.quality = this.blurYFilter.quality = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blurX", { /** - * The value of the preserveDrawingBuffer flag affects whether or not the contents of - * the stencil buffer is retained after rendering. + * Sets the strength of the blurX property * - * @member {boolean} + * @member {number} + * @default 2 */ - this.preserveDrawingBuffer = options.preserveDrawingBuffer; - + get: function () { + return this.blurXFilter.blur; + }, + set: function (value) { + this.blurXFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blurY", { /** - * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. - * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every - * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect - * to clear the canvas every frame. Disable this by setting this to false. For example, if - * your game has a canvas filling background image you often don't need this set. + * Sets the strength of the blurY property * - * @member {boolean} - * @default + * @member {number} + * @default 2 */ - this.clearBeforeRender = options.clearBeforeRender; - + get: function () { + return this.blurYFilter.blur; + }, + set: function (value) { + this.blurYFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blendMode", { /** - * The background color as a number. + * Sets the blendmode of the filter * * @member {number} - * @protected + * @default PIXI.BLEND_MODES.NORMAL */ - this._backgroundColor = 0x000000; - + get: function () { + return this.blurYFilter.blendMode; + }, + set: function (value) { + this.blurYFilter.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "repeatEdgePixels", { /** - * The background color as an [R, G, B] array. + * If set to true the edge of the target will be clamped * - * @member {number[]} - * @protected + * @member {boolean} + * @default false */ - this._backgroundColorRgba = [0, 0, 0, 0]; + get: function () { + return this._repeatEdgePixels; + }, + set: function (value) { + this._repeatEdgePixels = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + return BlurFilter; +}(core.Filter)); - /** - * The background color as a string. - * - * @member {string} - * @protected - */ - this._backgroundColorString = '#000000'; +exports.BlurFilter = BlurFilter; +exports.BlurFilterPass = BlurFilterPass; - this.backgroundColor = options.backgroundColor || this._backgroundColor; // run bg color setter - /** - * This temporary display object used as the parent of the currently being rendered item. - * - * @member {PIXI.DisplayObject} - * @protected - */ - this._tempDisplayObjectParent = new display.Container(); +},{"@pixi/core":8,"@pixi/settings":30}],13:[function(require,module,exports){ +/*! + * @pixi/filter-color-matrix - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/filter-color-matrix is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - /** - * The last root object that the renderer tried to render. - * - * @member {PIXI.DisplayObject} - * @protected - */ - this._lastObjectRendered = this._tempDisplayObjectParent; +Object.defineProperty(exports, '__esModule', { value: true }); - /** - * Collection of plugins. - * @readonly - * @member {object} - */ - this.plugins = {}; - } +var core = require('@pixi/core'); - if ( EventEmitter ) AbstractRenderer.__proto__ = EventEmitter; - AbstractRenderer.prototype = Object.create( EventEmitter && EventEmitter.prototype ); - AbstractRenderer.prototype.constructor = AbstractRenderer; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} - var prototypeAccessors = { width: { configurable: true },height: { configurable: true },backgroundColor: { configurable: true } }; +var fragment = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"; +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = /** @class */ (function (_super) { + __extends(ColorMatrixFilter, _super); + function ColorMatrixFilter() { + var _this = this; + var uniforms = { + m: new Float32Array([1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0]), + uAlpha: 1, + }; + _this = _super.call(this, core.defaultFilterVertex, fragment, uniforms) || this; + _this.alpha = 1; + return _this; + } /** - * Initialize the plugins. + * Transforms current matrix and set the new one * - * @protected - * @param {object} staticMap - The dictionary of statically saved plugins. + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - AbstractRenderer.prototype.initPlugins = function initPlugins (staticMap) - { - for (var o in staticMap) - { - this.plugins[o] = new (staticMap[o])(this); + ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) { + if (multiply === void 0) { multiply = false; } + var newMatrix = matrix; + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); } + // set the new matrix + this.uniforms.m = newMatrix; }; - /** - * Same as view.width, actual number of pixels in the canvas by horizontal. + * Multiplies two mat5's * - * @member {number} - * @readonly - * @default 800 + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix */ - prototypeAccessors.width.get = function () - { - return this.view.width; + ColorMatrixFilter.prototype._multiply = function (out, a, b) { + // Red Channel + out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); + out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); + out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); + out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); + out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4]; + // Green Channel + out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); + out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); + out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); + out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); + out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9]; + // Blue Channel + out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); + out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); + out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); + out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); + out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14]; + // Alpha Channel + out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); + out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); + out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); + out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); + out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19]; + return out; }; - /** - * Same as view.height, actual number of pixels in the canvas by vertical. + * Create a Float32 Array and normalize the offset component to 0-1 * - * @member {number} - * @readonly - * @default 600 + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 */ - prototypeAccessors.height.get = function () - { - return this.view.height; + ColorMatrixFilter.prototype._colorMatrix = function (matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + return m; }; - /** - * Resizes the screen and canvas to the specified width and height. - * Canvas dimensions are multiplied by resolution. + * Adjusts brightness * - * @param {number} screenWidth - The new width of the screen. - * @param {number} screenHeight - The new height of the screen. + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - AbstractRenderer.prototype.resize = function resize (screenWidth, screenHeight) - { - this.screen.width = screenWidth; - this.screen.height = screenHeight; - - this.view.width = screenWidth * this.resolution; - this.view.height = screenHeight * this.resolution; - - if (this.autoDensity) - { - this.view.style.width = screenWidth + "px"; - this.view.style.height = screenHeight + "px"; - } + ColorMatrixFilter.prototype.brightness = function (b, multiply) { + var matrix = [ + b, 0, 0, 0, 0, + 0, b, 0, 0, 0, + 0, 0, b, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - /** - * Useful function that returns a texture of the display object that can then be used to create sprites - * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * Set the matrices in grey scales * - * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from. - * @param {number} scaleMode - Should be one of the scaleMode consts. - * @param {number} resolution - The resolution / device pixel ratio of the texture being generated. - * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered, - * if no region is specified, defaults to the local bounds of the displayObject. - * @return {PIXI.RenderTexture} A texture of the graphics object. + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - AbstractRenderer.prototype.generateTexture = function generateTexture (displayObject, scaleMode, resolution, region) - { - region = region || displayObject.getLocalBounds(); - - // minimum texture size is 1x1, 0x0 will throw an error - if (region.width === 0) { region.width = 1; } - if (region.height === 0) { region.height = 1; } - - var renderTexture = RenderTexture.create(region.width | 0, region.height | 0, scaleMode, resolution); - - tempMatrix.tx = -region.x; - tempMatrix.ty = -region.y; - - this.render(displayObject, renderTexture, false, tempMatrix, !!displayObject.parent); - - return renderTexture; + ColorMatrixFilter.prototype.greyscale = function (scale, multiply) { + var matrix = [ + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - /** - * Removes everything from the renderer and optionally removes the Canvas DOM element. + * Set the black and white matrice. * - * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - AbstractRenderer.prototype.destroy = function destroy (removeView) - { - for (var o in this.plugins) - { - this.plugins[o].destroy(); - this.plugins[o] = null; - } - - if (removeView && this.view.parentNode) - { - this.view.parentNode.removeChild(this.view); - } - - this.plugins = null; - - this.type = constants.RENDERER_TYPE.UNKNOWN; - - this.view = null; - - this.screen = null; - - this.resolution = 0; - - this.transparent = false; - - this.autoDensity = false; - - this.blendModes = null; - - this.options = null; - - this.preserveDrawingBuffer = false; - this.clearBeforeRender = false; - - this._backgroundColor = 0; - this._backgroundColorRgba = null; - this._backgroundColorString = null; - - this._tempDisplayObjectParent = null; - this._lastObjectRendered = null; + ColorMatrixFilter.prototype.blackAndWhite = function (multiply) { + var matrix = [ + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - /** - * The background color to fill if not transparent + * Set the hue property of the color * - * @member {number} + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - prototypeAccessors.backgroundColor.get = function () - { - return this._backgroundColor; - }; - - prototypeAccessors.backgroundColor.set = function (value) // eslint-disable-line require-jsdoc - { - this._backgroundColor = value; - this._backgroundColorString = utils.hex2string(value); - utils.hex2rgb(value, this._backgroundColorRgba); - }; - - Object.defineProperties( AbstractRenderer.prototype, prototypeAccessors ); + ColorMatrixFilter.prototype.hue = function (rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php - return AbstractRenderer; -}(utils.EventEmitter)); + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js -/** - * The Renderer draws the scene and all its content onto a WebGL enabled canvas. - * - * This renderer should be used for browsers that support WebGL. - * - * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds. - * Don't forget to add the view to your DOM or you will not see anything! - * - * @class - * @memberof PIXI - * @extends PIXI.AbstractRenderer - */ -var Renderer = /*@__PURE__*/(function (AbstractRenderer) { - function Renderer(options) - { - if ( options === void 0 ) options = {}; - - AbstractRenderer.call(this, 'WebGL', options); - - // the options will have been modified here in the super constructor with pixi's default settings.. - options = this.options; - - /** - * The type of this renderer as a standardized const - * - * @member {number} - * @see PIXI.RENDERER_TYPE - */ - this.type = constants.RENDERER_TYPE.WEBGL; - - /** - * WebGL context, set by the contextSystem (this.context) - * - * @readonly - * @member {WebGLRenderingContext} - */ - this.gl = null; - - this.CONTEXT_UID = 0; - - // TODO legacy! - - /** - * Internal signal instances of **runner**, these - * are assigned to each system created. - * @see PIXI.Runner - * @name PIXI.Renderer#runners - * @private - * @type {object} - * @readonly - * @property {PIXI.Runner} destroy - Destroy runner - * @property {PIXI.Runner} contextChange - Context change runner - * @property {PIXI.Runner} reset - Reset runner - * @property {PIXI.Runner} update - Update runner - * @property {PIXI.Runner} postrender - Post-render runner - * @property {PIXI.Runner} prerender - Pre-render runner - * @property {PIXI.Runner} resize - Resize runner - */ - this.runners = { - destroy: new runner.Runner('destroy'), - contextChange: new runner.Runner('contextChange', 1), - reset: new runner.Runner('reset'), - update: new runner.Runner('update'), - postrender: new runner.Runner('postrender'), - prerender: new runner.Runner('prerender'), - resize: new runner.Runner('resize', 2), - }; - - /** - * Global uniforms - * @member {PIXI.UniformGroup} - */ - this.globalUniforms = new UniformGroup({ - projectionMatrix: new math.Matrix(), - }, true); - - /** - * Mask system instance - * @member {PIXI.systems.MaskSystem} mask - * @memberof PIXI.Renderer# - * @readonly - */ - this.addSystem(MaskSystem, 'mask') - /** - * Context system instance - * @member {PIXI.systems.ContextSystem} context - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(ContextSystem, 'context') - /** - * State system instance - * @member {PIXI.systems.StateSystem} state - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(StateSystem, 'state') - /** - * Shader system instance - * @member {PIXI.systems.ShaderSystem} shader - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(ShaderSystem, 'shader') - /** - * Texture system instance - * @member {PIXI.systems.TextureSystem} texture - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(TextureSystem, 'texture') - /** - * Geometry system instance - * @member {PIXI.systems.GeometrySystem} geometry - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(GeometrySystem, 'geometry') - /** - * Framebuffer system instance - * @member {PIXI.systems.FramebufferSystem} framebuffer - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(FramebufferSystem, 'framebuffer') - /** - * Scissor system instance - * @member {PIXI.systems.ScissorSystem} scissor - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(ScissorSystem, 'scissor') - /** - * Stencil system instance - * @member {PIXI.systems.StencilSystem} stencil - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(StencilSystem, 'stencil') - /** - * Projection system instance - * @member {PIXI.systems.ProjectionSystem} projection - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(ProjectionSystem, 'projection') - /** - * Texture garbage collector system instance - * @member {PIXI.systems.TextureGCSystem} textureGC - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(TextureGCSystem, 'textureGC') - /** - * Filter system instance - * @member {PIXI.systems.FilterSystem} filter - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(FilterSystem, 'filter') - /** - * RenderTexture system instance - * @member {PIXI.systems.RenderTextureSystem} renderTexture - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(RenderTextureSystem, 'renderTexture') - - /** - * Batch system instance - * @member {PIXI.systems.BatchSystem} batch - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(BatchSystem, 'batch'); - - this.initPlugins(Renderer.__plugins); - - /** - * The options passed in to create a new WebGL context. - */ - if (options.context) - { - this.context.initFromContext(options.context); - } - else - { - this.context.initFromOptions({ - alpha: this.transparent, - antialias: options.antialias, - premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', - stencil: true, - preserveDrawingBuffer: options.preserveDrawingBuffer, - powerPreference: this.options.powerPreference, - }); - } - - /** - * Flag if we are rendering to the screen vs renderTexture - * @member {boolean} - * @readonly - * @default true + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 */ - this.renderingToScreen = true; - - utils.sayHello(this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1'); - - this.resize(this.options.width, this.options.height); - } - - if ( AbstractRenderer ) Renderer.__proto__ = AbstractRenderer; - Renderer.prototype = Object.create( AbstractRenderer && AbstractRenderer.prototype ); - Renderer.prototype.constructor = Renderer; - + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + var a00 = cosR + ((1.0 - cosR) * w); + var a01 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a02 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a10 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a11 = cosR + (w * (1.0 - cosR)); + var a12 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a20 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a21 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a22 = cosR + (w * (1.0 - cosR)); + var matrix = [ + a00, a01, a02, 0, 0, + a10, a11, a12, 0, 0, + a20, a21, a22, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; /** - * Add a new system to the renderer. - * @param {Function} ClassRef - Class reference - * @param {string} [name] - Property name for system, if not specified - * will use a static `name` property on the class itself. This - * name will be assigned as s property on the Renderer so make - * sure it doesn't collide with properties on Renderer. - * @return {PIXI.Renderer} Return instance of renderer + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - Renderer.create = function create (options) - { - if (utils.isWebGLSupported()) - { - return new Renderer(options); - } - - throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.'); - }; - - Renderer.prototype.addSystem = function addSystem (ClassRef, name) - { - if (!name) - { - name = ClassRef.name; - } - - var system = new ClassRef(this); - - if (this[name]) - { - throw new Error(("Whoops! The name \"" + name + "\" is already in use")); - } - - this[name] = system; - - for (var i in this.runners) - { - this.runners[i].add(system); - } - - /** - * Fired after rendering finishes. - * - * @event PIXI.Renderer#postrender - */ - - /** - * Fired before rendering starts. - * - * @event PIXI.Renderer#prerender - */ - - /** - * Fired when the WebGL context is set. - * - * @event PIXI.Renderer#context - * @param {WebGLRenderingContext} gl - WebGL context. - */ - - return this; + ColorMatrixFilter.prototype.contrast = function (amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + var matrix = [ + v, 0, 0, 0, o, + 0, v, 0, 0, o, + 0, 0, v, 0, o, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - /** - * Renders the object to its WebGL view + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness * - * @param {PIXI.DisplayObject} displayObject - The object to be rendered. - * @param {PIXI.RenderTexture} [renderTexture] - The render texture to render to. - * @param {boolean} [clear=true] - Should the canvas be cleared before the new render. - * @param {PIXI.Matrix} [transform] - A transform to apply to the render texture before rendering. - * @param {boolean} [skipUpdateTransform=false] - Should we skip the update transform pass? + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} [multiply] - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - Renderer.prototype.render = function render (displayObject, renderTexture, clear, transform, skipUpdateTransform) - { - // can be handy to know! - this.renderingToScreen = !renderTexture; - - this.runners.prerender.run(); - this.emit('prerender'); - - // apply a transform at a GPU level - this.projection.transform = transform; - - // no point rendering if our context has been blown up! - if (this.context.isLost) - { - return; - } - - if (!renderTexture) - { - this._lastObjectRendered = displayObject; - } - - if (!skipUpdateTransform) - { - // update the scene graph - var cacheParent = displayObject.parent; - - displayObject.parent = this._tempDisplayObjectParent; - displayObject.updateTransform(); - displayObject.parent = cacheParent; - // displayObject.hitArea = //TODO add a temp hit area - } - - this.renderTexture.bind(renderTexture); - this.batch.currentRenderer.start(); - - if (clear !== undefined ? clear : this.clearBeforeRender) - { - this.renderTexture.clear(); - } - - displayObject.render(this); - - // apply transform.. - this.batch.currentRenderer.flush(); - - if (renderTexture) - { - renderTexture.baseTexture.update(); - } - - this.runners.postrender.run(); - - // reset transform after render - this.projection.transform = null; - - this.emit('postrender'); + ColorMatrixFilter.prototype.saturate = function (amount, multiply) { + if (amount === void 0) { amount = 0; } + var x = (amount * 2 / 3) + 1; + var y = ((x - 1) * -0.5); + var matrix = [ + x, y, y, 0, 0, + y, x, y, 0, 0, + y, y, x, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - /** - * Resizes the WebGL view to the specified width and height. + * Desaturate image (remove color) + * + * Call the saturate function * - * @param {number} screenWidth - The new width of the screen. - * @param {number} screenHeight - The new height of the screen. */ - Renderer.prototype.resize = function resize (screenWidth, screenHeight) - { - AbstractRenderer.prototype.resize.call(this, screenWidth, screenHeight); - - this.runners.resize.run(screenWidth, screenHeight); + ColorMatrixFilter.prototype.desaturate = function () { + this.saturate(-1); }; - /** - * Resets the WebGL state so you can render things however you fancy! + * Negative image (inverse of classic rgb matrix) * - * @return {PIXI.Renderer} Returns itself. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - Renderer.prototype.reset = function reset () - { - this.runners.reset.run(); - - return this; + ColorMatrixFilter.prototype.negative = function (multiply) { + var matrix = [ + -1, 0, 0, 1, 0, + 0, -1, 0, 1, 0, + 0, 0, -1, 1, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - /** - * Clear the frame buffer + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - Renderer.prototype.clear = function clear () - { - this.framebuffer.bind(); - this.framebuffer.clear(); + ColorMatrixFilter.prototype.sepia = function (multiply) { + var matrix = [ + 0.393, 0.7689999, 0.18899999, 0, 0, + 0.349, 0.6859999, 0.16799999, 0, 0, + 0.272, 0.5339999, 0.13099999, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - /** - * Removes everything from the renderer (event listeners, spritebatch, etc...) + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) * - * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. - * See: https://github.com/pixijs/pixi.js/issues/2233 + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - Renderer.prototype.destroy = function destroy (removeView) - { - this.runners.destroy.run(); - - for (var r in this.runners) - { - this.runners[r].destroy(); - } - - // call base destroy - AbstractRenderer.prototype.destroy.call(this, removeView); - - // TODO nullify all the managers.. - this.gl = null; + ColorMatrixFilter.prototype.technicolor = function (multiply) { + var matrix = [ + 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, + -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, + -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - /** - * Collection of installed plugins. These are included by default in PIXI, but can be excluded - * by creating a custom build. Consult the README for more information about creating custom - * builds and excluding plugins. - * @name PIXI.Renderer#plugins - * @type {object} - * @readonly - * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. - * @property {PIXI.extract.Extract} extract Extract image data from renderer. - * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. - * @property {PIXI.prepare.Prepare} prepare Pre-render display objects. + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - + ColorMatrixFilter.prototype.polaroid = function (multiply) { + var matrix = [ + 1.438, -0.062, -0.062, 0, 0, + -0.122, 1.378, -0.122, 0, 0, + -0.016, -0.016, 1.483, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; /** - * Adds a plugin to the renderer. + * Filter who transforms : Red -> Blue and Blue -> Red * - * @method - * @param {string} pluginName - The name of the plugin. - * @param {Function} ctor - The constructor function or class for the plugin. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - Renderer.registerPlugin = function registerPlugin (pluginName, ctor) - { - Renderer.__plugins = Renderer.__plugins || {}; - Renderer.__plugins[pluginName] = ctor; + ColorMatrixFilter.prototype.toBGR = function (multiply) { + var matrix = [ + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - - return Renderer; -}(AbstractRenderer)); - -/** - * This helper function will automatically detect which renderer you should be using. - * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by - * the browser then this function will return a canvas renderer - * - * @memberof PIXI - * @function autoDetectRenderer - * @param {object} [options] - The optional renderer parameters - * @param {number} [options.width=800] - the width of the renderers view - * @param {number} [options.height=600] - the height of the renderers view - * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional - * @param {boolean} [options.transparent=false] - If the render view is transparent, default false - * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for - * resolutions other than 1 - * @param {boolean} [options.antialias=false] - sets antialias - * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you - * need to call toDataUrl on the webgl context - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or - * not before the new render pass. - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 - * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this - * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise - * it is ignored. - * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. - * FXAA is faster, but may not always look as great **webgl only** - * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" - * for devices with dual graphics card **webgl only** - * @return {PIXI.Renderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer - */ -function autoDetectRenderer(options) -{ - return Renderer.create(options); -} - -var _default = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; - -var defaultFilter = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; - -/** - * A Texture that depends on six other resources. - * - * @class - * @extends PIXI.BaseTexture - * @memberof PIXI - */ -var CubeTexture = /*@__PURE__*/(function (BaseTexture) { - function CubeTexture () { - BaseTexture.apply(this, arguments); - } - - if ( BaseTexture ) CubeTexture.__proto__ = BaseTexture; - CubeTexture.prototype = Object.create( BaseTexture && BaseTexture.prototype ); - CubeTexture.prototype.constructor = CubeTexture; - - CubeTexture.from = function from (resources, options) - { - return new CubeTexture(new CubeResource(resources, options)); + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.kodachrome = function (multiply) { + var matrix = [ + 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, + -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, + -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); }; - - return CubeTexture; -}(BaseTexture)); - -/** - * Used by the batcher to draw batches. - * Each one of these contains all information required to draw a bound geometry. - * - * @class - * @memberof PIXI - */ -var BatchDrawCall = function BatchDrawCall() -{ - this.texArray = null; - this.blend = 0; - this.type = constants.DRAW_MODES.TRIANGLES; - - this.start = 0; - this.size = 0; - /** - * data for uniforms or custom webgl state - * @member {object} + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - this.data = null; -}; - -/** - * Used by the batcher to build texture batches. - * Holds list of textures and their respective locations. - * - * @class - * @memberof PIXI - */ -var BatchTextureArray = function BatchTextureArray() -{ + ColorMatrixFilter.prototype.browni = function (multiply) { + var matrix = [ + 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, + -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, + 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; /** - * inside textures array - * @member {PIXI.BaseTexture[]} + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - this.elements = []; + ColorMatrixFilter.prototype.vintage = function (multiply) { + var matrix = [ + 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, + 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, + 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; /** - * Respective locations for textures - * @member {number[]} + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {number} lightColor - Tone values, example: `0xFFE580` + * @param {number} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - this.ids = []; + ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + var lR = ((lightColor >> 16) & 0xFF) / 255; + var lG = ((lightColor >> 8) & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + var dR = ((darkColor >> 16) & 0xFF) / 255; + var dG = ((darkColor >> 8) & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + var matrix = [ + 0.3, 0.59, 0.11, 0, 0, + lR, lG, lB, desaturation, 0, + dR, dG, dB, toned, 0, + lR - dR, lG - dG, lB - dB, 0, 0 ]; + this._loadMatrix(matrix, multiply); + }; /** - * number of filled elements - * @member {number} + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - this.count = 0; -}; - -BatchTextureArray.prototype.clear = function clear () -{ - for (var i = 0; i < this.count; i++) - { - this.elements[i] = null; - } - this.count = 0; -}; - -/** - * Flexible wrapper around `ArrayBuffer` that also provides - * typed array views on demand. - * - * @class - * @memberof PIXI - */ -var ViewableBuffer = function ViewableBuffer(size) -{ + ColorMatrixFilter.prototype.night = function (intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [ + intensity * (-2.0), -intensity, 0, 0, 0, + -intensity, 0, intensity, 0, 0, + 0, intensity, intensity * 2.0, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; /** - * Underlying `ArrayBuffer` that holds all the data - * and is of capacity `size`. + * Predator effect + * + * Erase the current matrix by setting a new indepent one * - * @member {ArrayBuffer} + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - this.rawBinaryData = new ArrayBuffer(size); - + ColorMatrixFilter.prototype.predator = function (amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, + -4.794486999511719 * amount, + -2.8746118545532227 * amount, + 0 * amount, + 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, + 9.193157196044922 * amount, + -2.951810836791992 * amount, + 0 * amount, + -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, + -4.2375030517578125 * amount, + 7.476448059082031 * amount, + 0 * amount, + 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; /** - * View on the raw binary data as a `Uint32Array`. + * LSD effect + * + * Multiply the current matrix * - * @member {Uint32Array} + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix */ - this.uint32View = new Uint32Array(this.rawBinaryData); - + ColorMatrixFilter.prototype.lsd = function (multiply) { + var matrix = [ + 2, -0.4, 0.5, 0, 0, + -0.5, 2, -0.4, 0, 0, + -0.4, -0.5, 3, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; /** - * View on the raw binary data as a `Float32Array`. + * Erase the current matrix by setting the default one * - * @member {Float32Array} */ - this.float32View = new Float32Array(this.rawBinaryData); -}; + ColorMatrixFilter.prototype.reset = function () { + var matrix = [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, false); + }; + Object.defineProperty(ColorMatrixFilter.prototype, "matrix", { + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + get: function () { + return this.uniforms.m; + }, + set: function (value) { + this.uniforms.m = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ColorMatrixFilter.prototype, "alpha", { + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * + * @member {number} + * @default 1 + */ + get: function () { + return this.uniforms.uAlpha; + }, + set: function (value) { + this.uniforms.uAlpha = value; + }, + enumerable: false, + configurable: true + }); + return ColorMatrixFilter; +}(core.Filter)); +// Americanized alias +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; -var prototypeAccessors$5 = { int8View: { configurable: true },uint8View: { configurable: true },int16View: { configurable: true },uint16View: { configurable: true },int32View: { configurable: true } }; +exports.ColorMatrixFilter = ColorMatrixFilter; -/** - * View on the raw binary data as a `Int8Array`. + +},{"@pixi/core":8}],14:[function(require,module,exports){ +/*! + * @pixi/filter-displacement - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @member {Int8Array} + * @pixi/filter-displacement is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license */ -prototypeAccessors$5.int8View.get = function () -{ - if (!this._int8View) - { - this._int8View = new Int8Array(this.rawBinaryData); - } +'use strict'; - return this._int8View; -}; +Object.defineProperty(exports, '__esModule', { value: true }); -/** - * View on the raw binary data as a `Uint8Array`. - * - * @member {Uint8Array} - */ -prototypeAccessors$5.uint8View.get = function () -{ - if (!this._uint8View) - { - this._uint8View = new Uint8Array(this.rawBinaryData); - } +var core = require('@pixi/core'); +var math = require('@pixi/math'); - return this._uint8View; -}; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var fragment = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n"; + +var vertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n"; /** - * View on the raw binary data as a `Int16Array`. + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. + * + * You can use this filter to apply all manor of crazy warping effects. + * Currently the `r` property of the texture is used to offset the `x` + * and the `g` property of the texture is used to offset the `y`. + * + * The way it works is it uses the values of the displacement map to look up the + * correct pixels to output. This means it's not technically moving the original. + * Instead, it's starting at the output and asking "which pixel from the original goes here". + * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`, + * this filter will output the pixel approximately 20 pixels to the right of the original. * - * @member {Int16Array} + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters */ -prototypeAccessors$5.int16View.get = function () -{ - if (!this._int16View) - { - this._int16View = new Int16Array(this.rawBinaryData); +var DisplacementFilter = /** @class */ (function (_super) { + __extends(DisplacementFilter, _super); + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} [scale] - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + var _this = this; + var maskMatrix = new math.Matrix(); + sprite.renderable = false; + _this = _super.call(this, vertex, fragment, { + mapSampler: sprite._texture, + filterMatrix: maskMatrix, + scale: { x: 1, y: 1 }, + rotation: new Float32Array([1, 0, 0, 1]), + }) || this; + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + if (scale === null || scale === undefined) { + scale = 20; + } + /** + * scaleX, scaleY for displacements + * @member {PIXI.Point} + */ + _this.scale = new math.Point(scale, scale); + return _this; } + /** + * Applies the filter. + * + * @param {PIXI.systems.FilterSystem} filterManager - The manager. + * @param {PIXI.RenderTexture} input - The input target. + * @param {PIXI.RenderTexture} output - The output target. + * @param {PIXI.CLEAR_MODES} clearMode - clearMode. + */ + DisplacementFilter.prototype.apply = function (filterManager, input, output, clearMode) { + // fill maskMatrix with _normalized sprite texture coords_ + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x; + this.uniforms.scale.y = this.scale.y; + // Extract rotation from world transform + var wt = this.maskSprite.worldTransform; + var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b)); + var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d)); + if (lenX !== 0 && lenY !== 0) { + this.uniforms.rotation[0] = wt.a / lenX; + this.uniforms.rotation[1] = wt.b / lenX; + this.uniforms.rotation[2] = wt.c / lenY; + this.uniforms.rotation[3] = wt.d / lenY; + } + // draw the filter... + filterManager.applyFilter(this, input, output, clearMode); + }; + Object.defineProperty(DisplacementFilter.prototype, "map", { + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + get: function () { + return this.uniforms.mapSampler; + }, + set: function (value) { + this.uniforms.mapSampler = value; + }, + enumerable: false, + configurable: true + }); + return DisplacementFilter; +}(core.Filter)); - return this._int16View; -}; +exports.DisplacementFilter = DisplacementFilter; -/** - * View on the raw binary data as a `Uint16Array`. + +},{"@pixi/core":8,"@pixi/math":20}],15:[function(require,module,exports){ +/*! + * @pixi/filter-fxaa - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @member {Uint16Array} + * @pixi/filter-fxaa is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license */ -prototypeAccessors$5.uint16View.get = function () -{ - if (!this._uint16View) - { - this._uint16View = new Uint16Array(this.rawBinaryData); - } +'use strict'; - return this._uint16View; -}; +Object.defineProperty(exports, '__esModule', { value: true }); + +var core = require('@pixi/core'); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var vertex = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputPixel;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"; + +var fragment = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputPixel;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n"; /** - * View on the raw binary data as a `Int32Array`. + * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com + * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters * - * @member {Int32Array} */ -prototypeAccessors$5.int32View.get = function () -{ - if (!this._int32View) - { - this._int32View = new Int32Array(this.rawBinaryData); +var FXAAFilter = /** @class */ (function (_super) { + __extends(FXAAFilter, _super); + function FXAAFilter() { + // TODO - needs work + return _super.call(this, vertex, fragment) || this; } + return FXAAFilter; +}(core.Filter)); - return this._int32View; -}; +exports.FXAAFilter = FXAAFilter; -/** - * Returns the view of the given type. + +},{"@pixi/core":8}],16:[function(require,module,exports){ +/*! + * @pixi/filter-noise - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @param {string} type - One of `int8`, `uint8`, `int16`, - *`uint16`, `int32`, `uint32`, and `float32`. - * @return {object} typed array of given type + * @pixi/filter-noise is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license */ -ViewableBuffer.prototype.view = function view (type) -{ - return this[(type + "View")]; -}; +'use strict'; -/** - * Destroys all buffer references. Do not use after calling - * this. - */ -ViewableBuffer.prototype.destroy = function destroy () -{ - this.rawBinaryData = null; - this._int8View = null; - this._uint8View = null; - this._int16View = null; - this._uint16View = null; - this._int32View = null; - this.uint32View = null; - this.float32View = null; -}; +Object.defineProperty(exports, '__esModule', { value: true }); -ViewableBuffer.sizeOf = function sizeOf (type) -{ - switch (type) - { - case 'int8': - case 'uint8': - return 1; - case 'int16': - case 'uint16': - return 2; - case 'int32': - case 'uint32': - case 'float32': - return 4; - default: - throw new Error((type + " isn't a valid view type")); - } -}; +var core = require('@pixi/core'); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} -Object.defineProperties( ViewableBuffer.prototype, prototypeAccessors$5 ); +var fragment = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"; /** - * Renderer dedicated to drawing and batching sprites. - * - * This is the default batch renderer. It buffers objects - * with texture-based geometries and renders them in - * batches. It uploads multiple textures to the GPU to - * reduce to the number of draw calls. + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ +/** + * A Noise effect filter. * * @class - * @protected - * @memberof PIXI - * @extends PIXI.ObjectRenderer + * @extends PIXI.Filter + * @memberof PIXI.filters */ -var AbstractBatchRenderer = /*@__PURE__*/(function (ObjectRenderer) { - function AbstractBatchRenderer(renderer) - { - ObjectRenderer.call(this, renderer); - - /** - * This is used to generate a shader that can - * color each vertex based on a `aTextureId` - * attribute that points to an texture in `uSampler`. - * - * This enables the objects with different textures - * to be drawn in the same draw call. - * - * You can customize your shader by creating your - * custom shader generator. - * - * @member {PIXI.BatchShaderGenerator} - * @protected - */ - this.shaderGenerator = null; - +var NoiseFilter = /** @class */ (function (_super) { + __extends(NoiseFilter, _super); + /** + * @param {number} [noise=0.5] - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} [seed] - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter(noise, seed) { + if (noise === void 0) { noise = 0.5; } + if (seed === void 0) { seed = Math.random(); } + var _this = _super.call(this, core.defaultFilterVertex, fragment, { + uNoise: 0, + uSeed: 0, + }) || this; + _this.noise = noise; + _this.seed = seed; + return _this; + } + Object.defineProperty(NoiseFilter.prototype, "noise", { /** - * The class that represents the geometry of objects - * that are going to be batched with this. + * The amount of noise to apply, this value should be in the range (0, 1]. * - * @member {object} - * @default PIXI.BatchGeometry - * @protected + * @member {number} + * @default 0.5 */ - this.geometryClass = null; - + get: function () { + return this.uniforms.uNoise; + }, + set: function (value) { + this.uniforms.uNoise = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NoiseFilter.prototype, "seed", { /** - * Size of data being buffered per vertex in the - * attribute buffers (in floats). By default, the - * batch-renderer plugin uses 6: - * - * | aVertexPosition | 2 | - * |-----------------|---| - * | aTextureCoords | 2 | - * | aColor | 1 | - * | aTextureId | 1 | + * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. * * @member {number} - * @readonly */ - this.vertexSize = null; + get: function () { + return this.uniforms.uSeed; + }, + set: function (value) { + this.uniforms.uSeed = value; + }, + enumerable: false, + configurable: true + }); + return NoiseFilter; +}(core.Filter)); - /** - * The WebGL state in which this renderer will work. - * - * @member {PIXI.State} - * @readonly - */ - this.state = State.for2d(); +exports.NoiseFilter = NoiseFilter; - /** - * The number of bufferable objects before a flush - * occurs automatically. - * - * @member {number} - * @default settings.SPRITE_BATCH_SIZE * 4 - */ - this.size = settings.settings.SPRITE_BATCH_SIZE * 4; - /** - * Total count of all vertices used by the currently - * buffered objects. - * - * @member {number} - * @private - */ - this._vertexCount = 0; +},{"@pixi/core":8}],17:[function(require,module,exports){ +/*! + * @pixi/graphics - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/graphics is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - /** - * Total count of all indices used by the currently - * buffered objects. - * - * @member {number} - * @private - */ - this._indexCount = 0; +Object.defineProperty(exports, '__esModule', { value: true }); - /** - * Buffer of objects that are yet to be rendered. - * - * @member {PIXI.DisplayObject[]} - * @private - */ - this._bufferedElements = []; +var core = require('@pixi/core'); +var math = require('@pixi/math'); +var utils = require('@pixi/utils'); +var constants = require('@pixi/constants'); +var display = require('@pixi/display'); - /** - * Data for texture batch builder, helps to save a bit of CPU on a pass - * @type {PIXI.BaseTexture[]} - * @private - */ - this._bufferedTextures = []; +/** + * Supported line joints in `PIXI.LineStyle` for graphics. + * + * @see PIXI.Graphics#lineStyle + * @see https://graphicdesign.stackexchange.com/questions/59018/what-is-a-bevel-join-of-two-lines-exactly-illustrator + * + * @name LINE_JOIN + * @memberof PIXI + * @static + * @enum {string} + * @property {string} MITER - 'miter': make a sharp corner where outer part of lines meet + * @property {string} BEVEL - 'bevel': add a square butt at each end of line segment and fill the triangle at turn + * @property {string} ROUND - 'round': add an arc at the joint + */ +(function (LINE_JOIN) { + LINE_JOIN["MITER"] = "miter"; + LINE_JOIN["BEVEL"] = "bevel"; + LINE_JOIN["ROUND"] = "round"; +})(exports.LINE_JOIN || (exports.LINE_JOIN = {})); +(function (LINE_CAP) { + LINE_CAP["BUTT"] = "butt"; + LINE_CAP["ROUND"] = "round"; + LINE_CAP["SQUARE"] = "square"; +})(exports.LINE_CAP || (exports.LINE_CAP = {})); +/** + * Graphics curves resolution settings. If `adaptive` flag is set to `true`, + * the resolution is calculated based on the curve's length to ensure better visual quality. + * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. + * + * @static + * @constant + * @memberof PIXI + * @name GRAPHICS_CURVES + * @type {object} + * @property {boolean} adaptive=false - flag indicating if the resolution should be adaptive + * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored) + * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored) + * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored) + */ +var GRAPHICS_CURVES = { + adaptive: true, + maxLength: 10, + minSegments: 8, + maxSegments: 2048, + epsilon: 0.0001, + _segmentsCount: function (length, defaultSegments) { + if (defaultSegments === void 0) { defaultSegments = 20; } + if (!this.adaptive || !length || isNaN(length)) { + return defaultSegments; + } + var result = Math.ceil(length / this.maxLength); + if (result < this.minSegments) { + result = this.minSegments; + } + else if (result > this.maxSegments) { + result = this.maxSegments; + } + return result; + }, +}; +/** + * Fill style object for Graphics. + * + * @class + * @memberof PIXI + */ +var FillStyle = /** @class */ (function () { + function FillStyle() { /** - * Number of elements that are buffered and are - * waiting to be flushed. + * The hex color value used when coloring the Graphics object. * * @member {number} - * @private + * @default 0xFFFFFF */ - this._bufferSize = 0; - + this.color = 0xFFFFFF; /** - * This shader is generated by `this.shaderGenerator`. - * - * It is generated specifically to handle the required - * number of textures being batched together. + * The alpha value used when filling the Graphics object. * - * @member {PIXI.Shader} - * @protected + * @member {number} + * @default 1 */ - this._shader = null; - + this.alpha = 1.0; /** - * Pool of `this.geometryClass` geometry objects - * that store buffers. They are used to pass data - * to the shader on each draw call. - * - * These are never re-allocated again, unless a - * context change occurs; however, the pool may - * be expanded if required. + * The texture to be used for the fill. * - * @member {PIXI.Geometry[]} - * @private - * @see PIXI.AbstractBatchRenderer.contextChange + * @member {PIXI.Texture} + * @default 0 */ - this._packedGeometries = []; - + this.texture = core.Texture.WHITE; /** - * Size of `this._packedGeometries`. It can be expanded - * if more than `this._packedGeometryPoolSize` flushes - * occur in a single frame. + * The transform aplpied to the texture. * - * @member {number} - * @private + * @member {PIXI.Matrix} + * @default null */ - this._packedGeometryPoolSize = 2; - + this.matrix = null; /** - * A flush may occur multiple times in a single - * frame. On iOS devices or when - * `settings.CAN_UPLOAD_SAME_BUFFER` is false, the - * batch renderer does not upload data to the same - * `WebGLBuffer` for performance reasons. - * - * This is the index into `packedGeometries` that points to - * geometry holding the most recent buffers. + * If the current fill is visible. * - * @member {number} - * @private - */ - this._flushId = 0; - - /** - * Pool of `ViewableBuffer` objects that are sorted in - * order of increasing size. The flush method uses - * the buffer with the least size above the amount - * it requires. These are used for passing attributes. - * - * The first buffer has a size of 8; each subsequent - * buffer has double capacity of its previous. - * - * @member {PIXI.ViewableBuffer[]} - * @private - * @see PIXI.AbstractBatchRenderer#getAttributeBuffer - */ - this._aBuffers = {}; - - /** - * Pool of `Uint16Array` objects that are sorted in - * order of increasing size. The flush method uses - * the buffer with the least size above the amount - * it requires. These are used for passing indices. - * - * The first buffer has a size of 12; each subsequent - * buffer has double capacity of its previous. - * - * @member {Uint16Array[]} - * @private - * @see PIXI.AbstractBatchRenderer#getIndexBuffer - */ - this._iBuffers = {}; - - /** - * Maximum number of textures that can be uploaded to - * the GPU under the current context. It is initialized - * properly in `this.contextChange`. - * - * @member {number} - * @see PIXI.AbstractBatchRenderer#contextChange - * @readonly + * @member {boolean} + * @default false */ - this.MAX_TEXTURES = 1; - - this.renderer.on('prerender', this.onPrerender, this); - renderer.runners.contextChange.add(this); - - this._dcIndex = 0; - this._aIndex = 0; - this._iIndex = 0; - this._attributeBuffer = null; - this._indexBuffer = null; - this._tempBoundTextures = []; + this.visible = false; + this.reset(); } - - if ( ObjectRenderer ) AbstractBatchRenderer.__proto__ = ObjectRenderer; - AbstractBatchRenderer.prototype = Object.create( ObjectRenderer && ObjectRenderer.prototype ); - AbstractBatchRenderer.prototype.constructor = AbstractBatchRenderer; - /** - * Handles the `contextChange` signal. + * Clones the object * - * It calculates `this.MAX_TEXTURES` and allocating the - * packed-geometry object pool. - */ - AbstractBatchRenderer.prototype.contextChange = function contextChange () - { - var gl = this.renderer.gl; - - if (settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY) - { - this.MAX_TEXTURES = 1; - } - else - { - // step 1: first check max textures the GPU can handle. - this.MAX_TEXTURES = Math.min( - gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), - settings.settings.SPRITE_MAX_TEXTURES); - - // step 2: check the maximum number of if statements the shader can have too.. - this.MAX_TEXTURES = checkMaxIfStatementsInShader( - this.MAX_TEXTURES, gl); - } - - this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES); - - // we use the second shader as the first one depending on your browser - // may omit aTextureId as it is not used by the shader so is optimized out. - for (var i = 0; i < this._packedGeometryPoolSize; i++) - { - /* eslint-disable max-len */ - this._packedGeometries[i] = new (this.geometryClass)(); - } - - this.initFlushBuffers(); - }; - - /** - * Makes sure that static and dynamic flush pooled objects have correct dimensions + * @return {PIXI.FillStyle} */ - AbstractBatchRenderer.prototype.initFlushBuffers = function initFlushBuffers () - { - var _drawCallPool = AbstractBatchRenderer._drawCallPool; - var _textureArrayPool = AbstractBatchRenderer._textureArrayPool; - // max draw calls - var MAX_SPRITES = this.size / 4; - // max texture arrays - var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1; - - while (_drawCallPool.length < MAX_SPRITES) - { - _drawCallPool.push(new BatchDrawCall()); - } - while (_textureArrayPool.length < MAX_TA) - { - _textureArrayPool.push(new BatchTextureArray()); - } - for (var i = 0; i < this.MAX_TEXTURES; i++) - { - this._tempBoundTextures[i] = null; - } + FillStyle.prototype.clone = function () { + var obj = new FillStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + return obj; }; - /** - * Handles the `prerender` signal. - * - * It ensures that flushes start from the first geometry - * object again. + * Reset */ - AbstractBatchRenderer.prototype.onPrerender = function onPrerender () - { - this._flushId = 0; + FillStyle.prototype.reset = function () { + this.color = 0xFFFFFF; + this.alpha = 1; + this.texture = core.Texture.WHITE; + this.matrix = null; + this.visible = false; }; - /** - * Buffers the "batchable" object. It need not be rendered - * immediately. - * - * @param {PIXI.DisplayObject} element - the element to render when - * using this renderer + * Destroy and don't use after this */ - AbstractBatchRenderer.prototype.render = function render (element) - { - if (!element._texture.valid) - { - return; - } - - if (this._vertexCount + (element.vertexData.length / 2) > this.size) - { - this.flush(); - } - - this._vertexCount += element.vertexData.length / 2; - this._indexCount += element.indices.length; - this._bufferedTextures[this._bufferSize] = element._texture.baseTexture; - this._bufferedElements[this._bufferSize++] = element; + FillStyle.prototype.destroy = function () { + this.texture = null; + this.matrix = null; }; + return FillStyle; +}()); - AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function buildTexturesAndDrawCalls () - { - var ref = this; - var textures = ref._bufferedTextures; - var MAX_TEXTURES = ref.MAX_TEXTURES; - var textureArrays = AbstractBatchRenderer._textureArrayPool; - var batch = this.renderer.batch; - var boundTextures = this._tempBoundTextures; - var touch = this.renderer.textureGC.count; - - var TICK = ++BaseTexture._globalBatch; - var countTexArrays = 0; - var texArray = textureArrays[0]; - var start = 0; - - batch.copyBoundTextures(boundTextures, MAX_TEXTURES); - - for (var i = 0; i < this._bufferSize; ++i) - { - var tex = textures[i]; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} - textures[i] = null; - if (tex._batchEnabled === TICK) - { - continue; +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ +var buildPoly = { + build: function (graphicsData) { + graphicsData.points = graphicsData.shape.points.slice(); + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var holes = graphicsData.holes; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + if (points.length >= 6) { + var holeArray = []; + // Process holes.. + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + holeArray.push(points.length / 2); + points = points.concat(hole.points); } - - if (texArray.count >= MAX_TEXTURES) - { - batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); - this.buildDrawCalls(texArray, start, i); - start = i; - texArray = textureArrays[++countTexArrays]; - ++TICK; + // sort color + var triangles = utils.earcut(points, holeArray, 2); + if (!triangles) { + return; + } + var vertPos = verts.length / 2; + for (var i = 0; i < triangles.length; i += 3) { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i + 1] + vertPos); + indices.push(triangles[i + 2] + vertPos); + } + for (var i = 0; i < points.length; i++) { + verts.push(points[i]); } - - tex._batchEnabled = TICK; - tex.touched = touch; - texArray.elements[texArray.count++] = tex; } + }, +}; - if (texArray.count > 0) - { - batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); - this.buildDrawCalls(texArray, start, this._bufferSize); - ++countTexArrays; - ++TICK; +// for type only +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ +var buildCircle = { + build: function (graphicsData) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var points = graphicsData.points; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + points.length = 0; + // TODO - bit hacky?? + if (graphicsData.type === math.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; } - - // Clean-up - - for (var i$1 = 0; i$1 < boundTextures.length; i$1++) - { - boundTextures[i$1] = null; + else { + var ellipseData = graphicsData.shape; + width = ellipseData.width; + height = ellipseData.height; } - BaseTexture._globalBatch = TICK; - }; - - /** - * Populating drawcalls for rendering - * - * @param {PIXI.BatchTextureArray} texArray - * @param {number} start - * @param {number} finish - */ - AbstractBatchRenderer.prototype.buildDrawCalls = function buildDrawCalls (texArray, start, finish) - { - var ref = this; - var elements = ref._bufferedElements; - var _attributeBuffer = ref._attributeBuffer; - var _indexBuffer = ref._indexBuffer; - var vertexSize = ref.vertexSize; - var drawCalls = AbstractBatchRenderer._drawCallPool; - - var dcIndex = this._dcIndex; - var aIndex = this._aIndex; - var iIndex = this._iIndex; - - var drawCall = drawCalls[dcIndex]; - - drawCall.start = this._iIndex; - drawCall.texArray = texArray; - - for (var i = start; i < finish; ++i) - { - var sprite = elements[i]; - var tex = sprite._texture.baseTexture; - var spriteBlendMode = utils.premultiplyBlendMode[ - tex.alphaMode ? 1 : 0][sprite.blendMode]; - - elements[i] = null; - - if (start < i && drawCall.blend !== spriteBlendMode) - { - drawCall.size = iIndex - drawCall.start; - start = i; - drawCall = drawCalls[++dcIndex]; - drawCall.texArray = texArray; - drawCall.start = iIndex; - } - - this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); - aIndex += sprite.vertexData.length / 2 * vertexSize; - iIndex += sprite.indices.length; - - drawCall.blend = spriteBlendMode; + if (width === 0 || height === 0) { + return; } - - if (start < finish) - { - drawCall.size = iIndex - drawCall.start; - ++dcIndex; + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) + || Math.floor(15 * Math.sqrt(width + height)); + totalSegs /= 2.3; + var seg = (Math.PI * 2) / totalSegs; + for (var i = 0; i < totalSegs - 0.5; i++) { + points.push(x + (Math.sin(-seg * i) * width), y + (Math.cos(-seg * i) * height)); } - - this._dcIndex = dcIndex; - this._aIndex = aIndex; - this._iIndex = iIndex; - }; - - /** - * Bind textures for current rendering - * - * @param {PIXI.BatchTextureArray} texArray - */ - AbstractBatchRenderer.prototype.bindAndClearTexArray = function bindAndClearTexArray (texArray) - { - var textureSystem = this.renderer.texture; - - for (var j = 0; j < texArray.count; j++) - { - textureSystem.bind(texArray.elements[j], texArray.ids[j]); - texArray.elements[j] = null; + points.push(points[0], points[1]); + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + var vertPos = verts.length / 2; + var center = vertPos; + var circle = (graphicsData.shape); + var matrix = graphicsData.matrix; + var x = circle.x; + var y = circle.y; + // Push center (special point) + verts.push(graphicsData.matrix ? (matrix.a * x) + (matrix.c * y) + matrix.tx : x, graphicsData.matrix ? (matrix.b * x) + (matrix.d * y) + matrix.ty : y); + for (var i = 0; i < points.length; i += 2) { + verts.push(points[i], points[i + 1]); + // add some uvs + indices.push(vertPos++, center, vertPos); } - texArray.count = 0; - }; - - AbstractBatchRenderer.prototype.updateGeometry = function updateGeometry () - { - var ref = this; - var packedGeometries = ref._packedGeometries; - var attributeBuffer = ref._attributeBuffer; - var indexBuffer = ref._indexBuffer; - - if (!settings.settings.CAN_UPLOAD_SAME_BUFFER) - { /* Usually on iOS devices, where the browser doesn't - like uploads to the same buffer in a single frame. */ - if (this._packedGeometryPoolSize <= this._flushId) - { - this._packedGeometryPoolSize++; - packedGeometries[this._flushId] = new (this.geometryClass)(); - } + }, +}; - packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); - packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ +var buildRectangle = { + build: function (graphicsData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + var points = graphicsData.points; + points.length = 0; + points.push(x, y, x + width, y, x + width, y + height, x, y + height); + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var vertPos = verts.length / 2; + verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]); + graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3); + }, +}; - this.renderer.geometry.bind(packedGeometries[this._flushId]); - this.renderer.geometry.updateBuffers(); - this._flushId++; +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + return n1 + (diff * perc); +} +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) { + if (out === void 0) { out = []; } + var n = 20; + var points = out; + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + points.push(x, y); + } + return points; +} +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ +var buildRoundedRectangle = { + build: function (graphicsData) { + var rrectData = graphicsData.shape; + var points = graphicsData.points; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + // Don't allow negative radius or greater than half the smallest width + var radius = Math.max(0, Math.min(rrectData.radius, Math.min(width, height) / 2)); + points.length = 0; + // No radius, do a simple rectangle + if (!radius) { + points.push(x, y, x + width, y, x + width, y + height, x, y + height); } - else - { - // lets use the faster option, always use buffer number 0 - packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); - packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); - - this.renderer.geometry.updateBuffers(); + else { + quadraticBezierCurve(x, y + radius, x, y, x + radius, y, points); + quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, points); + quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, points); + quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, points); } - }; + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + var vecPos = verts.length / 2; + var triangles = utils.earcut(points, null, 2); + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + // indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + // indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + for (var i = 0, j = points.length; i < j; i++) { + verts.push(points[i], points[++i]); + } + }, +}; - AbstractBatchRenderer.prototype.drawBatches = function drawBatches () +/** + * Buffers vertices to draw a square cap. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} x - X-coord of end point + * @param {number} y - Y-coord of end point + * @param {number} nx - X-coord of line normal pointing inside + * @param {number} ny - Y-coord of line normal pointing inside + * @param {Array} verts - vertex buffer + * @returns {} + */ +function square(x, y, nx, ny, innerWeight, outerWeight, clockwise, /* rotation for square (true at left end, false at right end) */ verts) { + var ix = x - (nx * innerWeight); + var iy = y - (ny * innerWeight); + var ox = x + (nx * outerWeight); + var oy = y + (ny * outerWeight); + /* Rotate nx,ny for extension vector */ + var exx; + var eyy; + if (clockwise) { + exx = ny; + eyy = -nx; + } + else { + exx = -ny; + eyy = nx; + } + /* [i|0]x,y extended at cap */ + var eix = ix + exx; + var eiy = iy + eyy; + var eox = ox + exx; + var eoy = oy + eyy; + /* Square itself must be inserted clockwise*/ + verts.push(eix, eiy); + verts.push(eox, eoy); + return 2; +} +/** + * Buffers vertices to draw an arc at the line joint or cap. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} cx - X-coord of center + * @param {number} cy - Y-coord of center + * @param {number} sx - X-coord of arc start + * @param {number} sy - Y-coord of arc start + * @param {number} ex - X-coord of arc end + * @param {number} ey - Y-coord of arc end + * @param {Array} verts - buffer of vertices + * @param {boolean} clockwise - orientation of vertices + * @returns {number} - no. of vertices pushed + */ +function round(cx, cy, sx, sy, ex, ey, verts, clockwise) { + var cx2p0x = sx - cx; + var cy2p0y = sy - cy; + var angle0 = Math.atan2(cx2p0x, cy2p0y); + var angle1 = Math.atan2(ex - cx, ey - cy); + if (clockwise && angle0 < angle1) { + angle0 += Math.PI * 2; + } + else if (!clockwise && angle0 > angle1) { + angle1 += Math.PI * 2; + } + var startAngle = angle0; + var angleDiff = angle1 - angle0; + var absAngleDiff = Math.abs(angleDiff); + /* if (absAngleDiff >= PI_LBOUND && absAngleDiff <= PI_UBOUND) { - var dcCount = this._dcIndex; - var ref = this.renderer; - var gl = ref.gl; - var stateSystem = ref.state; - var drawCalls = AbstractBatchRenderer._drawCallPool; - - var curTexArray = null; + const r1x = cx - nxtPx; + const r1y = cy - nxtPy; - // Upload textures and do the draw calls - for (var i = 0; i < dcCount; i++) + if (r1x === 0) { - var ref$1 = drawCalls[i]; - var texArray = ref$1.texArray; - var type = ref$1.type; - var size = ref$1.size; - var start = ref$1.start; - var blend = ref$1.blend; - - if (curTexArray !== texArray) + if (r1y > 0) { - curTexArray = texArray; - this.bindAndClearTexArray(texArray); + angleDiff = -angleDiff; } - - stateSystem.setBlendMode(blend); - gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); } - }; - - /** - * Renders the content _now_ and empties the current batch. - */ - AbstractBatchRenderer.prototype.flush = function flush () - { - if (this._vertexCount === 0) + else if (r1x >= -GRAPHICS_CURVES.epsilon) { - return; + angleDiff = -angleDiff; } - - this._attributeBuffer = this.getAttributeBuffer(this._vertexCount); - this._indexBuffer = this.getIndexBuffer(this._indexCount); - this._aIndex = 0; - this._iIndex = 0; - this._dcIndex = 0; - - this.buildTexturesAndDrawCalls(); - this.updateGeometry(); - this.drawBatches(); - - // reset elements buffer for the next flush - this._bufferSize = 0; - this._vertexCount = 0; - this._indexCount = 0; - }; - - /** - * Starts a new sprite batch. - */ - AbstractBatchRenderer.prototype.start = function start () - { - this.renderer.state.set(this.state); - - this.renderer.shader.bind(this._shader); - - if (settings.settings.CAN_UPLOAD_SAME_BUFFER) - { - // bind buffer #0, we don't need others - this.renderer.geometry.bind(this._packedGeometries[this._flushId]); + }*/ + var radius = Math.sqrt((cx2p0x * cx2p0x) + (cy2p0y * cy2p0y)); + var segCount = ((15 * absAngleDiff * Math.sqrt(radius) / Math.PI) >> 0) + 1; + var angleInc = angleDiff / segCount; + startAngle += angleInc; + if (clockwise) { + verts.push(cx, cy); + verts.push(sx, sy); + for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx, cy); + verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); } - }; - - /** - * Stops and flushes the current batch. - */ - AbstractBatchRenderer.prototype.stop = function stop () - { - this.flush(); - }; - - /** - * Destroys this `AbstractBatchRenderer`. It cannot be used again. - */ - AbstractBatchRenderer.prototype.destroy = function destroy () - { - for (var i = 0; i < this._packedGeometryPoolSize; i++) - { - if (this._packedGeometries[i]) - { - this._packedGeometries[i].destroy(); + verts.push(cx, cy); + verts.push(ex, ey); + } + else { + verts.push(sx, sy); + verts.push(cx, cy); + for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); + verts.push(cx, cy); + } + verts.push(ex, ey); + verts.push(cx, cy); + } + return segCount * 2; +} +/** + * Builds a line to draw using the polygon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ +function buildNonNativeLine(graphicsData, graphicsGeometry) { + var shape = graphicsData.shape; + var points = graphicsData.points || shape.points.slice(); + var eps = graphicsGeometry.closePointEps; + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + var style = graphicsData.lineStyle; + // get first and last point.. figure out the middle! + var firstPoint = new math.Point(points[0], points[1]); + var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); + var closedShape = shape.type !== math.SHAPES.POLY || shape.closeStroke; + var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps + && Math.abs(firstPoint.y - lastPoint.y) < eps; + // if the first point is the last point - gonna have issues :) + if (closedShape) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + if (closedPath) { + points.pop(); + points.pop(); + lastPoint.set(points[points.length - 2], points[points.length - 1]); + } + var midPointX = (firstPoint.x + lastPoint.x) * 0.5; + var midPointY = (lastPoint.y + firstPoint.y) * 0.5; + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + var verts = graphicsGeometry.points; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 2; + // Max. inner and outer width + var width = style.width / 2; + var widthSquared = width * width; + var miterLimitSquared = style.miterLimit * style.miterLimit; + /* Line segments of interest where (x1,y1) forms the corner. */ + var x0 = points[0]; + var y0 = points[1]; + var x1 = points[2]; + var y1 = points[3]; + var x2 = 0; + var y2 = 0; + /* perp[?](x|y) = the line normal with magnitude lineWidth. */ + var perpx = -(y0 - y1); + var perpy = x0 - x1; + var perp1x = 0; + var perp1y = 0; + var dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + var ratio = style.alignment; // 0.5; + var innerWeight = (1 - ratio) * 2; + var outerWeight = ratio * 2; + if (!closedShape) { + if (style.cap === exports.LINE_CAP.ROUND) { + indexCount += round(x0 - (perpx * (innerWeight - outerWeight) * 0.5), y0 - (perpy * (innerWeight - outerWeight) * 0.5), x0 - (perpx * innerWeight), y0 - (perpy * innerWeight), x0 + (perpx * outerWeight), y0 + (perpy * outerWeight), verts, true) + 2; + } + else if (style.cap === exports.LINE_CAP.SQUARE) { + indexCount += square(x0, y0, perpx, perpy, innerWeight, outerWeight, true, verts); + } + } + // Push first point (below & above vertices) + verts.push(x0 - (perpx * innerWeight), y0 - (perpy * innerWeight)); + verts.push(x0 + (perpx * outerWeight), y0 + (perpy * outerWeight)); + for (var i = 1; i < length - 1; ++i) { + x0 = points[(i - 1) * 2]; + y0 = points[((i - 1) * 2) + 1]; + x1 = points[i * 2]; + y1 = points[(i * 2) + 1]; + x2 = points[(i + 1) * 2]; + y2 = points[((i + 1) * 2) + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + perp1x = -(y1 - y2); + perp1y = x1 - x2; + dist = Math.sqrt((perp1x * perp1x) + (perp1y * perp1y)); + perp1x /= dist; + perp1y /= dist; + perp1x *= width; + perp1y *= width; + /* d[x|y](0|1) = the component displacment between points p(0,1|1,2) */ + var dx0 = x1 - x0; + var dy0 = y0 - y1; + var dx1 = x1 - x2; + var dy1 = y2 - y1; + /* +ve if internal angle counterclockwise, -ve if internal angle clockwise. */ + var cross = (dy0 * dx1) - (dy1 * dx0); + var clockwise = (cross < 0); + /* Going nearly straight? */ + if (Math.abs(cross) < 0.1) { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + continue; + } + /* p[x|y] is the miter point. pdist is the distance between miter point and p1. */ + var c1 = ((-perpx + x0) * (-perpy + y1)) - ((-perpx + x1) * (-perpy + y0)); + var c2 = ((-perp1x + x2) * (-perp1y + y1)) - ((-perp1x + x1) * (-perp1y + y2)); + var px = ((dx0 * c2) - (dx1 * c1)) / cross; + var py = ((dy1 * c1) - (dy0 * c2)) / cross; + var pdist = ((px - x1) * (px - x1)) + ((py - y1) * (py - y1)); + /* Inner miter point */ + var imx = x1 + ((px - x1) * innerWeight); + var imy = y1 + ((py - y1) * innerWeight); + /* Outer miter point */ + var omx = x1 - ((px - x1) * outerWeight); + var omy = y1 - ((py - y1) * outerWeight); + if (style.join === exports.LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) { + if (clockwise) /* rotating at inner angle */ { + verts.push(imx, imy); // inner miter point + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex + verts.push(imx, imy); // inner miter point + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex + } + else /* rotating at outer angle */ { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex + verts.push(omx, omy); // outer miter point + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's outer vertex + verts.push(omx, omy); // outer miter point + } + indexCount += 2; + } + else if (style.join === exports.LINE_JOIN.ROUND) { + if (clockwise) /* arc is outside */ { + verts.push(imx, imy); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 4; + verts.push(imx, imy); + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); + } + else /* arc is inside */ { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(omx, omy); + indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4; + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); + verts.push(omx, omy); } } - - this.renderer.off('prerender', this.onPrerender, this); - - this._aBuffers = null; - this._iBuffers = null; - this._packedGeometries = null; - this._attributeBuffer = null; - this._indexBuffer = null; - - if (this._shader) - { - this._shader.destroy(); - this._shader = null; + else { + verts.push(imx, imy); + verts.push(omx, omy); + } + } + x0 = points[(length - 2) * 2]; + y0 = points[((length - 2) * 2) + 1]; + x1 = points[(length - 1) * 2]; + y1 = points[((length - 1) * 2) + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + if (!closedShape) { + if (style.cap === exports.LINE_CAP.ROUND) { + indexCount += round(x1 - (perpx * (innerWeight - outerWeight) * 0.5), y1 - (perpy * (innerWeight - outerWeight) * 0.5), x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), verts, false) + 2; } + else if (style.cap === exports.LINE_CAP.SQUARE) { + indexCount += square(x1, y1, perpx, perpy, innerWeight, outerWeight, false, verts); + } + } + var indices = graphicsGeometry.indices; + var eps2 = GRAPHICS_CURVES.epsilon * GRAPHICS_CURVES.epsilon; + // indices.push(indexStart); + for (var i = indexStart; i < indexCount + indexStart - 2; ++i) { + x0 = verts[(i * 2)]; + y0 = verts[(i * 2) + 1]; + x1 = verts[(i + 1) * 2]; + y1 = verts[((i + 1) * 2) + 1]; + x2 = verts[(i + 2) * 2]; + y2 = verts[((i + 2) * 2) + 1]; + /* Skip zero area triangles */ + if (Math.abs((x0 * (y1 - y2)) + (x1 * (y2 - y0)) + (x2 * (y0 - y1))) < eps2) { + continue; + } + indices.push(i, i + 1, i + 2); + } +} +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ +function buildNativeLine(graphicsData, graphicsGeometry) { + var i = 0; + var shape = graphicsData.shape; + var points = graphicsData.points || shape.points; + var closedShape = shape.type !== math.SHAPES.POLY || shape.closeStroke; + if (points.length === 0) + { return; } + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + var length = points.length / 2; + var startIndex = verts.length / 2; + var currentIndex = startIndex; + verts.push(points[0], points[1]); + for (i = 1; i < length; i++) { + verts.push(points[i * 2], points[(i * 2) + 1]); + indices.push(currentIndex, currentIndex + 1); + currentIndex++; + } + if (closedShape) { + indices.push(currentIndex, startIndex); + } +} +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ +function buildLine(graphicsData, graphicsGeometry) { + if (graphicsData.lineStyle.native) { + buildNativeLine(graphicsData, graphicsGeometry); + } + else { + buildNonNativeLine(graphicsData, graphicsGeometry); + } +} - ObjectRenderer.prototype.destroy.call(this); - }; +/** + * Draw a star shape with an arbitrary number of points. + * + * @class + * @extends PIXI.Polygon + * @memberof PIXI.graphicsUtils + * @param {number} x - Center X position of the star + * @param {number} y - Center Y position of the star + * @param {number} points - The number of points of the star, must be > 1 + * @param {number} radius - The outer radius of the star + * @param {number} [innerRadius] - The inner radius between points, default half `radius` + * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +var Star = /** @class */ (function (_super) { + __extends(Star, _super); + function Star(x, y, points, radius, innerRadius, rotation) { + if (rotation === void 0) { rotation = 0; } + var _this = this; + innerRadius = innerRadius || radius / 2; + var startAngle = (-1 * Math.PI / 2) + rotation; + var len = points * 2; + var delta = math.PI_2 / len; + var polygon = []; + for (var i = 0; i < len; i++) { + var r = i % 2 ? innerRadius : radius; + var angle = (i * delta) + startAngle; + polygon.push(x + (r * Math.cos(angle)), y + (r * Math.sin(angle))); + } + _this = _super.call(this, polygon) || this; + return _this; + } + return Star; +}(math.Polygon)); +/** + * Utilities for arc curves + * @class + * @private + */ +var ArcUtils = /** @class */ (function () { + function ArcUtils() { + } /** - * Fetches an attribute buffer from `this._aBuffers` that - * can hold atleast `size` floats. + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! * - * @param {number} size - minimum capacity required - * @return {ViewableBuffer} - buffer than can hold atleast `size` floats * @private + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {object} If the arc length is valid, return center of circle, radius and other info otherwise `null`. */ - AbstractBatchRenderer.prototype.getAttributeBuffer = function getAttributeBuffer (size) - { - // 8 vertices is enough for 2 quads - var roundedP2 = utils.nextPow2(Math.ceil(size / 8)); - var roundedSizeIndex = utils.log2(roundedP2); - var roundedSize = roundedP2 * 8; - - if (this._aBuffers.length <= roundedSizeIndex) - { - this._iBuffers.length = roundedSizeIndex + 1; - } - - var buffer = this._aBuffers[roundedSize]; - - if (!buffer) - { - this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4); + ArcUtils.curveTo = function (x1, y1, x2, y2, radius, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs((a1 * b2) - (b1 * a2)); + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + return null; } - - return buffer; + var dd = (a1 * a1) + (b1 * b1); + var cc = (a2 * a2) + (b2 * b2); + var tt = (a1 * a2) + (b1 * b2); + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = (k1 * b2) + (k2 * b1); + var cy = (k1 * a2) + (k2 * a1); + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + return { + cx: (cx + x1), + cy: (cy + y1), + radius: radius, + startAngle: startAngle, + endAngle: endAngle, + anticlockwise: (b1 * a2 > b2 * a1), + }; }; - + /* eslint-disable max-len */ /** - * Fetches an index buffer from `this._iBuffers` that can - * has atleast `size` capacity. + * The arc method creates an arc/curve (used to create circles, or parts of circles). * - * @param {number} size - minimum required capacity - * @return {Uint16Array} - buffer that can fit `size` - * indices. * @private + * @param {number} startX - Start x location of arc + * @param {number} startY - Start y location of arc + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} anticlockwise - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @param {number[]} points - Collection of points to add to */ - AbstractBatchRenderer.prototype.getIndexBuffer = function getIndexBuffer (size) - { - // 12 indices is enough for 2 quads - var roundedP2 = utils.nextPow2(Math.ceil(size / 12)); - var roundedSizeIndex = utils.log2(roundedP2); - var roundedSize = roundedP2 * 12; - - if (this._iBuffers.length <= roundedSizeIndex) - { - this._iBuffers.length = roundedSizeIndex + 1; - } - - var buffer = this._iBuffers[roundedSizeIndex]; + ArcUtils.arc = function (_startX, _startY, cx, cy, radius, startAngle, endAngle, _anticlockwise, points) { + var sweep = endAngle - startAngle; + var n = GRAPHICS_CURVES._segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / math.PI_2) * 40); + var theta = (sweep) / (n * 2); + var theta2 = theta * 2; + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + var segMinus = n - 1; + var remainder = (segMinus % 1) / segMinus; + for (var i = 0; i <= segMinus; ++i) { + var real = i + (remainder * i); + var angle = ((theta) + startAngle + (theta2 * real)); + var c = Math.cos(angle); + var s = -Math.sin(angle); + points.push((((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy); + } + }; + return ArcUtils; +}()); - if (!buffer) - { - this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize); +/** + * Utilities for bezier curves + * @class + * @private + */ +var BezierUtils = /** @class */ (function () { + function BezierUtils() { + } + /** + * Calculate length of bezier curve. + * Analytical solution is impossible, since it involves an integral that does not integrate in general. + * Therefore numerical solution is used. + * + * @private + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {number} Length of bezier curve + */ + BezierUtils.curveLength = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var n = 10; + var result = 0.0; + var t = 0.0; + var t2 = 0.0; + var t3 = 0.0; + var nt = 0.0; + var nt2 = 0.0; + var nt3 = 0.0; + var x = 0.0; + var y = 0.0; + var dx = 0.0; + var dy = 0.0; + var prevX = fromX; + var prevY = fromY; + for (var i = 1; i <= n; ++i) { + t = i / n; + t2 = t * t; + t3 = t2 * t; + nt = (1.0 - t); + nt2 = nt * nt; + nt3 = nt2 * nt; + x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX); + y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY); + dx = prevX - x; + dy = prevY - y; + prevX = x; + prevY = y; + result += Math.sqrt((dx * dx) + (dy * dy)); } - - return buffer; + return result; }; - /** - * Takes the four batching parameters of `element`, interleaves - * and pushes them into the batching attribute/index buffers given. + * Calculate the points for a bezier curve and then draws it. * - * It uses these properties: `vertexData` `uvs`, `textureId` and - * `indicies`. It also uses the "tint" of the base-texture, if - * present. + * Ignored from docs since it is not directly exposed. * - * @param {PIXI.Sprite} element - element being rendered - * @param {PIXI.ViewableBuffer} attributeBuffer - attribute buffer. - * @param {Uint16Array} indexBuffer - index buffer - * @param {number} aIndex - number of floats already in the attribute buffer - * @param {number} iIndex - number of indices already in `indexBuffer` + * @ignore + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} points - Path array to push points into */ - AbstractBatchRenderer.prototype.packInterleavedGeometry = function packInterleavedGeometry (element, attributeBuffer, indexBuffer, aIndex, iIndex) - { - var uint32View = attributeBuffer.uint32View; - var float32View = attributeBuffer.float32View; - - var packedVertices = aIndex / this.vertexSize; - var uvs = element.uvs; - var indicies = element.indices; - var vertexData = element.vertexData; - var textureId = element._texture.baseTexture._batchLocation; - - var alpha = Math.min(element.worldAlpha, 1.0); - var argb = (alpha < 1.0 - && element._texture.baseTexture.alphaMode) - ? utils.premultiplyTint(element._tintRGB, alpha) - : element._tintRGB + (alpha * 255 << 24); - - // lets not worry about tint! for now.. - for (var i = 0; i < vertexData.length; i += 2) - { - float32View[aIndex++] = vertexData[i]; - float32View[aIndex++] = vertexData[i + 1]; - float32View[aIndex++] = uvs[i]; - float32View[aIndex++] = uvs[i + 1]; - uint32View[aIndex++] = argb; - float32View[aIndex++] = textureId; - } + BezierUtils.curveTo = function (cpX, cpY, cpX2, cpY2, toX, toY, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + points.length -= 2; + var n = GRAPHICS_CURVES._segmentsCount(BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)); + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + points.push(fromX, fromY); + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + t2 = j * j; + t3 = t2 * j; + points.push((dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY)); + } + }; + return BezierUtils; +}()); - for (var i$1 = 0; i$1 < indicies.length; i$1++) - { - indexBuffer[iIndex++] = packedVertices + indicies[i$1]; +/** + * Utilities for quadratic curves + * @class + * @private + */ +var QuadraticUtils = /** @class */ (function () { + function QuadraticUtils() { + } + /** + * Calculate length of quadratic curve + * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} + * for the detailed explanation of math behind this. + * + * @private + * @param {number} fromX - x-coordinate of curve start point + * @param {number} fromY - y-coordinate of curve start point + * @param {number} cpX - x-coordinate of curve control point + * @param {number} cpY - y-coordinate of curve control point + * @param {number} toX - x-coordinate of curve end point + * @param {number} toY - y-coordinate of curve end point + * @return {number} Length of quadratic curve + */ + QuadraticUtils.curveLength = function (fromX, fromY, cpX, cpY, toX, toY) { + var ax = fromX - (2.0 * cpX) + toX; + var ay = fromY - (2.0 * cpY) + toY; + var bx = (2.0 * cpX) - (2.0 * fromX); + var by = (2.0 * cpY) - (2.0 * fromY); + var a = 4.0 * ((ax * ax) + (ay * ay)); + var b = 4.0 * ((ax * bx) + (ay * by)); + var c = (bx * bx) + (by * by); + var s = 2.0 * Math.sqrt(a + b + c); + var a2 = Math.sqrt(a); + var a32 = 2.0 * a * a2; + var c2 = 2.0 * Math.sqrt(c); + var ba = b / a2; + return ((a32 * s) + + (a2 * b * (s - c2)) + + (((4.0 * c * a) - (b * b)) + * Math.log(((2.0 * a2) + ba + s) / (ba + c2)))) / (4.0 * a32); + }; + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @private + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} points - Points to add segments to. + */ + QuadraticUtils.curveTo = function (cpX, cpY, toX, toY, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var n = GRAPHICS_CURVES._segmentsCount(QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY)); + var xa = 0; + var ya = 0; + for (var i = 1; i <= n; ++i) { + var j = i / n; + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j)); } }; + return QuadraticUtils; +}()); - return AbstractBatchRenderer; -}(ObjectRenderer)); +/** + * A structure to hold interim batch objects for Graphics. + * @class + * @memberof PIXI.graphicsUtils + */ +var BatchPart = /** @class */ (function () { + function BatchPart() { + this.reset(); + } + /** + * Begin batch part + * + * @param {PIXI.FillStyle | PIXI.LineStyle} style + * @param {number} startIndex + * @param {number} attribStart + */ + BatchPart.prototype.begin = function (style, startIndex, attribStart) { + this.reset(); + this.style = style; + this.start = startIndex; + this.attribStart = attribStart; + }; + /** + * End batch part + * + * @param {number} endIndex + * @param {number} endAttrib + */ + BatchPart.prototype.end = function (endIndex, endAttrib) { + this.attribSize = endAttrib - this.attribStart; + this.size = endIndex - this.start; + }; + BatchPart.prototype.reset = function () { + this.style = null; + this.size = 0; + this.start = 0; + this.attribStart = 0; + this.attribSize = 0; + }; + return BatchPart; +}()); /** - * Pool of `BatchDrawCall` objects that `flush` used - * to create "batches" of the objects being rendered. + * Generalized convenience utilities for Graphics. * - * These are never re-allocated again. - * Shared between all batch renderers because it can be only one "flush" working at the moment. + * @namespace graphicsUtils + * @memberof PIXI + */ +var _a; +/** + * Map of fill commands for each shape type. * - * @static - * @member {PIXI.BatchDrawCall[]} + * @memberof PIXI.graphicsUtils + * @member {Object} FILL_COMMANDS */ -AbstractBatchRenderer._drawCallPool = []; - +var FILL_COMMANDS = (_a = {}, + _a[math.SHAPES.POLY] = buildPoly, + _a[math.SHAPES.CIRC] = buildCircle, + _a[math.SHAPES.ELIP] = buildCircle, + _a[math.SHAPES.RECT] = buildRectangle, + _a[math.SHAPES.RREC] = buildRoundedRectangle, + _a); /** - * Pool of `BatchDrawCall` objects that `flush` used - * to create "batches" of the objects being rendered. + * Batch pool, stores unused batches for preventing allocations. * - * These are never re-allocated again. - * Shared between all batch renderers because it can be only one "flush" working at the moment. + * @memberof PIXI.graphicsUtils + * @member {Array} BATCH_POOL + */ +var BATCH_POOL = []; +/** + * Draw call pool, stores unused draw calls for preventing allocations. * - * @static - * @member {PIXI.BatchTextureArray[]} + * @memberof PIXI.graphicsUtils + * @member {Array} DRAW_CALL_POOL */ -AbstractBatchRenderer._textureArrayPool = []; +var DRAW_CALL_POOL = []; + +var index = ({ + buildPoly: buildPoly, + buildCircle: buildCircle, + buildRectangle: buildRectangle, + buildRoundedRectangle: buildRoundedRectangle, + FILL_COMMANDS: FILL_COMMANDS, + BATCH_POOL: BATCH_POOL, + DRAW_CALL_POOL: DRAW_CALL_POOL, + buildLine: buildLine, + Star: Star, + ArcUtils: ArcUtils, + BezierUtils: BezierUtils, + QuadraticUtils: QuadraticUtils, + BatchPart: BatchPart +}); /** - * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer + * A class to contain data useful for Graphics objects * * @class * @memberof PIXI */ -var BatchShaderGenerator = function BatchShaderGenerator(vertexSrc, fragTemplate) -{ +var GraphicsData = /** @class */ (function () { /** - * Reference to the vertex shader source. * - * @member {string} + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param {PIXI.FillStyle} [fillStyle] - the width of the line to draw + * @param {PIXI.LineStyle} [lineStyle] - the color of the line to draw + * @param {PIXI.Matrix} [matrix] - Transform matrix */ - this.vertexSrc = vertexSrc; - + function GraphicsData(shape, fillStyle, lineStyle, matrix) { + if (fillStyle === void 0) { fillStyle = null; } + if (lineStyle === void 0) { lineStyle = null; } + if (matrix === void 0) { matrix = null; } + /** + * The shape object to draw. + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} + */ + this.shape = shape; + /** + * The style of the line. + * @member {PIXI.LineStyle} + */ + this.lineStyle = lineStyle; + /** + * The style of the fill. + * @member {PIXI.FillStyle} + */ + this.fillStyle = fillStyle; + /** + * The transform matrix. + * @member {PIXI.Matrix} + */ + this.matrix = matrix; + /** + * The type of the shape, see the Const.Shapes file for all the existing types, + * @member {number} + */ + this.type = shape.type; + /** + * The collection of points. + * @member {number[]} + */ + this.points = []; + /** + * The collection of holes. + * @member {PIXI.GraphicsData[]} + */ + this.holes = []; + } /** - * Reference to the fragement shader template. Must contain "%count%" and "%forloop%". + * Creates a new GraphicsData object with the same values as this one. * - * @member {string} + * @return {PIXI.GraphicsData} Cloned GraphicsData object */ - this.fragTemplate = fragTemplate; - - this.programCache = {}; - this.defaultGroupCache = {}; - - if (fragTemplate.indexOf('%count%') < 0) - { - throw new Error('Fragment template must contain "%count%".'); - } - - if (fragTemplate.indexOf('%forloop%') < 0) - { - throw new Error('Fragment template must contain "%forloop%".'); - } -}; - -BatchShaderGenerator.prototype.generateShader = function generateShader (maxTextures) -{ - if (!this.programCache[maxTextures]) - { - var sampleValues = new Int32Array(maxTextures); - - for (var i = 0; i < maxTextures; i++) - { - sampleValues[i] = i; - } - - this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true); - - var fragmentSrc = this.fragTemplate; - - fragmentSrc = fragmentSrc.replace(/%count%/gi, ("" + maxTextures)); - fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); - - this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc); - } - - var uniforms = { - tint: new Float32Array([1, 1, 1, 1]), - translationMatrix: new math.Matrix(), - default: this.defaultGroupCache[maxTextures], + GraphicsData.prototype.clone = function () { + return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix); }; + /** + * Destroys the Graphics data. + * + */ + GraphicsData.prototype.destroy = function () { + this.shape = null; + this.holes.length = 0; + this.holes = null; + this.points.length = 0; + this.points = null; + this.lineStyle = null; + this.fillStyle = null; + }; + return GraphicsData; +}()); - return new Shader(this.programCache[maxTextures], uniforms); -}; - -BatchShaderGenerator.prototype.generateSampleSrc = function generateSampleSrc (maxTextures) -{ - var src = ''; - - src += '\n'; - src += '\n'; - - for (var i = 0; i < maxTextures; i++) - { - if (i > 0) - { - src += '\nelse '; - } - - if (i < maxTextures - 1) - { - src += "if(vTextureId < " + i + ".5)"; - } - - src += '\n{'; - src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);"; - src += '\n}'; - } - - src += '\n'; - src += '\n'; - - return src; -}; - +var tmpPoint = new math.Point(); +var tmpBounds = new display.Bounds(); /** - * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects). + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive + * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster. * * @class + * @extends PIXI.BatchGeometry * @memberof PIXI */ -var BatchGeometry = /*@__PURE__*/(function (Geometry) { - function BatchGeometry(_static) - { - if ( _static === void 0 ) _static = false; - - Geometry.call(this); - +var GraphicsGeometry = /** @class */ (function (_super) { + __extends(GraphicsGeometry, _super); + function GraphicsGeometry() { + var _this = _super.call(this) || this; + _this.uvsFloat32 = null; + _this.indicesUint16 = null; /** - * Buffer used for position, color, texture IDs + * An array of points to draw, 2 numbers per point * - * @member {PIXI.Buffer} + * @member {number[]} * @protected */ - this._buffer = new Buffer(null, _static, false); - + _this.points = []; /** - * Index buffer data + * The collection of colors * - * @member {PIXI.Buffer} + * @member {number[]} * @protected */ - this._indexBuffer = new Buffer(null, _static, true); - - this.addAttribute('aVertexPosition', this._buffer, 2, false, constants.TYPES.FLOAT) - .addAttribute('aTextureCoord', this._buffer, 2, false, constants.TYPES.FLOAT) - .addAttribute('aColor', this._buffer, 4, true, constants.TYPES.UNSIGNED_BYTE) - .addAttribute('aTextureId', this._buffer, 1, true, constants.TYPES.FLOAT) - .addIndex(this._indexBuffer); - } - - if ( Geometry ) BatchGeometry.__proto__ = Geometry; - BatchGeometry.prototype = Object.create( Geometry && Geometry.prototype ); - BatchGeometry.prototype.constructor = BatchGeometry; - - return BatchGeometry; -}(Geometry)); - -var defaultVertex$2 = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"; - -var defaultFragment$2 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"; - -/** - * @class - * @memberof PIXI - * @hideconstructor - */ -var BatchPluginFactory = function BatchPluginFactory () {}; - -var staticAccessors$1 = { defaultVertexSrc: { configurable: true },defaultFragmentTemplate: { configurable: true } }; - -BatchPluginFactory.create = function create (options) -{ - var ref = Object.assign({ - vertex: defaultVertex$2, - fragment: defaultFragment$2, - geometryClass: BatchGeometry, - vertexSize: 6, - }, options); - var vertex = ref.vertex; - var fragment = ref.fragment; - var vertexSize = ref.vertexSize; - var geometryClass = ref.geometryClass; - - return /*@__PURE__*/(function (AbstractBatchRenderer) { - function BatchPlugin(renderer) - { - AbstractBatchRenderer.call(this, renderer); - - this.shaderGenerator = new BatchShaderGenerator(vertex, fragment); - this.geometryClass = geometryClass; - this.vertexSize = vertexSize; - } - - if ( AbstractBatchRenderer ) BatchPlugin.__proto__ = AbstractBatchRenderer; - BatchPlugin.prototype = Object.create( AbstractBatchRenderer && AbstractBatchRenderer.prototype ); - BatchPlugin.prototype.constructor = BatchPlugin; - - return BatchPlugin; - }(AbstractBatchRenderer)); -}; - -/** - * The default vertex shader source - * - * @static - * @type {string} - * @constant - */ -staticAccessors$1.defaultVertexSrc.get = function () -{ - return defaultVertex$2; -}; - -/** - * The default fragment shader source - * - * @static - * @type {string} - * @constant - */ -staticAccessors$1.defaultFragmentTemplate.get = function () -{ - return defaultFragment$2; -}; - -Object.defineProperties( BatchPluginFactory, staticAccessors$1 ); - -// Setup the default BatchRenderer plugin, this is what -// we'll actually export at the root level -var BatchRenderer = BatchPluginFactory.create(); - -exports.AbstractBatchRenderer = AbstractBatchRenderer; -exports.AbstractRenderer = AbstractRenderer; -exports.Attribute = Attribute; -exports.BaseRenderTexture = BaseRenderTexture; -exports.BaseTexture = BaseTexture; -exports.BatchDrawCall = BatchDrawCall; -exports.BatchGeometry = BatchGeometry; -exports.BatchPluginFactory = BatchPluginFactory; -exports.BatchRenderer = BatchRenderer; -exports.BatchShaderGenerator = BatchShaderGenerator; -exports.BatchTextureArray = BatchTextureArray; -exports.Buffer = Buffer; -exports.CubeTexture = CubeTexture; -exports.Filter = Filter; -exports.Framebuffer = Framebuffer; -exports.GLProgram = GLProgram; -exports.GLTexture = GLTexture; -exports.Geometry = Geometry; -exports.MaskData = MaskData; -exports.ObjectRenderer = ObjectRenderer; -exports.Program = Program; -exports.Quad = Quad; -exports.QuadUv = QuadUv; -exports.RenderTexture = RenderTexture; -exports.RenderTexturePool = RenderTexturePool; -exports.Renderer = Renderer; -exports.Shader = Shader; -exports.SpriteMaskFilter = SpriteMaskFilter; -exports.State = State; -exports.System = System; -exports.Texture = Texture; -exports.TextureMatrix = TextureMatrix; -exports.TextureUvs = TextureUvs; -exports.UniformGroup = UniformGroup; -exports.ViewableBuffer = ViewableBuffer; -exports.autoDetectRenderer = autoDetectRenderer; -exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader; -exports.defaultFilterVertex = defaultFilter; -exports.defaultVertex = _default; -exports.resources = index; -exports.systems = systems; - - -},{"@pixi/constants":16,"@pixi/display":18,"@pixi/math":29,"@pixi/runner":38,"@pixi/settings":39,"@pixi/ticker":46,"@pixi/utils":47}],18:[function(require,module,exports){ -/*! - * @pixi/display - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/display is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var settings = require('@pixi/settings'); -var math = require('@pixi/math'); -var utils = require('@pixi/utils'); - -/** - * Sets the default value for the container property 'sortableChildren'. - * If set to true, the container will sort its children by zIndex value - * when updateTransform() is called, or manually if sortChildren() is called. - * - * This actually changes the order of elements in the array, so should be treated - * as a basic solution that is not performant compared to other solutions, - * such as @link https://github.com/pixijs/pixi-display - * - * Also be aware of that this may not work nicely with the addChildAt() function, - * as the zIndex sorting may cause the child to automatically sorted to another position. - * - * @static - * @constant - * @name SORTABLE_CHILDREN - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ -settings.settings.SORTABLE_CHILDREN = false; - -/** - * 'Builder' pattern for bounds rectangles. - * - * This could be called an Axis-Aligned Bounding Box. - * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems. - * - * @class - * @memberof PIXI - */ -var Bounds = function Bounds() -{ - /** - * @member {number} - * @default 0 - */ - this.minX = Infinity; - - /** - * @member {number} - * @default 0 - */ - this.minY = Infinity; - - /** - * @member {number} - * @default 0 - */ - this.maxX = -Infinity; - - /** - * @member {number} - * @default 0 - */ - this.maxY = -Infinity; - - this.rect = null; -}; - -/** - * Checks if bounds are empty. - * - * @return {boolean} True if empty. - */ -Bounds.prototype.isEmpty = function isEmpty () -{ - return this.minX > this.maxX || this.minY > this.maxY; -}; - -/** - * Clears the bounds and resets. - * - */ -Bounds.prototype.clear = function clear () -{ - this.updateID++; - - this.minX = Infinity; - this.minY = Infinity; - this.maxX = -Infinity; - this.maxY = -Infinity; -}; - -/** - * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle - * It is not guaranteed that it will return tempRect - * - * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty - * @returns {PIXI.Rectangle} A rectangle of the bounds - */ -Bounds.prototype.getRectangle = function getRectangle (rect) -{ - if (this.minX > this.maxX || this.minY > this.maxY) - { - return math.Rectangle.EMPTY; - } - - rect = rect || new math.Rectangle(0, 0, 1, 1); - - rect.x = this.minX; - rect.y = this.minY; - rect.width = this.maxX - this.minX; - rect.height = this.maxY - this.minY; - - return rect; -}; - -/** - * This function should be inlined when its possible. - * - * @param {PIXI.Point} point - The point to add. - */ -Bounds.prototype.addPoint = function addPoint (point) -{ - this.minX = Math.min(this.minX, point.x); - this.maxX = Math.max(this.maxX, point.x); - this.minY = Math.min(this.minY, point.y); - this.maxY = Math.max(this.maxY, point.y); -}; - -/** - * Adds a quad, not transformed - * - * @param {Float32Array} vertices - The verts to add. - */ -Bounds.prototype.addQuad = function addQuad (vertices) -{ - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - var x = vertices[0]; - var y = vertices[1]; - - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = vertices[2]; - y = vertices[3]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = vertices[4]; - y = vertices[5]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = vertices[6]; - y = vertices[7]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; -}; - -/** - * Adds sprite frame, transformed. - * - * @param {PIXI.Transform} transform - transform to apply - * @param {number} x0 - left X of frame - * @param {number} y0 - top Y of frame - * @param {number} x1 - right X of frame - * @param {number} y1 - bottom Y of frame - */ -Bounds.prototype.addFrame = function addFrame (transform, x0, y0, x1, y1) -{ - this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1); -}; - -/** - * Adds sprite frame, multiplied by matrix - * - * @param {PIXI.Matrix} matrix - matrix to apply - * @param {number} x0 - left X of frame - * @param {number} y0 - top Y of frame - * @param {number} x1 - right X of frame - * @param {number} y1 - bottom Y of frame - */ -Bounds.prototype.addFrameMatrix = function addFrameMatrix (matrix, x0, y0, x1, y1) -{ - var a = matrix.a; - var b = matrix.b; - var c = matrix.c; - var d = matrix.d; - var tx = matrix.tx; - var ty = matrix.ty; - - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - var x = (a * x0) + (c * y0) + tx; - var y = (b * x0) + (d * y0) + ty; - - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = (a * x1) + (c * y0) + tx; - y = (b * x1) + (d * y0) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = (a * x0) + (c * y1) + tx; - y = (b * x0) + (d * y1) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - x = (a * x1) + (c * y1) + tx; - y = (b * x1) + (d * y1) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; -}; - -/** - * Adds screen vertices from array - * - * @param {Float32Array} vertexData - calculated vertices - * @param {number} beginOffset - begin offset - * @param {number} endOffset - end offset, excluded - */ -Bounds.prototype.addVertexData = function addVertexData (vertexData, beginOffset, endOffset) -{ - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - for (var i = beginOffset; i < endOffset; i += 2) - { - var x = vertexData[i]; - var y = vertexData[i + 1]; - - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - } - - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; -}; - -/** - * Add an array of mesh vertices - * - * @param {PIXI.Transform} transform - mesh transform - * @param {Float32Array} vertices - mesh coordinates in array - * @param {number} beginOffset - begin offset - * @param {number} endOffset - end offset, excluded - */ -Bounds.prototype.addVertices = function addVertices (transform, vertices, beginOffset, endOffset) -{ - this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset); -}; - -/** - * Add an array of mesh vertices - * - * @param {PIXI.Matrix} matrix - mesh matrix - * @param {Float32Array} vertices - mesh coordinates in array - * @param {number} beginOffset - begin offset - * @param {number} endOffset - end offset, excluded - * @param {number} [padX] - x padding - * @param {number} [padY] - y padding - */ -Bounds.prototype.addVerticesMatrix = function addVerticesMatrix (matrix, vertices, beginOffset, endOffset, padX, padY) -{ - var a = matrix.a; - var b = matrix.b; - var c = matrix.c; - var d = matrix.d; - var tx = matrix.tx; - var ty = matrix.ty; - - padX = padX || 0; - padY = padY || 0; - - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - for (var i = beginOffset; i < endOffset; i += 2) - { - var rawX = vertices[i]; - var rawY = vertices[i + 1]; - var x = (a * rawX) + (c * rawY) + tx; - var y = (d * rawY) + (b * rawX) + ty; - - minX = Math.min(minX, x - padX); - maxX = Math.max(maxX, x + padX); - minY = Math.min(minY, y - padY); - maxY = Math.max(maxY, y + padY); - } - - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; -}; - -/** - * Adds other Bounds - * - * @param {PIXI.Bounds} bounds - TODO - */ -Bounds.prototype.addBounds = function addBounds (bounds) -{ - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - this.minX = bounds.minX < minX ? bounds.minX : minX; - this.minY = bounds.minY < minY ? bounds.minY : minY; - this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; - this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; -}; - -/** - * Adds other Bounds, masked with Bounds - * - * @param {PIXI.Bounds} bounds - TODO - * @param {PIXI.Bounds} mask - TODO - */ -Bounds.prototype.addBoundsMask = function addBoundsMask (bounds, mask) -{ - var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; - var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; - var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; - var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; - - if (_minX <= _maxX && _minY <= _maxY) - { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - this.minX = _minX < minX ? _minX : minX; - this.minY = _minY < minY ? _minY : minY; - this.maxX = _maxX > maxX ? _maxX : maxX; - this.maxY = _maxY > maxY ? _maxY : maxY; - } -}; - -/** - * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty - * - * @param {PIXI.Bounds} bounds other bounds - * @param {PIXI.Matrix} matrix multiplicator - */ -Bounds.prototype.addBoundsMatrix = function addBoundsMatrix (bounds, matrix) -{ - this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); -}; - -/** - * Adds other Bounds, masked with Rectangle - * - * @param {PIXI.Bounds} bounds - TODO - * @param {PIXI.Rectangle} area - TODO - */ -Bounds.prototype.addBoundsArea = function addBoundsArea (bounds, area) -{ - var _minX = bounds.minX > area.x ? bounds.minX : area.x; - var _minY = bounds.minY > area.y ? bounds.minY : area.y; - var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width); - var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height); - - if (_minX <= _maxX && _minY <= _maxY) - { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - - this.minX = _minX < minX ? _minX : minX; - this.minY = _minY < minY ? _minY : minY; - this.maxX = _maxX > maxX ? _maxX : maxX; - this.maxY = _maxY > maxY ? _maxY : maxY; - } -}; - -/** - * Pads bounds object, making it grow in all directions. - * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. - * - * @param {number} [paddingX=0] - The horizontal padding amount. - * @param {number} [paddingY=0] - The vertical padding amount. - */ -Bounds.prototype.pad = function pad (paddingX, paddingY) -{ - paddingX = paddingX || 0; - paddingY = paddingY || ((paddingY !== 0) ? paddingX : 0); - - if (!this.isEmpty()) - { - this.minX -= paddingX; - this.maxX += paddingX; - this.minY -= paddingY; - this.maxY += paddingY; - } -}; - -/** - * Adds padded frame. (x0, y0) should be strictly less than (x1, y1) - * - * @param {number} x0 - left X of frame - * @param {number} y0 - top Y of frame - * @param {number} x1 - right X of frame - * @param {number} y1 - bottom Y of frame - * @param {number} padX - padding X - * @param {number} padY - padding Y - */ -Bounds.prototype.addFramePad = function addFramePad (x0, y0, x1, y1, padX, padY) -{ - x0 -= padX; - y0 -= padY; - x1 += padX; - y1 += padY; - - this.minX = this.minX < x0 ? this.minX : x0; - this.maxX = this.maxX > x1 ? this.maxX : x1; - this.minY = this.minY < y0 ? this.minY : y0; - this.maxY = this.maxY > y1 ? this.maxY : y1; -}; - -// _tempDisplayObjectParent = new DisplayObject(); - -/** - * The base class for all objects that are rendered on the screen. - * - * This is an abstract class and should not be used on its own; rather it should be extended. - * - * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI - */ -var DisplayObject = /*@__PURE__*/(function (EventEmitter) { - function DisplayObject() - { - EventEmitter.call(this); - - this.tempDisplayObjectParent = null; - - // TODO: need to create Transform from factory + _this.colors = []; /** - * World transform and local transform of this object. - * This will become read-only later, please do not assign anything there unless you know what are you doing. + * The UVs collection * - * @member {PIXI.Transform} + * @member {number[]} + * @protected */ - this.transform = new math.Transform(); - + _this.uvs = []; /** - * The opacity of the object. + * The indices of the vertices * - * @member {number} + * @member {number[]} + * @protected */ - this.alpha = 1; - + _this.indices = []; /** - * The visibility of the object. If false the object will not be drawn, and - * the updateTransform function will not be called. - * - * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually. + * Reference to the texture IDs. * - * @member {boolean} + * @member {number[]} + * @protected */ - this.visible = true; - + _this.textureIds = []; /** - * Can this object be rendered, if false the object will not be drawn but the updateTransform - * methods will still be called. - * - * Only affects recursive calls from parent. You can ask for bounds manually. + * The collection of drawn shapes. * - * @member {boolean} + * @member {PIXI.GraphicsData[]} + * @protected */ - this.renderable = true; - + _this.graphicsData = []; /** - * The display object container that contains this display object. + * Used to detect if the graphics object has changed. * - * @member {PIXI.Container} - * @readonly + * @member {number} + * @protected */ - this.parent = null; - + _this.dirty = 0; /** - * The multiplied alpha of the displayObject. + * Batches need to regenerated if the geometry is updated. * * @member {number} - * @readonly + * @protected */ - this.worldAlpha = 1; - + _this.batchDirty = -1; /** - * Which index in the children array the display component was before the previous zIndex sort. - * Used by containers to help sort objects with the same zIndex, by using previous array index as the decider. + * Used to check if the cache is dirty. * * @member {number} * @protected */ - this._lastSortedIndex = 0; - + _this.cacheDirty = -1; /** - * The zIndex of the displayObject. - * A higher value will mean it will be rendered on top of other displayObjects within the same container. + * Used to detect if we cleared the graphicsData. * * @member {number} + * @default 0 * @protected */ - this._zIndex = 0; - + _this.clearDirty = 0; /** - * The area the filter is applied to. This is used as more of an optimization - * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle. - * - * Also works as an interaction mask. + * List of current draw calls drived from the batches. * - * @member {?PIXI.Rectangle} + * @member {object[]} + * @protected */ - this.filterArea = null; - + _this.drawCalls = []; /** - * Sets the filters for the displayObject. - * * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. - * To remove filters simply set this property to `'null'`. + * Intermediate abstract format sent to batch system. + * Can be converted to drawCalls or to batchable objects. * - * @member {?PIXI.Filter[]} + * @member {PIXI.graphicsUtils.BatchPart[]} + * @protected */ - this.filters = null; - this._enabledFilters = null; - + _this.batches = []; /** - * The bounds object, this is used to calculate and store the bounds of the displayObject. + * Index of the last batched shape in the stack of calls. * - * @member {PIXI.Bounds} + * @member {number} * @protected */ - this._bounds = new Bounds(); - this._boundsID = 0; - this._lastBoundsID = -1; - this._boundsRect = null; - this._localBoundsRect = null; - + _this.shapeIndex = 0; /** - * The original, cached mask of the object. + * Cached bounds. * - * @member {PIXI.Graphics|PIXI.Sprite|null} + * @member {PIXI.Bounds} * @protected */ - this._mask = null; - + _this._bounds = new display.Bounds(); /** - * Fired when this DisplayObject is added to a Container. + * The bounds dirty flag. * - * @event PIXI.DisplayObject#added - * @param {PIXI.Container} container - The container added to. + * @member {number} + * @protected */ - + _this.boundsDirty = -1; /** - * Fired when this DisplayObject is removed from a Container. + * Padding to add to the bounds. * - * @event PIXI.DisplayObject#removed - * @param {PIXI.Container} container - The container removed from. + * @member {number} + * @default 0 */ - + _this.boundsPadding = 0; + _this.batchable = false; + _this.indicesUint16 = null; + _this.uvsFloat32 = null; /** - * If the object has been destroyed via destroy(). If true, it should not be used. + * Minimal distance between points that are considered different. + * Affects line tesselation. * - * @member {boolean} - * @protected - */ - this._destroyed = false; - - /** - * used to fast check if a sprite is.. a sprite! - * @member {boolean} + * @member {number} */ - this.isSprite = false; - + _this.closePointEps = 1e-4; + return _this; + } + Object.defineProperty(GraphicsGeometry.prototype, "bounds", { /** - * Does any other displayObject use this object as a mask? - * @member {boolean} + * Get the current bounds of the graphic geometry. + * + * @member {PIXI.Bounds} + * @readonly */ - this.isMask = false; - } - - if ( EventEmitter ) DisplayObject.__proto__ = EventEmitter; - DisplayObject.prototype = Object.create( EventEmitter && EventEmitter.prototype ); - DisplayObject.prototype.constructor = DisplayObject; - - var prototypeAccessors = { _tempDisplayObjectParent: { configurable: true },x: { configurable: true },y: { configurable: true },worldTransform: { configurable: true },localTransform: { configurable: true },position: { configurable: true },scale: { configurable: true },pivot: { configurable: true },skew: { configurable: true },rotation: { configurable: true },angle: { configurable: true },zIndex: { configurable: true },worldVisible: { configurable: true },mask: { configurable: true } }; - + get: function () { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.calculateBounds(); + } + return this._bounds; + }, + enumerable: false, + configurable: true + }); /** - * @protected - * @member {PIXI.DisplayObject} + * Call if you changed graphicsData manually. + * Empties all batch buffers. */ - DisplayObject.mixin = function mixin (source) - { - // in ES8/ES2017, this would be really easy: - // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - - // get all the enumerable property keys - var keys = Object.keys(source); - - // loop through properties - for (var i = 0; i < keys.length; ++i) - { - var propertyName = keys[i]; - - // Set the property using the property descriptor - this works for accessors and normal value properties - Object.defineProperty( - DisplayObject.prototype, - propertyName, - Object.getOwnPropertyDescriptor(source, propertyName) - ); + GraphicsGeometry.prototype.invalidate = function () { + this.boundsDirty = -1; + this.dirty++; + this.batchDirty++; + this.shapeIndex = 0; + this.points.length = 0; + this.colors.length = 0; + this.uvs.length = 0; + this.indices.length = 0; + this.textureIds.length = 0; + for (var i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); } - }; - - prototypeAccessors._tempDisplayObjectParent.get = function () - { - if (this.tempDisplayObjectParent === null) - { - this.tempDisplayObjectParent = new DisplayObject(); + this.drawCalls.length = 0; + for (var i = 0; i < this.batches.length; i++) { + var batchPart = this.batches[i]; + batchPart.reset(); + BATCH_POOL.push(batchPart); } - - return this.tempDisplayObjectParent; + this.batches.length = 0; }; - /** - * Updates the object transform for rendering. + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. * - * TODO - Optimization pass! + * @return {PIXI.GraphicsGeometry} This GraphicsGeometry object. Good for chaining method calls */ - DisplayObject.prototype.updateTransform = function updateTransform () - { - this.transform.updateTransform(this.parent.transform); - // multiply the alphas.. - this.worldAlpha = this.alpha * this.parent.worldAlpha; - - this._bounds.updateID++; + GraphicsGeometry.prototype.clear = function () { + if (this.graphicsData.length > 0) { + this.invalidate(); + this.clearDirty++; + this.graphicsData.length = 0; + } + return this; }; - /** - * Recursively updates transform of all objects from the root to this one - * internal function for toLocal() + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param {PIXI.FillStyle} fillStyle - Defines style of the fill. + * @param {PIXI.LineStyle} lineStyle - Defines style of the lines. + * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape. + * @return {PIXI.GraphicsGeometry} Returns geometry for chaining. */ - DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform () - { - if (this.parent) - { - this.parent._recursivePostUpdateTransform(); - this.transform.updateTransform(this.parent.transform); - } - else - { - this.transform.updateTransform(this._tempDisplayObjectParent.transform); - } + GraphicsGeometry.prototype.drawShape = function (shape, fillStyle, lineStyle, matrix) { + if (fillStyle === void 0) { fillStyle = null; } + if (lineStyle === void 0) { lineStyle = null; } + if (matrix === void 0) { matrix = null; } + var data = new GraphicsData(shape, fillStyle, lineStyle, matrix); + this.graphicsData.push(data); + this.dirty++; + return this; }; - /** - * Retrieves the bounds of the displayObject as a rectangle object. + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. * - * @param {boolean} [skipUpdate] - Setting to `true` will stop the transforms of the scene graph from - * being updated. This means the calculation returned MAY be out of date BUT will give you a - * nice performance boost. - * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. - * @return {PIXI.Rectangle} The rectangular bounding area. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape. + * @return {PIXI.GraphicsGeometry} Returns geometry for chaining. */ - DisplayObject.prototype.getBounds = function getBounds (skipUpdate, rect) - { - if (!skipUpdate) - { - if (!this.parent) - { - this.parent = this._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } - else - { - this._recursivePostUpdateTransform(); - this.updateTransform(); - } - } - - if (this._boundsID !== this._lastBoundsID) - { - this.calculateBounds(); - this._lastBoundsID = this._boundsID; - } - - if (!rect) - { - if (!this._boundsRect) - { - this._boundsRect = new math.Rectangle(); - } - - rect = this._boundsRect; + GraphicsGeometry.prototype.drawHole = function (shape, matrix) { + if (matrix === void 0) { matrix = null; } + if (!this.graphicsData.length) { + return null; } - - return this._bounds.getRectangle(rect); + var data = new GraphicsData(shape, null, null, matrix); + var lastShape = this.graphicsData[this.graphicsData.length - 1]; + data.lineStyle = lastShape.lineStyle; + lastShape.holes.push(data); + this.dirty++; + return this; }; - /** - * Retrieves the local bounds of the displayObject as a rectangle object. + * Destroys the GraphicsGeometry object. * - * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. - * @return {PIXI.Rectangle} The rectangular bounding area. */ - DisplayObject.prototype.getLocalBounds = function getLocalBounds (rect) - { - var transformRef = this.transform; - var parentRef = this.parent; - - this.parent = null; - this.transform = this._tempDisplayObjectParent.transform; - - if (!rect) - { - if (!this._localBoundsRect) - { - this._localBoundsRect = new math.Rectangle(); - } - - rect = this._localBoundsRect; + GraphicsGeometry.prototype.destroy = function () { + _super.prototype.destroy.call(this); + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); } - - var bounds = this.getBounds(false, rect); - - this.parent = parentRef; - this.transform = transformRef; - - return bounds; + this.points.length = 0; + this.points = null; + this.colors.length = 0; + this.colors = null; + this.uvs.length = 0; + this.uvs = null; + this.indices.length = 0; + this.indices = null; + this.indexBuffer.destroy(); + this.indexBuffer = null; + this.graphicsData.length = 0; + this.graphicsData = null; + this.drawCalls.length = 0; + this.drawCalls = null; + this.batches.length = 0; + this.batches = null; + this._bounds = null; }; - /** - * Calculates the global position of the display object. + * Check to see if a point is contained within this geometry. * - * @param {PIXI.IPoint} position - The world origin to calculate from. - * @param {PIXI.IPoint} [point] - A Point object in which to store the value, optional - * (otherwise will create a new Point). - * @param {boolean} [skipUpdate=false] - Should we skip the update transform. - * @return {PIXI.IPoint} A point object representing the position of this object. + * @param {PIXI.IPointData} point - Point to check if it's contained. + * @return {Boolean} `true` if the point is contained within geometry. */ - DisplayObject.prototype.toGlobal = function toGlobal (position, point, skipUpdate) - { - if ( skipUpdate === void 0 ) skipUpdate = false; - - if (!skipUpdate) - { - this._recursivePostUpdateTransform(); - - // this parent check is for just in case the item is a root object. - // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly - // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) - if (!this.parent) - { - this.parent = this._tempDisplayObjectParent; - this.displayObjectUpdateTransform(); - this.parent = null; + GraphicsGeometry.prototype.containsPoint = function (point) { + var graphicsData = this.graphicsData; + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + if (!data.fillStyle.visible) { + continue; } - else - { - this.displayObjectUpdateTransform(); + // only deal with fills.. + if (data.shape) { + if (data.matrix) { + data.matrix.applyInverse(point, tmpPoint); + } + else { + tmpPoint.copyFrom(point); + } + if (data.shape.contains(tmpPoint.x, tmpPoint.y)) { + var hitHole = false; + if (data.holes) { + for (var i_1 = 0; i_1 < data.holes.length; i_1++) { + var hole = data.holes[i_1]; + if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) { + hitHole = true; + break; + } + } + } + if (!hitHole) { + return true; + } + } } } - - // don't need to update the lot - return this.worldTransform.apply(position, point); + return false; }; - /** - * Calculates the local position of the display object relative to another point. + * Generates intermediate batch data. Either gets converted to drawCalls + * or used to convert to batch objects directly by the Graphics object. * - * @param {PIXI.IPoint} position - The world origin to calculate from. - * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from. - * @param {PIXI.IPoint} [point] - A Point object in which to store the value, optional - * (otherwise will create a new Point). - * @param {boolean} [skipUpdate=false] - Should we skip the update transform - * @return {PIXI.IPoint} A point object representing the position of this object + * @param {boolean} [aloow32Indices] - Allow using 32-bit indices for preventings artefacts when more that 65535 vertices */ - DisplayObject.prototype.toLocal = function toLocal (position, from, point, skipUpdate) - { - if (from) - { - position = from.toGlobal(position, point, skipUpdate); + GraphicsGeometry.prototype.updateBatches = function (allow32Indices) { + if (!this.graphicsData.length) { + this.batchable = true; + return; } - - if (!skipUpdate) - { - this._recursivePostUpdateTransform(); - - // this parent check is for just in case the item is a root object. - // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly - // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) - if (!this.parent) - { - this.parent = this._tempDisplayObjectParent; - this.displayObjectUpdateTransform(); - this.parent = null; + if (!this.validateBatching()) { + return; + } + this.cacheDirty = this.dirty; + var uvs = this.uvs; + var graphicsData = this.graphicsData; + var batchPart = null; + var currentStyle = null; + if (this.batches.length > 0) { + batchPart = this.batches[this.batches.length - 1]; + currentStyle = batchPart.style; + } + for (var i = this.shapeIndex; i < graphicsData.length; i++) { + this.shapeIndex++; + var data = graphicsData[i]; + var fillStyle = data.fillStyle; + var lineStyle = data.lineStyle; + var command = FILL_COMMANDS[data.type]; + // build out the shapes points.. + command.build(data); + if (data.matrix) { + this.transformPoints(data.points, data.matrix); } - else - { - this.displayObjectUpdateTransform(); + for (var j = 0; j < 2; j++) { + var style = (j === 0) ? fillStyle : lineStyle; + if (!style.visible) + { continue; } + var nextTexture = style.texture.baseTexture; + var index_1 = this.indices.length; + var attribIndex = this.points.length / 2; + nextTexture.wrapMode = constants.WRAP_MODES.REPEAT; + if (j === 0) { + this.processFill(data); + } + else { + this.processLine(data); + } + var size = (this.points.length / 2) - attribIndex; + if (size === 0) + { continue; } + // close batch if style is different + if (batchPart && !this._compareStyles(currentStyle, style)) { + batchPart.end(index_1, attribIndex); + batchPart = null; + } + // spawn new batch if its first batch or previous was closed + if (!batchPart) { + batchPart = BATCH_POOL.pop() || new BatchPart(); + batchPart.begin(style, index_1, attribIndex); + this.batches.push(batchPart); + currentStyle = style; + } + this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix); } } - - // simply apply the matrix.. - return this.worldTransform.applyInverse(position, point); + var index = this.indices.length; + var attrib = this.points.length / 2; + if (batchPart) { + batchPart.end(index, attrib); + } + if (this.batches.length === 0) { + // there are no visible styles in GraphicsData + // its possible that someone wants Graphics just for the bounds + this.batchable = true; + return; + } + // prevent allocation when length is same as buffer + if (this.indicesUint16 && this.indices.length === this.indicesUint16.length) { + this.indicesUint16.set(this.indices); + } + else { + var need32 = attrib > 0xffff && allow32Indices; + this.indicesUint16 = need32 ? new Uint32Array(this.indices) : new Uint16Array(this.indices); + } + // TODO make this a const.. + this.batchable = this.isBatchable(); + if (this.batchable) { + this.packBatches(); + } + else { + this.buildDrawCalls(); + } }; - /** - * Renders the object using the WebGL renderer. + * Affinity check * - * @param {PIXI.Renderer} renderer - The renderer. + * @param {PIXI.FillStyle | PIXI.LineStyle} styleA + * @param {PIXI.FillStyle | PIXI.LineStyle} styleB */ - DisplayObject.prototype.render = function render (renderer) // eslint-disable-line no-unused-vars - { - // OVERWRITE; + GraphicsGeometry.prototype._compareStyles = function (styleA, styleB) { + if (!styleA || !styleB) { + return false; + } + if (styleA.texture.baseTexture !== styleB.texture.baseTexture) { + return false; + } + if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) { + return false; + } + if (!!styleA.native !== !!styleB.native) { + return false; + } + return true; }; - /** - * Set the parent Container of this DisplayObject. + * Test geometry for batching process. * - * @param {PIXI.Container} container - The Container to add this DisplayObject to. - * @return {PIXI.Container} The Container that this DisplayObject was added to. + * @protected */ - DisplayObject.prototype.setParent = function setParent (container) - { - if (!container || !container.addChild) - { - throw new Error('setParent: Argument must be a Container'); + GraphicsGeometry.prototype.validateBatching = function () { + if (this.dirty === this.cacheDirty || !this.graphicsData.length) { + return false; } - - container.addChild(this); - - return container; + for (var i = 0, l = this.graphicsData.length; i < l; i++) { + var data = this.graphicsData[i]; + var fill = data.fillStyle; + var line = data.lineStyle; + if (fill && !fill.texture.baseTexture.valid) + { return false; } + if (line && !line.texture.baseTexture.valid) + { return false; } + } + return true; }; - /** - * Convenience function to set the position, scale, skew and pivot at once. + * Offset the indices so that it works with the batcher. * - * @param {number} [x=0] - The X position - * @param {number} [y=0] - The Y position - * @param {number} [scaleX=1] - The X scale value - * @param {number} [scaleY=1] - The Y scale value - * @param {number} [rotation=0] - The rotation - * @param {number} [skewX=0] - The X skew value - * @param {number} [skewY=0] - The Y skew value - * @param {number} [pivotX=0] - The X pivot value - * @param {number} [pivotY=0] - The Y pivot value - * @return {PIXI.DisplayObject} The DisplayObject instance + * @protected */ - DisplayObject.prototype.setTransform = function setTransform (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) - { - if ( x === void 0 ) x = 0; - if ( y === void 0 ) y = 0; - if ( scaleX === void 0 ) scaleX = 1; - if ( scaleY === void 0 ) scaleY = 1; - if ( rotation === void 0 ) rotation = 0; - if ( skewX === void 0 ) skewX = 0; - if ( skewY === void 0 ) skewY = 0; - if ( pivotX === void 0 ) pivotX = 0; - if ( pivotY === void 0 ) pivotY = 0; - - this.position.x = x; - this.position.y = y; - this.scale.x = !scaleX ? 1 : scaleX; - this.scale.y = !scaleY ? 1 : scaleY; - this.rotation = rotation; - this.skew.x = skewX; - this.skew.y = skewY; - this.pivot.x = pivotX; - this.pivot.y = pivotY; - - return this; + GraphicsGeometry.prototype.packBatches = function () { + this.batchDirty++; + this.uvsFloat32 = new Float32Array(this.uvs); + var batches = this.batches; + for (var i = 0, l = batches.length; i < l; i++) { + var batch = batches[i]; + for (var j = 0; j < batch.size; j++) { + var index = batch.start + j; + this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart; + } + } }; - /** - * Base destroy method for generic display objects. This will automatically - * remove the display object from its parent Container as well as remove - * all current event listeners and internal references. Do not use a DisplayObject - * after calling `destroy()`. + * Checks to see if this graphics geometry can be batched. + * Currently it needs to be small enough and not contain any native lines. * + * @protected */ - DisplayObject.prototype.destroy = function destroy () - { - this.removeAllListeners(); - if (this.parent) - { - this.parent.removeChild(this); + GraphicsGeometry.prototype.isBatchable = function () { + // prevent heavy mesh batching + if (this.points.length > 0xffff * 2) { + return false; } - this.transform = null; - - this.parent = null; - this._bounds = null; - this._currentBounds = null; - this._mask = null; - - this.filters = null; - this.filterArea = null; - this.hitArea = null; - - this.interactive = false; - this.interactiveChildren = false; - - this._destroyed = true; + var batches = this.batches; + for (var i = 0; i < batches.length; i++) { + if (batches[i].style.native) { + return false; + } + } + return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2); }; - /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. - * An alias to position.x + * Converts intermediate batches data to drawCalls. * - * @member {number} + * @protected */ - prototypeAccessors.x.get = function () - { - return this.position.x; - }; - - prototypeAccessors.x.set = function (value) // eslint-disable-line require-jsdoc - { - this.transform.position.x = value; + GraphicsGeometry.prototype.buildDrawCalls = function () { + var TICK = ++core.BaseTexture._globalBatch; + for (var i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); + } + this.drawCalls.length = 0; + var colors = this.colors; + var textureIds = this.textureIds; + var currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new core.BatchDrawCall(); + currentGroup.texArray = new core.BatchTextureArray(); + } + currentGroup.texArray.count = 0; + currentGroup.start = 0; + currentGroup.size = 0; + currentGroup.type = constants.DRAW_MODES.TRIANGLES; + var textureCount = 0; + var currentTexture = null; + var textureId = 0; + var native = false; + var drawMode = constants.DRAW_MODES.TRIANGLES; + var index = 0; + this.drawCalls.push(currentGroup); + // TODO - this can be simplified + for (var i = 0; i < this.batches.length; i++) { + var data = this.batches[i]; + // TODO add some full on MAX_TEXTURE CODE.. + var MAX_TEXTURES = 8; + // Forced cast for checking `native` without errors + var style = data.style; + var nextTexture = style.texture.baseTexture; + if (native !== !!style.native) { + native = !!style.native; + drawMode = native ? constants.DRAW_MODES.LINES : constants.DRAW_MODES.TRIANGLES; + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + if (nextTexture._batchEnabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + textureCount = 0; + if (currentGroup.size > 0) { + currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new core.BatchDrawCall(); + currentGroup.texArray = new core.BatchTextureArray(); + } + this.drawCalls.push(currentGroup); + } + currentGroup.start = index; + currentGroup.size = 0; + currentGroup.texArray.count = 0; + currentGroup.type = drawMode; + } + // TODO add this to the render part.. + // Hack! Because texture has protected `touched` + nextTexture.touched = 1; // touch; + nextTexture._batchEnabled = TICK; + nextTexture._batchLocation = textureCount; + nextTexture.wrapMode = 10497; + currentGroup.texArray.elements[currentGroup.texArray.count++] = nextTexture; + textureCount++; + } + } + currentGroup.size += data.size; + index += data.size; + textureId = nextTexture._batchLocation; + this.addColors(colors, style.color, style.alpha, data.attribSize); + this.addTextureIds(textureIds, textureId, data.attribSize); + } + core.BaseTexture._globalBatch = TICK; + // upload.. + // merge for now! + this.packAttributes(); }; - /** - * The position of the displayObject on the y axis relative to the local coordinates of the parent. - * An alias to position.y + * Packs attributes to single buffer. * - * @member {number} + * @protected */ - prototypeAccessors.y.get = function () - { - return this.position.y; - }; - - prototypeAccessors.y.set = function (value) // eslint-disable-line require-jsdoc - { - this.transform.position.y = value; + GraphicsGeometry.prototype.packAttributes = function () { + var verts = this.points; + var uvs = this.uvs; + var colors = this.colors; + var textureIds = this.textureIds; + // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes + var glPoints = new ArrayBuffer(verts.length * 3 * 4); + var f32 = new Float32Array(glPoints); + var u32 = new Uint32Array(glPoints); + var p = 0; + for (var i = 0; i < verts.length / 2; i++) { + f32[p++] = verts[i * 2]; + f32[p++] = verts[(i * 2) + 1]; + f32[p++] = uvs[i * 2]; + f32[p++] = uvs[(i * 2) + 1]; + u32[p++] = colors[i]; + f32[p++] = textureIds[i]; + } + this._buffer.update(glPoints); + this._indexBuffer.update(this.indicesUint16); }; - /** - * Current transform of the object based on world (parent) factors. + * Process fill part of Graphics. * - * @member {PIXI.Matrix} - * @readonly + * @param {PIXI.GraphicsData} data + * @protected */ - prototypeAccessors.worldTransform.get = function () - { - return this.transform.worldTransform; + GraphicsGeometry.prototype.processFill = function (data) { + if (data.holes.length) { + this.processHoles(data.holes); + buildPoly.triangulate(data, this); + } + else { + var command = FILL_COMMANDS[data.type]; + command.triangulate(data, this); + } }; - /** - * Current transform of the object based on local factors: position, scale, other stuff. + * Process line part of Graphics. * - * @member {PIXI.Matrix} - * @readonly + * @param {PIXI.GraphicsData} data + * @protected */ - prototypeAccessors.localTransform.get = function () - { - return this.transform.localTransform; + GraphicsGeometry.prototype.processLine = function (data) { + buildLine(data, this); + for (var i = 0; i < data.holes.length; i++) { + buildLine(data.holes[i], this); + } }; - /** - * The coordinate of the object relative to the local coordinates of the parent. - * Assignment by value since pixi-v4. + * Process the holes data. * - * @member {PIXI.IPoint} + * @param {PIXI.GraphicsData[]} holes - Holes to render + * @protected */ - prototypeAccessors.position.get = function () - { - return this.transform.position; - }; - - prototypeAccessors.position.set = function (value) // eslint-disable-line require-jsdoc - { - this.transform.position.copyFrom(value); + GraphicsGeometry.prototype.processHoles = function (holes) { + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + var command = FILL_COMMANDS[hole.type]; + command.build(hole); + if (hole.matrix) { + this.transformPoints(hole.points, hole.matrix); + } + } }; - /** - * The scale factor of the object. - * Assignment by value since pixi-v4. + * Update the local bounds of the object. Expensive to use performance-wise. * - * @member {PIXI.IPoint} + * @protected */ - prototypeAccessors.scale.get = function () - { - return this.transform.scale; - }; - - prototypeAccessors.scale.set = function (value) // eslint-disable-line require-jsdoc - { - this.transform.scale.copyFrom(value); + GraphicsGeometry.prototype.calculateBounds = function () { + var bounds = this._bounds; + var sequenceBounds = tmpBounds; + var curMatrix = math.Matrix.IDENTITY; + this._bounds.clear(); + sequenceBounds.clear(); + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var shape = data.shape; + var type = data.type; + var lineStyle = data.lineStyle; + var nextMatrix = data.matrix || math.Matrix.IDENTITY; + var lineWidth = 0.0; + if (lineStyle && lineStyle.visible) { + var alignment = lineStyle.alignment; + lineWidth = lineStyle.width; + if (type === math.SHAPES.POLY) { + lineWidth = lineWidth * (0.5 + Math.abs(0.5 - alignment)); + } + else { + lineWidth = lineWidth * Math.max(0, alignment); + } + } + if (curMatrix !== nextMatrix) { + if (!sequenceBounds.isEmpty()) { + bounds.addBoundsMatrix(sequenceBounds, curMatrix); + sequenceBounds.clear(); + } + curMatrix = nextMatrix; + } + if (type === math.SHAPES.RECT || type === math.SHAPES.RREC) { + var rect = shape; + sequenceBounds.addFramePad(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, lineWidth, lineWidth); + } + else if (type === math.SHAPES.CIRC) { + var circle = shape; + sequenceBounds.addFramePad(circle.x, circle.y, circle.x, circle.y, circle.radius + lineWidth, circle.radius + lineWidth); + } + else if (type === math.SHAPES.ELIP) { + var ellipse = shape; + sequenceBounds.addFramePad(ellipse.x, ellipse.y, ellipse.x, ellipse.y, ellipse.width + lineWidth, ellipse.height + lineWidth); + } + else { + var poly = shape; + // adding directly to the bounds + bounds.addVerticesMatrix(curMatrix, poly.points, 0, poly.points.length, lineWidth, lineWidth); + } + } + if (!sequenceBounds.isEmpty()) { + bounds.addBoundsMatrix(sequenceBounds, curMatrix); + } + bounds.pad(this.boundsPadding, this.boundsPadding); }; - /** - * The pivot point of the displayObject that it rotates around. - * Assignment by value since pixi-v4. + * Transform points using matrix. * - * @member {PIXI.IPoint} + * @protected + * @param {number[]} points - Points to transform + * @param {PIXI.Matrix} matrix - Transform matrix */ - prototypeAccessors.pivot.get = function () - { - return this.transform.pivot; - }; - - prototypeAccessors.pivot.set = function (value) // eslint-disable-line require-jsdoc - { - this.transform.pivot.copyFrom(value); + GraphicsGeometry.prototype.transformPoints = function (points, matrix) { + for (var i = 0; i < points.length / 2; i++) { + var x = points[(i * 2)]; + var y = points[(i * 2) + 1]; + points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx; + points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty; + } }; - /** - * The skew factor for the object in radians. - * Assignment by value since pixi-v4. + * Add colors. * - * @member {PIXI.ObservablePoint} + * @protected + * @param {number[]} colors - List of colors to add to + * @param {number} color - Color to add + * @param {number} alpha - Alpha to use + * @param {number} size - Number of colors to add */ - prototypeAccessors.skew.get = function () - { - return this.transform.skew; - }; - - prototypeAccessors.skew.set = function (value) // eslint-disable-line require-jsdoc - { - this.transform.skew.copyFrom(value); + GraphicsGeometry.prototype.addColors = function (colors, color, alpha, size) { + // TODO use the premultiply bits Ivan added + var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16); + var rgba = utils.premultiplyTint(rgb, alpha); + while (size-- > 0) { + colors.push(rgba); + } }; - /** - * The rotation of the object in radians. - * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + * Add texture id that the shader/fragment wants to use. * - * @member {number} + * @protected + * @param {number[]} textureIds + * @param {number} id + * @param {number} size */ - prototypeAccessors.rotation.get = function () - { - return this.transform.rotation; - }; - - prototypeAccessors.rotation.set = function (value) // eslint-disable-line require-jsdoc - { - this.transform.rotation = value; + GraphicsGeometry.prototype.addTextureIds = function (textureIds, id, size) { + while (size-- > 0) { + textureIds.push(id); + } }; - /** - * The angle of the object in degrees. - * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + * Generates the UVs for a shape. * - * @member {number} + * @protected + * @param {number[]} verts - Vertices + * @param {number[]} uvs - UVs + * @param {PIXI.Texture} texture - Reference to Texture + * @param {number} start - Index buffer start index. + * @param {number} size - The size/length for index buffer. + * @param {PIXI.Matrix} [matrix] - Optional transform for all points. */ - prototypeAccessors.angle.get = function () - { - return this.transform.rotation * math.RAD_TO_DEG; - }; - - prototypeAccessors.angle.set = function (value) // eslint-disable-line require-jsdoc - { - this.transform.rotation = value * math.DEG_TO_RAD; + GraphicsGeometry.prototype.addUvs = function (verts, uvs, texture, start, size, matrix) { + if (matrix === void 0) { matrix = null; } + var index = 0; + var uvsStart = uvs.length; + var frame = texture.frame; + while (index < size) { + var x = verts[(start + index) * 2]; + var y = verts[((start + index) * 2) + 1]; + if (matrix) { + var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx; + y = (matrix.b * x) + (matrix.d * y) + matrix.ty; + x = nx; + } + index++; + uvs.push(x / frame.width, y / frame.height); + } + var baseTexture = texture.baseTexture; + if (frame.width < baseTexture.width + || frame.height < baseTexture.height) { + this.adjustUvs(uvs, texture, uvsStart, size); + } }; - /** - * The zIndex of the displayObject. - * If a container has the sortableChildren property set to true, children will be automatically - * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, - * and thus rendered on top of other displayObjects within the same container. - * - * @member {number} + * Modify uvs array according to position of texture region + * Does not work with rotated or trimmed textures + * + * @param {number[]} uvs - array + * @param {PIXI.Texture} texture - region + * @param {number} start - starting index for uvs + * @param {number} size - how many points to adjust */ - prototypeAccessors.zIndex.get = function () - { - return this._zIndex; - }; - - prototypeAccessors.zIndex.set = function (value) // eslint-disable-line require-jsdoc - { - this._zIndex = value; - if (this.parent) - { - this.parent.sortDirty = true; + GraphicsGeometry.prototype.adjustUvs = function (uvs, texture, start, size) { + var baseTexture = texture.baseTexture; + var eps = 1e-6; + var finish = start + (size * 2); + var frame = texture.frame; + var scaleX = frame.width / baseTexture.width; + var scaleY = frame.height / baseTexture.height; + var offsetX = frame.x / frame.width; + var offsetY = frame.y / frame.height; + var minX = Math.floor(uvs[start] + eps); + var minY = Math.floor(uvs[start + 1] + eps); + for (var i = start + 2; i < finish; i += 2) { + minX = Math.min(minX, Math.floor(uvs[i] + eps)); + minY = Math.min(minY, Math.floor(uvs[i + 1] + eps)); + } + offsetX -= minX; + offsetY -= minY; + for (var i = start; i < finish; i += 2) { + uvs[i] = (uvs[i] + offsetX) * scaleX; + uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY; } }; - /** - * Indicates if the object is globally visible. + * The maximum number of points to consider an object "batchable", + * able to be batched by the renderer's batch system. * - * @member {boolean} - * @readonly + * @memberof PIXI.GraphicsGeometry + * @static + * @member {number} BATCHABLE_SIZE + * @default 100 */ - prototypeAccessors.worldVisible.get = function () - { - var item = this; - - do - { - if (!item.visible) - { - return false; - } - - item = item.parent; - } while (item); - - return true; - }; + GraphicsGeometry.BATCHABLE_SIZE = 100; + return GraphicsGeometry; +}(core.BatchGeometry)); +/** + * Represents the line style for Graphics. + * @memberof PIXI + * @class + * @extends PIXI.FillStyle + */ +var LineStyle = /** @class */ (function (_super) { + __extends(LineStyle, _super); + function LineStyle() { + var _this = _super !== null && _super.apply(this, arguments) || this; + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.width = 0; + /** + * The alignment of any lines drawn (0.5 = middle, 1 = outer, 0 = inner). + * + * @member {number} + * @default 0.5 + */ + _this.alignment = 0.5; + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + * @default false + */ + _this.native = false; + /** + * Line cap style. + * + * @member {PIXI.LINE_CAP} + * @default PIXI.LINE_CAP.BUTT + */ + _this.cap = exports.LINE_CAP.BUTT; + /** + * Line join style. + * + * @member {PIXI.LINE_JOIN} + * @default PIXI.LINE_JOIN.MITER + */ + _this.join = exports.LINE_JOIN.MITER; + /** + * Miter limit. + * + * @member {number} + * @default 10 + */ + _this.miterLimit = 10; + return _this; + } /** - * Sets a mask for the displayObject. A mask is an object that limits the visibility of an - * object to the shape of the mask applied to it. In PixiJS a regular mask must be a - * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it - * utilities shape clipping. To remove a mask, set this property to `null`. - * - * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask. - * @example - * const graphics = new PIXI.Graphics(); - * graphics.beginFill(0xFF3300); - * graphics.drawRect(50, 250, 100, 100); - * graphics.endFill(); + * Clones the object * - * const sprite = new PIXI.Sprite(texture); - * sprite.mask = graphics; - * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. - * - * @member {PIXI.Graphics|PIXI.Sprite|null} + * @return {PIXI.LineStyle} */ - prototypeAccessors.mask.get = function () - { - return this._mask; + LineStyle.prototype.clone = function () { + var obj = new LineStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + obj.width = this.width; + obj.alignment = this.alignment; + obj.native = this.native; + obj.cap = this.cap; + obj.join = this.join; + obj.miterLimit = this.miterLimit; + return obj; }; - - prototypeAccessors.mask.set = function (value) // eslint-disable-line require-jsdoc - { - if (this._mask) - { - var maskObject = this._mask.maskObject || this._mask; - - maskObject.renderable = true; - maskObject.isMask = false; - } - - this._mask = value; - - if (this._mask) - { - var maskObject$1 = this._mask.maskObject || this._mask; - - maskObject$1.renderable = false; - maskObject$1.isMask = true; - } + /** + * Reset the line style to default. + */ + LineStyle.prototype.reset = function () { + _super.prototype.reset.call(this); + // Override default line style color + this.color = 0x0; + this.alignment = 0.5; + this.width = 0; + this.native = false; }; + return LineStyle; +}(FillStyle)); - Object.defineProperties( DisplayObject.prototype, prototypeAccessors ); - - return DisplayObject; -}(utils.EventEmitter)); - -/** - * DisplayObject default updateTransform, does not update children of container. - * Will crash if there's no parent element. - * - * @memberof PIXI.DisplayObject# - * @function displayObjectUpdateTransform - */ -DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; - -function sortChildren(a, b) -{ - if (a.zIndex === b.zIndex) - { - return a._lastSortedIndex - b._lastSortedIndex; - } - - return a.zIndex - b.zIndex; -} - +var temp = new Float32Array(3); +// a default shaders map used by graphics.. +var DEFAULT_SHADERS = {}; /** - * A Container represents a collection of display objects. - * - * It is the base class of all display objects that act as a container for other objects (like Sprites). + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. * - *```js - * let container = new PIXI.Container(); - * container.addChild(sprite); - * ``` + * Note that because Graphics can share a GraphicsGeometry with other instances, + * it is necessary to call `destroy()` to properly dereference the underlying + * GraphicsGeometry and avoid a memory leak. Alternatively, keep using the same + * Graphics instance and call `clear()` between redraws. * * @class - * @extends PIXI.DisplayObject + * @extends PIXI.Container * @memberof PIXI */ -var Container = /*@__PURE__*/(function (DisplayObject) { - function Container() - { - DisplayObject.call(this); - +var Graphics = /** @class */ (function (_super) { + __extends(Graphics, _super); + /** + * @param {PIXI.GraphicsGeometry} [geometry=null] - Geometry to use, if omitted + * will create a new GraphicsGeometry instance. + */ + function Graphics(geometry) { + if (geometry === void 0) { geometry = null; } + var _this = _super.call(this) || this; + _this._geometry = geometry || new GraphicsGeometry(); + _this._geometry.refCount++; /** - * The array of children of this container. + * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. + * Can be shared between multiple Graphics objects. * - * @member {PIXI.DisplayObject[]} - * @readonly + * @member {PIXI.Shader} */ - this.children = []; - + _this.shader = null; /** - * If set to true, the container will sort its children by zIndex value - * when updateTransform() is called, or manually if sortChildren() is called. + * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g., + * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. * - * This actually changes the order of elements in the array, so should be treated - * as a basic solution that is not performant compared to other solutions, - * such as @link https://github.com/pixijs/pixi-display + * @member {PIXI.State} + */ + _this.state = core.State.for2d(); + /** + * Current fill style * - * Also be aware of that this may not work nicely with the addChildAt() function, - * as the zIndex sorting may cause the child to automatically sorted to another position. + * @member {PIXI.FillStyle} + * @protected + */ + _this._fillStyle = new FillStyle(); + /** + * Current line style * - * @see PIXI.settings.SORTABLE_CHILDREN + * @member {PIXI.LineStyle} + * @protected + */ + _this._lineStyle = new LineStyle(); + /** + * Current shape transform matrix. + * + * @member {PIXI.Matrix} + * @protected + */ + _this._matrix = null; + /** + * Current hole mode is enabled. * * @member {boolean} + * @default false + * @protected */ - this.sortableChildren = settings.settings.SORTABLE_CHILDREN; - + _this._holeMode = false; /** - * Should children be sorted by zIndex at the next updateTransform call. - * Will get automatically set to true if a new child is added, or if a child's zIndex changes. + * Current path + * + * @member {PIXI.Polygon} + * @protected + */ + _this.currentPath = null; + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. * + * @name cacheAsBitmap * @member {boolean} + * @memberof PIXI.Graphics# + * @default false */ - this.sortDirty = false; - /** - * Fired when a DisplayObject is added to this Container. + * A collections of batches! These can be drawn by the renderer batch system. * - * @event PIXI.Container#childAdded - * @param {PIXI.DisplayObject} child - The child added to the Container. - * @param {PIXI.Container} container - The container that added the child. - * @param {number} index - The children's index of the added child. + * @protected + * @member {object[]} */ - + _this.batches = []; /** - * Fired when a DisplayObject is removed from this Container. + * Update dirty for limiting calculating tints for batches. * - * @event PIXI.DisplayObject#removedFrom - * @param {PIXI.DisplayObject} child - The child removed from the Container. - * @param {PIXI.Container} container - The container that removed removed the child. - * @param {number} index - The former children's index of the removed child + * @protected + * @member {number} + * @default -1 + */ + _this.batchTint = -1; + /** + * Update dirty for limiting calculating batches. + * + * @protected + * @member {number} + * @default -1 + */ + _this.batchDirty = -1; + /** + * Copy of the object vertex data. + * + * @protected + * @member {Float32Array} + */ + _this.vertexData = null; + /** + * Renderer plugin for batching + * + * @member {string} + * @default 'batch' */ + _this.pluginName = 'batch'; + _this._transformID = -1; + // Set default + _this.tint = 0xFFFFFF; + _this.blendMode = constants.BLEND_MODES.NORMAL; + return _this; } - - if ( DisplayObject ) Container.__proto__ = DisplayObject; - Container.prototype = Object.create( DisplayObject && DisplayObject.prototype ); - Container.prototype.constructor = Container; - - var prototypeAccessors = { width: { configurable: true },height: { configurable: true } }; - + Object.defineProperty(Graphics.prototype, "geometry", { + /** + * Includes vertex positions, face indices, normals, colors, UVs, and + * custom attributes within buffers, reducing the cost of passing all + * this data to the GPU. Can be shared between multiple Mesh or Graphics objects. + * + * @member {PIXI.GraphicsGeometry} + * @readonly + */ + get: function () { + return this._geometry; + }, + enumerable: false, + configurable: true + }); /** - * Overridable method that can be used by Container subclasses whenever the children array is modified + * Creates a new Graphics object with the same values as this one. + * Note that only the geometry of the object is cloned, not its transform (position,scale,etc) * - * @protected + * @return {PIXI.Graphics} A clone of the graphics object */ - Container.prototype.onChildrenChange = function onChildrenChange () - { - /* empty */ + Graphics.prototype.clone = function () { + this.finishPoly(); + return new Graphics(this._geometry); }; - + Object.defineProperty(Graphics.prototype, "blendMode", { + get: function () { + return this.state.blendMode; + }, + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "tint", { + /** + * The tint applied to the graphic shape. This is a hex value. A value of + * 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "fill", { + /** + * The current fill style. + * + * @member {PIXI.FillStyle} + * @readonly + */ + get: function () { + return this._fillStyle; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "line", { + /** + * The current line style. + * + * @member {PIXI.LineStyle} + * @readonly + */ + get: function () { + return this._lineStyle; + }, + enumerable: false, + configurable: true + }); /** - * Adds one or more children to the container. + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. * - * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * @method PIXI.Graphics#lineStyle + * @param {number} [width=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0x0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {number} [alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) + * @param {boolean} [native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. * - * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container - * @return {PIXI.DisplayObject} The first child that was added. + * @param {object} [options] - Line style options + * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style + * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style + * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) + * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style + * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style + * @param {number}[options.miterLimit=10] - miter limit ratio + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.addChild = function addChild (child) - { - var arguments$1 = arguments; - - var argumentsLength = arguments.length; - - // if there is only one argument we can bypass looping through the them - if (argumentsLength > 1) - { - // loop through the arguments property and add all children - // use it the right way (.length and [i]) so that this function can still be optimized by JS runtimes - for (var i = 0; i < argumentsLength; i++) - { - this.addChild(arguments$1[i]); - } + Graphics.prototype.lineStyle = function (options) { + if (options === void 0) { options = null; } + // Support non-object params: (width, color, alpha, alignment, native) + if (typeof options === 'number') { + // eslint-disable-next-line + var args = arguments; + options = { + width: args[0] || 0, + color: args[1] || 0x0, + alpha: args[2] !== undefined ? args[2] : 1, + alignment: args[3] !== undefined ? args[3] : 0.5, + native: !!args[4], + }; } - else - { - // if the child has a parent then lets remove it as PixiJS objects can only exist in one place - if (child.parent) - { - child.parent.removeChild(child); + return this.lineTextureStyle(options); + }; + /** + * Like line style but support texture for line fill. + * + * @param {object} [options] - Collection of options for setting line style. + * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style + * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use + * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style. + * Default 0xFFFFFF if texture present. + * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {PIXI.Matrix} [options.matrix=null] - Texture matrix to transform texture + * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) + * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style + * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style + * @param {number}[options.miterLimit=10] - miter limit ratio + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.lineTextureStyle = function (options) { + // backward compatibility with params: (width, texture, + // color, alpha, matrix, alignment, native) + if (typeof options === 'number') { + utils.deprecation('v5.2.0', 'Please use object-based options for Graphics#lineTextureStyle'); + // eslint-disable-next-line + var _a = arguments, width = _a[0], texture = _a[1], color = _a[2], alpha = _a[3], matrix = _a[4], alignment = _a[5], native = _a[6]; + options = { width: width, texture: texture, color: color, alpha: alpha, matrix: matrix, alignment: alignment, native: native }; + // Remove undefined keys + Object.keys(options).forEach(function (key) { return options[key] === undefined && delete options[key]; }); + } + // Apply defaults + options = Object.assign({ + width: 0, + texture: core.Texture.WHITE, + color: (options && options.texture) ? 0xFFFFFF : 0x0, + alpha: 1, + matrix: null, + alignment: 0.5, + native: false, + cap: exports.LINE_CAP.BUTT, + join: exports.LINE_JOIN.MITER, + miterLimit: 10, + }, options); + if (this.currentPath) { + this.startPoly(); + } + var visible = options.width > 0 && options.alpha > 0; + if (!visible) { + this._lineStyle.reset(); + } + else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); } - - child.parent = this; - this.sortDirty = true; - - // ensure child transform will be recalculated - child.transform._parentID = -1; - - this.children.push(child); - - // ensure bounds will be recalculated - this._boundsID++; - - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(this.children.length - 1); - this.emit('childAdded', child, this, this.children.length - 1); - child.emit('added', this); + Object.assign(this._lineStyle, { visible: visible }, options); } - - return child; + return this; }; - /** - * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown - * - * @param {PIXI.DisplayObject} child - The child to add - * @param {number} index - The index to place the child in - * @return {PIXI.DisplayObject} The child that was added. + * Start a polygon object internally + * @protected */ - Container.prototype.addChildAt = function addChildAt (child, index) - { - if (index < 0 || index > this.children.length) - { - throw new Error((child + "addChildAt: The index " + index + " supplied is out of bounds " + (this.children.length))); + Graphics.prototype.startPoly = function () { + if (this.currentPath) { + var points = this.currentPath.points; + var len = this.currentPath.points.length; + if (len > 2) { + this.drawShape(this.currentPath); + this.currentPath = new math.Polygon(); + this.currentPath.closeStroke = false; + this.currentPath.points.push(points[len - 2], points[len - 1]); + } } - - if (child.parent) - { - child.parent.removeChild(child); + else { + this.currentPath = new math.Polygon(); + this.currentPath.closeStroke = false; } - - child.parent = this; - this.sortDirty = true; - - // ensure child transform will be recalculated - child.transform._parentID = -1; - - this.children.splice(index, 0, child); - - // ensure bounds will be recalculated - this._boundsID++; - - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('added', this); - this.emit('childAdded', child, this, index); - - return child; }; - /** - * Swaps the position of 2 Display Objects within this container. - * - * @param {PIXI.DisplayObject} child - First display object to swap - * @param {PIXI.DisplayObject} child2 - Second display object to swap + * Finish the polygon object. + * @protected */ - Container.prototype.swapChildren = function swapChildren (child, child2) - { - if (child === child2) - { - return; + Graphics.prototype.finishPoly = function () { + if (this.currentPath) { + if (this.currentPath.points.length > 2) { + this.drawShape(this.currentPath); + this.currentPath = null; + } + else { + this.currentPath.points.length = 0; + } } - - var index1 = this.getChildIndex(child); - var index2 = this.getChildIndex(child2); - - this.children[index1] = child2; - this.children[index2] = child; - this.onChildrenChange(index1 < index2 ? index1 : index2); }; - /** - * Returns the index position of a child DisplayObject instance + * Moves the current drawing position to x, y. * - * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify - * @return {number} The index position of the child display object to identify + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.getChildIndex = function getChildIndex (child) - { - var index = this.children.indexOf(child); - - if (index === -1) - { - throw new Error('The supplied DisplayObject must be a child of the caller'); - } - - return index; + Graphics.prototype.moveTo = function (x, y) { + this.startPoly(); + this.currentPath.points[0] = x; + this.currentPath.points[1] = y; + return this; }; - /** - * Changes the position of an existing child in the display object container + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). * - * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number - * @param {number} index - The resulting index number for the child display object + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.setChildIndex = function setChildIndex (child, index) - { - if (index < 0 || index >= this.children.length) - { - throw new Error(("The index " + index + " supplied is out of bounds " + (this.children.length))); + Graphics.prototype.lineTo = function (x, y) { + if (!this.currentPath) { + this.moveTo(0, 0); } - - var currentIndex = this.getChildIndex(child); - - utils.removeItems(this.children, currentIndex, 1); // remove from old position - this.children.splice(index, 0, child); // add at new position - - this.onChildrenChange(index); + // remove duplicates.. + var points = this.currentPath.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + if (fromX !== x || fromY !== y) { + points.push(x, y); + } + return this; }; - /** - * Returns the child at the specified index + * Initialize the curve * - * @param {number} index - The index to get the child at - * @return {PIXI.DisplayObject} The child at the given index, if any. + * @protected + * @param {number} [x=0] + * @param {number} [y=0] */ - Container.prototype.getChildAt = function getChildAt (index) - { - if (index < 0 || index >= this.children.length) - { - throw new Error(("getChildAt: Index (" + index + ") does not exist.")); + Graphics.prototype._initCurve = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (this.currentPath) { + if (this.currentPath.points.length === 0) { + this.currentPath.points = [x, y]; + } + } + else { + this.moveTo(x, y); } - - return this.children[index]; }; - /** - * Removes one or more children from the container. + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c * - * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove - * @return {PIXI.DisplayObject} The first child that was removed. + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.removeChild = function removeChild (child) - { - var arguments$1 = arguments; - - var argumentsLength = arguments.length; - - // if there is only one argument we can bypass looping through the them - if (argumentsLength > 1) - { - // loop through the arguments property and add all children - // use it the right way (.length and [i]) so that this function can still be optimized by JS runtimes - for (var i = 0; i < argumentsLength; i++) - { - this.removeChild(arguments$1[i]); - } - } - else - { - var index = this.children.indexOf(child); - - if (index === -1) { return null; } - - child.parent = null; - // ensure child transform will be recalculated - child.transform._parentID = -1; - utils.removeItems(this.children, index, 1); - - // ensure bounds will be recalculated - this._boundsID++; - - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('removed', this); - this.emit('childRemoved', child, this, index); + Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + this._initCurve(); + var points = this.currentPath.points; + if (points.length === 0) { + this.moveTo(0, 0); } - - return child; + QuadraticUtils.curveTo(cpX, cpY, toX, toY, points); + return this; }; - /** - * Removes a child from the specified index position. + * Calculate the points for a bezier curve and then draws it. * - * @param {number} index - The index to get the child from - * @return {PIXI.DisplayObject} The child that was removed. + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.removeChildAt = function removeChildAt (index) - { - var child = this.getChildAt(index); - - // ensure child transform will be recalculated.. - child.parent = null; - child.transform._parentID = -1; - utils.removeItems(this.children, index, 1); - - // ensure bounds will be recalculated - this._boundsID++; - - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('removed', this); - this.emit('childRemoved', child, this, index); - - return child; + Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + this._initCurve(); + BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points); + return this; }; - /** - * Removes all children from this container that are within the begin and end indexes. + * The arcTo() method creates an arc/curve between two tangents on the canvas. * - * @param {number} [beginIndex=0] - The beginning position. - * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. - * @returns {PIXI.DisplayObject[]} List of removed children + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the first tangent point of the arc + * @param {number} y1 - The y-coordinate of the first tangent point of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.removeChildren = function removeChildren (beginIndex, endIndex) - { - if ( beginIndex === void 0 ) beginIndex = 0; - - var begin = beginIndex; - var end = typeof endIndex === 'number' ? endIndex : this.children.length; - var range = end - begin; - var removed; - - if (range > 0 && range <= end) - { - removed = this.children.splice(begin, range); - - for (var i = 0; i < removed.length; ++i) - { - removed[i].parent = null; - if (removed[i].transform) - { - removed[i].transform._parentID = -1; - } - } - - this._boundsID++; - - this.onChildrenChange(beginIndex); - - for (var i$1 = 0; i$1 < removed.length; ++i$1) - { - removed[i$1].emit('removed', this); - this.emit('childRemoved', removed[i$1], this, i$1); - } - - return removed; - } - else if (range === 0 && this.children.length === 0) - { - return []; + Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + this._initCurve(x1, y1); + var points = this.currentPath.points; + var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points); + if (result) { + var cx = result.cx, cy = result.cy, radius_1 = result.radius, startAngle = result.startAngle, endAngle = result.endAngle, anticlockwise = result.anticlockwise; + this.arc(cx, cy, radius_1, startAngle, endAngle, anticlockwise); } - - throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + return this; }; - /** - * Sorts children by zIndex. Previous order is mantained for 2 children with the same zIndex. + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.sortChildren = function sortChildren$1 () - { - var sortRequired = false; - - for (var i = 0, j = this.children.length; i < j; ++i) - { - var child = this.children[i]; - - child._lastSortedIndex = i; - - if (!sortRequired && child.zIndex !== 0) - { - sortRequired = true; + Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { + if (anticlockwise === void 0) { anticlockwise = false; } + if (startAngle === endAngle) { + return this; + } + if (!anticlockwise && endAngle <= startAngle) { + endAngle += math.PI_2; + } + else if (anticlockwise && startAngle <= endAngle) { + startAngle += math.PI_2; + } + var sweep = endAngle - startAngle; + if (sweep === 0) { + return this; + } + var startX = cx + (Math.cos(startAngle) * radius); + var startY = cy + (Math.sin(startAngle) * radius); + var eps = this._geometry.closePointEps; + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.points : null; + if (points) { + // TODO: make a better fix. + // We check how far our start is from the last existing point + var xDiff = Math.abs(points[points.length - 2] - startX); + var yDiff = Math.abs(points[points.length - 1] - startY); + if (xDiff < eps && yDiff < eps) ; + else { + points.push(startX, startY); } } - - if (sortRequired && this.children.length > 1) - { - this.children.sort(sortChildren); + else { + this.moveTo(startX, startY); + points = this.currentPath.points; } - - this.sortDirty = false; + ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points); + return this; }; - /** - * Updates the transform on all children of this container for rendering + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.updateTransform = function updateTransform () - { - if (this.sortableChildren && this.sortDirty) - { - this.sortChildren(); + Graphics.prototype.beginFill = function (color, alpha) { + if (color === void 0) { color = 0; } + if (alpha === void 0) { alpha = 1; } + return this.beginTextureFill({ texture: core.Texture.WHITE, color: color, alpha: alpha }); + }; + /** + * Begin the texture fill + * + * @param {object} [options] - Object object. + * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill + * @param {number} [options.color=0xffffff] - Background to fill behind texture + * @param {number} [options.alpha=1] - Alpha of fill + * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.beginTextureFill = function (options) { + // backward compatibility with params: (texture, color, alpha, matrix) + if (options instanceof core.Texture) { + utils.deprecation('v5.2.0', 'Please use object-based options for Graphics#beginTextureFill'); + // eslint-disable-next-line + var _a = arguments, texture = _a[0], color = _a[1], alpha = _a[2], matrix = _a[3]; + options = { texture: texture, color: color, alpha: alpha, matrix: matrix }; + // Remove undefined keys + Object.keys(options).forEach(function (key) { return options[key] === undefined && delete options[key]; }); } - - this._boundsID++; - - this.transform.updateTransform(this.parent.transform); - - // TODO: check render flags, how to process stuff here - this.worldAlpha = this.alpha * this.parent.worldAlpha; - - for (var i = 0, j = this.children.length; i < j; ++i) - { - var child = this.children[i]; - - if (child.visible) - { - child.updateTransform(); + // Apply defaults + options = Object.assign({ + texture: core.Texture.WHITE, + color: 0xFFFFFF, + alpha: 1, + matrix: null, + }, options); + if (this.currentPath) { + this.startPoly(); + } + var visible = options.alpha > 0; + if (!visible) { + this._fillStyle.reset(); + } + else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); } + Object.assign(this._fillStyle, { visible: visible }, options); } + return this; }; - /** - * Recalculates the bounds of the container. + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.calculateBounds = function calculateBounds () - { - this._bounds.clear(); - - this._calculateBounds(); - - for (var i = 0; i < this.children.length; i++) - { - var child = this.children[i]; - - if (!child.visible || !child.renderable) - { - continue; - } - - child.calculateBounds(); - - // TODO: filter+mask, need to mask both somehow - if (child._mask) - { - var maskObject = child._mask.maskObject || child._mask; - - maskObject.calculateBounds(); - this._bounds.addBoundsMask(child._bounds, maskObject._bounds); - } - else if (child.filterArea) - { - this._bounds.addBoundsArea(child._bounds, child.filterArea); - } - else - { - this._bounds.addBounds(child._bounds); - } - } - - this._lastBoundsID = this._boundsID; + Graphics.prototype.endFill = function () { + this.finishPoly(); + this._fillStyle.reset(); + return this; }; - /** - * Recalculates the bounds of the object. Override this to - * calculate the bounds of the specific object (not including children). + * Draws a rectangle shape. * - * @protected + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype._calculateBounds = function _calculateBounds () - { - // FILL IN// + Graphics.prototype.drawRect = function (x, y, width, height) { + return this.drawShape(new math.Rectangle(x, y, width, height)); }; - /** - * Renders the object using the WebGL renderer + * Draw a rectangle shape with rounded/beveled corners. * - * @param {PIXI.Renderer} renderer - The renderer + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.render = function render (renderer) - { - // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) - { - return; - } - - // do a quick check to see if this element has a mask or a filter. - if (this._mask || (this.filters && this.filters.length)) - { - this.renderAdvanced(renderer); - } - else - { - this._render(renderer); - - // simple render children! - for (var i = 0, j = this.children.length; i < j; ++i) - { - this.children[i].render(renderer); - } - } + Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + return this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); }; - /** - * Render the object using the WebGL renderer and advanced features. + * Draws a circle. * - * @protected - * @param {PIXI.Renderer} renderer - The renderer + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.renderAdvanced = function renderAdvanced (renderer) - { - renderer.batch.flush(); - - var filters = this.filters; - var mask = this._mask; - - // push filter first as we need to ensure the stencil buffer is correct for any masking - if (filters) - { - if (!this._enabledFilters) - { - this._enabledFilters = []; - } - - this._enabledFilters.length = 0; - - for (var i = 0; i < filters.length; i++) - { - if (filters[i].enabled) - { - this._enabledFilters.push(filters[i]); - } - } + Graphics.prototype.drawCircle = function (x, y, radius) { + return this.drawShape(new math.Circle(x, y, radius)); + }; + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawEllipse = function (x, y, width, height) { + return this.drawShape(new math.Ellipse(x, y, width, height)); + }; + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawPolygon = function () { + var arguments$1 = arguments; - if (this._enabledFilters.length) - { - renderer.filter.push(this, this._enabledFilters); - } + var path = []; + for (var _i = 0; _i < arguments.length; _i++) { + path[_i] = arguments$1[_i]; } - - if (mask) - { - renderer.mask.push(this, this._mask); + var points; + var closeStroke = true; // !!this._fillStyle; + var poly = path[0]; + // check if data has points.. + if (poly.points) { + closeStroke = poly.closeStroke; + points = poly.points; } - - // add this object to the batch, only rendered if it has a texture. - this._render(renderer); - - // now loop through the children and make sure they get rendered - for (var i$1 = 0, j = this.children.length; i$1 < j; i$1++) - { - this.children[i$1].render(renderer); + else if (Array.isArray(path[0])) { + points = path[0]; } - - renderer.batch.flush(); - - if (mask) - { - renderer.mask.pop(this, this._mask); + else { + points = path; } - - if (filters && this._enabledFilters && this._enabledFilters.length) - { - renderer.filter.pop(); + var shape = new math.Polygon(points); + shape.closeStroke = closeStroke; + this.drawShape(shape); + return this; + }; + /** + * Draw any shape. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawShape = function (shape) { + if (!this._holeMode) { + this._geometry.drawShape(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix); + } + else { + this._geometry.drawHole(shape, this._matrix); } + return this; }; - /** - * To be overridden by the subclasses. + * Draw a star shape with an arbitrary number of points. * - * @protected - * @param {PIXI.Renderer} renderer - The renderer + * @param {number} x - Center X position of the star + * @param {number} y - Center Y position of the star + * @param {number} points - The number of points of the star, must be > 1 + * @param {number} radius - The outer radius of the star + * @param {number} [innerRadius] - The inner radius between points, default half `radius` + * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype._render = function _render (renderer) // eslint-disable-line no-unused-vars - { - // this is where content itself gets rendered... + Graphics.prototype.drawStar = function (x, y, points, radius, innerRadius, rotation) { + if (rotation === void 0) { rotation = 0; } + return this.drawPolygon(new Star(x, y, points, radius, innerRadius, rotation)); }; - /** - * Removes all internal references and listeners as well as removes children from the display list. - * Do not use a Container after calling `destroy`. + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Container.prototype.destroy = function destroy (options) - { - DisplayObject.prototype.destroy.call(this); - - this.sortDirty = false; - - var destroyChildren = typeof options === 'boolean' ? options : options && options.children; - - var oldChildren = this.removeChildren(0, this.children.length); - - if (destroyChildren) - { - for (var i = 0; i < oldChildren.length; ++i) - { - oldChildren[i].destroy(options); - } - } + Graphics.prototype.clear = function () { + this._geometry.clear(); + this._lineStyle.reset(); + this._fillStyle.reset(); + this._boundsID++; + this._matrix = null; + this._holeMode = false; + this.currentPath = null; + return this; }; - /** - * The width of the Container, setting this will actually modify the scale to achieve the value set + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. * - * @member {number} + * @returns {boolean} True if only 1 rect. */ - prototypeAccessors.width.get = function () - { - return this.scale.x * this.getLocalBounds().width; + Graphics.prototype.isFastRect = function () { + var data = this._geometry.graphicsData; + return data.length === 1 + && data[0].shape.type === math.SHAPES.RECT + && !(data[0].lineStyle.visible && data[0].lineStyle.width); }; - - prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc - { - var width = this.getLocalBounds().width; - - if (width !== 0) - { - this.scale.x = value / width; + /** + * Renders the object using the WebGL renderer + * + * @protected + * @param {PIXI.Renderer} renderer - The renderer + */ + Graphics.prototype._render = function (renderer) { + this.finishPoly(); + var geometry = this._geometry; + var hasuit32 = renderer.context.supports.uint32Indices; + // batch part.. + // batch it! + geometry.updateBatches(hasuit32); + if (geometry.batchable) { + if (this.batchDirty !== geometry.batchDirty) { + this._populateBatches(); + } + this._renderBatched(renderer); } - else - { - this.scale.x = 1; + else { + // no batching... + renderer.batch.flush(); + this._renderDirect(renderer); } - - this._width = value; }; - /** - * The height of the Container, setting this will actually modify the scale to achieve the value set + * Populating batches for rendering * - * @member {number} + * @protected */ - prototypeAccessors.height.get = function () - { - return this.scale.y * this.getLocalBounds().height; + Graphics.prototype._populateBatches = function () { + var geometry = this._geometry; + var blendMode = this.blendMode; + var len = geometry.batches.length; + this.batchTint = -1; + this._transformID = -1; + this.batchDirty = geometry.batchDirty; + this.batches.length = len; + this.vertexData = new Float32Array(geometry.points); + for (var i = 0; i < len; i++) { + var gI = geometry.batches[i]; + var color = gI.style.color; + var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + var uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + var indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size); + var batch = { + vertexData: vertexData, + blendMode: blendMode, + indices: indices, + uvs: uvs, + _batchRGB: utils.hex2rgb(color), + _tintRGB: color, + _texture: gI.style.texture, + alpha: gI.style.alpha, + worldAlpha: 1 + }; + this.batches[i] = batch; + } }; - - prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc - { - var height = this.getLocalBounds().height; - - if (height !== 0) - { - this.scale.y = value / height; + /** + * Renders the batches using the BathedRenderer plugin + * + * @protected + * @param {PIXI.Renderer} renderer - The renderer + */ + Graphics.prototype._renderBatched = function (renderer) { + if (!this.batches.length) { + return; } - else - { - this.scale.y = 1; + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + this.calculateVertices(); + this.calculateTints(); + for (var i = 0, l = this.batches.length; i < l; i++) { + var batch = this.batches[i]; + batch.worldAlpha = this.worldAlpha * batch.alpha; + renderer.plugins[this.pluginName].render(batch); } - - this._height = value; }; + /** + * Renders the graphics direct + * + * @protected + * @param {PIXI.Renderer} renderer - The renderer + */ + Graphics.prototype._renderDirect = function (renderer) { + var shader = this._resolveDirectShader(renderer); + var geometry = this._geometry; + var tint = this.tint; + var worldAlpha = this.worldAlpha; + var uniforms = shader.uniforms; + var drawCalls = geometry.drawCalls; + // lets set the transfomr + uniforms.translationMatrix = this.transform.worldTransform; + // and then lets set the tint.. + uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha; + uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha; + uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha; + uniforms.tint[3] = worldAlpha; + // the first draw call, we can set the uniforms of the shader directly here. + // this means that we can tack advantage of the sync function of pixi! + // bind and sync uniforms.. + // there is a way to optimise this.. + renderer.shader.bind(shader); + renderer.geometry.bind(geometry, shader); + // set state.. + renderer.state.set(this.state); + // then render the rest of them... + for (var i = 0, l = drawCalls.length; i < l; i++) { + this._renderDrawCallDirect(renderer, geometry.drawCalls[i]); + } + }; + /** + * Renders specific DrawCall + * + * @param {PIXI.Renderer} renderer + * @param {PIXI.BatchDrawCall} drawCall + */ + Graphics.prototype._renderDrawCallDirect = function (renderer, drawCall) { + var texArray = drawCall.texArray, type = drawCall.type, size = drawCall.size, start = drawCall.start; + var groupTextureCount = texArray.count; + for (var j = 0; j < groupTextureCount; j++) { + renderer.texture.bind(texArray.elements[j], j); + } + renderer.geometry.draw(type, size, start); + }; + /** + * Resolves shader for direct rendering + * + * @protected + * @param {PIXI.Renderer} renderer - The renderer + */ + Graphics.prototype._resolveDirectShader = function (renderer) { + var shader = this.shader; + var pluginName = this.pluginName; + if (!shader) { + // if there is no shader here, we can use the default shader. + // and that only gets created if we actually need it.. + // but may be more than one plugins for graphics + if (!DEFAULT_SHADERS[pluginName]) { + var sampleValues = new Int32Array(16); + for (var i = 0; i < 16; i++) { + sampleValues[i] = i; + } + var uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new math.Matrix(), + default: core.UniformGroup.from({ uSamplers: sampleValues }, true), + }; + var program = renderer.plugins[pluginName]._shader.program; + DEFAULT_SHADERS[pluginName] = new core.Shader(program, uniforms); + } + shader = DEFAULT_SHADERS[pluginName]; + } + return shader; + }; + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @protected + */ + Graphics.prototype._calculateBounds = function () { + this.finishPoly(); + var geometry = this._geometry; + // skipping when graphics is empty, like a container + if (!geometry.graphicsData.length) { + return; + } + var _a = geometry.bounds, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY; + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.IPointData} point - the point to test + * @return {boolean} the result of the test + */ + Graphics.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, Graphics._TEMP_POINT); + return this._geometry.containsPoint(Graphics._TEMP_POINT); + }; + /** + * Recalcuate the tint by applying tin to batches using Graphics tint. + * @protected + */ + Graphics.prototype.calculateTints = function () { + if (this.batchTint !== this.tint) { + this.batchTint = this.tint; + var tintRGB = utils.hex2rgb(this.tint, temp); + for (var i = 0; i < this.batches.length; i++) { + var batch = this.batches[i]; + var batchTint = batch._batchRGB; + var r = (tintRGB[0] * batchTint[0]) * 255; + var g = (tintRGB[1] * batchTint[1]) * 255; + var b = (tintRGB[2] * batchTint[2]) * 255; + // TODO Ivan, can this be done in one go? + var color = (r << 16) + (g << 8) + (b | 0); + batch._tintRGB = (color >> 16) + + (color & 0xff00) + + ((color & 0xff) << 16); + } + } + }; + /** + * If there's a transform update or a change to the shape of the + * geometry, recaculate the vertices. + * @protected + */ + Graphics.prototype.calculateVertices = function () { + var wtID = this.transform._worldID; + if (this._transformID === wtID) { + return; + } + this._transformID = wtID; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var data = this._geometry.points; // batch.vertexDataOriginal; + var vertexData = this.vertexData; + var count = 0; + for (var i = 0; i < data.length; i += 2) { + var x = data[i]; + var y = data[i + 1]; + vertexData[count++] = (a * x) + (c * y) + tx; + vertexData[count++] = (d * y) + (b * x) + ty; + } + }; + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + Graphics.prototype.closePath = function () { + var currentPath = this.currentPath; + if (currentPath) { + // we don't need to add extra point in the end because buildLine will take care of that + currentPath.closeStroke = true; + } + return this; + }; + /** + * Apply a matrix to the positional data. + * + * @param {PIXI.Matrix} matrix - Matrix to use for transform current shape. + * @return {PIXI.Graphics} Returns itself. + */ + Graphics.prototype.setMatrix = function (matrix) { + this._matrix = matrix; + return this; + }; + /** + * Begin adding holes to the last draw shape + * IMPORTANT: holes must be fully inside a shape to work + * Also weirdness ensues if holes overlap! + * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer, + * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle. + * @return {PIXI.Graphics} Returns itself. + */ + Graphics.prototype.beginHole = function () { + this.finishPoly(); + this._holeMode = true; + return this; + }; + /** + * End adding holes to the last draw shape + * @return {PIXI.Graphics} Returns itself. + */ + Graphics.prototype.endHole = function () { + this.finishPoly(); + this._holeMode = false; + return this; + }; + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Graphics.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this._geometry.refCount--; + if (this._geometry.refCount === 0) { + this._geometry.dispose(); + } + this._matrix = null; + this.currentPath = null; + this._lineStyle.destroy(); + this._lineStyle = null; + this._fillStyle.destroy(); + this._fillStyle = null; + this._geometry = null; + this.shader = null; + this.vertexData = null; + this.batches.length = 0; + this.batches = null; + _super.prototype.destroy.call(this, options); + }; + /** + * Temporary point to use for containsPoint + * + * @static + * @private + * @member {PIXI.Point} + */ + Graphics._TEMP_POINT = new math.Point(); + return Graphics; +}(display.Container)); - Object.defineProperties( Container.prototype, prototypeAccessors ); - - return Container; -}(DisplayObject)); - -// performance increase to avoid using call.. (10x faster) -Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; - -exports.Bounds = Bounds; -exports.Container = Container; -exports.DisplayObject = DisplayObject; +exports.FillStyle = FillStyle; +exports.GRAPHICS_CURVES = GRAPHICS_CURVES; +exports.Graphics = Graphics; +exports.GraphicsData = GraphicsData; +exports.GraphicsGeometry = GraphicsGeometry; +exports.LineStyle = LineStyle; +exports.graphicsUtils = index; -},{"@pixi/math":29,"@pixi/settings":39,"@pixi/utils":47}],19:[function(require,module,exports){ +},{"@pixi/constants":7,"@pixi/core":8,"@pixi/display":9,"@pixi/math":20,"@pixi/utils":38}],18:[function(require,module,exports){ /*! - * @pixi/extract - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * @pixi/interaction - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @pixi/extract is licensed under the MIT License. + * @pixi/interaction is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); -var core = require('@pixi/core'); -var utils = require('@pixi/utils'); var math = require('@pixi/math'); - -var TEMP_RECT = new math.Rectangle(); -var BYTES_PER_PIXEL = 4; +var ticker = require('@pixi/ticker'); +var display = require('@pixi/display'); +var utils = require('@pixi/utils'); /** - * The extract manager provides functionality to export content from the renderers. - * - * An instance of this class is automatically created by default, and can be found at `renderer.plugins.extract` + * Holds all information related to an Interaction event * * @class - * @memberof PIXI.extract + * @memberof PIXI */ -var Extract = function Extract(renderer) -{ - this.renderer = renderer; +var InteractionData = /** @class */ (function () { + function InteractionData() { + this.pressure = 0; + this.rotationAngle = 0; + this.twist = 0; + this.tangentialPressure = 0; + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new math.Point(); + /** + * The target Sprite that was interacted with + * + * @member {PIXI.Sprite} + */ + this.target = null; + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent + * @member {MouseEvent|TouchEvent|PointerEvent} + */ + this.originalEvent = null; + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + /** + * Indicates whether or not the pointer device that created the event is the primary pointer. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary + * @type {Boolean} + */ + this.isPrimary = false; + /** + * Indicates which button was pressed on the mouse or pointer device to trigger the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button + * @type {number} + */ + this.button = 0; + /** + * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons + * @type {number} + */ + this.buttons = 0; + /** + * The width of the pointer's contact along the x-axis, measured in CSS pixels. + * radiusX of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width + * @type {number} + */ + this.width = 0; + /** + * The height of the pointer's contact along the y-axis, measured in CSS pixels. + * radiusY of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height + * @type {number} + */ + this.height = 0; + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX + * @type {number} + */ + this.tiltX = 0; + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY + * @type {number} + */ + this.tiltY = 0; + /** + * The type of pointer that triggered the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType + * @type {string} + */ + this.pointerType = null; + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + * @type {number} + */ + this.pressure = 0; + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + * @type {number} + */ + this.rotationAngle = 0; + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.twist = 0; + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.tangentialPressure = 0; + } + Object.defineProperty(InteractionData.prototype, "pointerId", { + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @member {number} + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + get: function () { + return this.identifier; + }, + enumerable: false, + configurable: true + }); /** - * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * This will return the local coordinates of the specified displayObject for this InteractionData * - * @member {PIXI.extract.Extract} extract - * @memberof PIXI.Renderer# - * @see PIXI.extract.Extract + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject */ - renderer.extract = this; -}; - -/** - * Will return a HTML Image of the target - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp". - * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92. - * @return {HTMLImageElement} HTML Image of the target - */ -Extract.prototype.image = function image (target, format, quality) -{ - var image = new Image(); - - image.src = this.base64(target, format, quality); + InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + /** + * Copies properties from normalized event data. + * + * @param {Touch|MouseEvent|PointerEvent} event - The normalized event data + */ + InteractionData.prototype.copyEvent = function (event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if ('isPrimary' in event && event.isPrimary) { + this.isPrimary = true; + } + this.button = 'button' in event && event.button; + // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard + // event.which property instead, which conveys the same information. + var buttons = 'buttons' in event && event.buttons; + this.buttons = Number.isInteger(buttons) ? buttons : 'which' in event && event.which; + this.width = 'width' in event && event.width; + this.height = 'height' in event && event.height; + this.tiltX = 'tiltX' in event && event.tiltX; + this.tiltY = 'tiltY' in event && event.tiltY; + this.pointerType = 'pointerType' in event && event.pointerType; + this.pressure = 'pressure' in event && event.pressure; + this.rotationAngle = 'rotationAngle' in event && event.rotationAngle; + this.twist = ('twist' in event && event.twist) || 0; + this.tangentialPressure = ('tangentialPressure' in event && event.tangentialPressure) || 0; + }; + /** + * Resets the data for pooling. + */ + InteractionData.prototype.reset = function () { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + return InteractionData; +}()); - return image; -}; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} /** - * Will return a a base64 encoded string of this target. It works by calling - * `Extract.getCanvas` and then running toDataURL on that. + * Event class that mimics native DOM events. * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp". - * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92. - * @return {string} A base64 encoded string of the texture. + * @class + * @memberof PIXI */ -Extract.prototype.base64 = function base64 (target, format, quality) -{ - return this.canvas(target).toDataURL(format, quality); -}; +var InteractionEvent = /** @class */ (function () { + function InteractionEvent() { + /** + * Whether this event will continue propagating in the tree. + * + * Remaining events for the {@link stopsPropagatingAt} object + * will still be dispatched. + * + * @member {boolean} + */ + this.stopped = false; + /** + * At which object this event stops propagating. + * + * @private + * @member {PIXI.DisplayObject} + */ + this.stopsPropagatingAt = null; + /** + * Whether we already reached the element we want to + * stop propagating at. This is important for delayed events, + * where we start over deeper in the tree again. + * + * @private + * @member {boolean} + */ + this.stopPropagationHint = false; + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + /** + * Type of the event + * + * @member {string} + */ + this.type = null; + /** + * InteractionData related to this event + * + * @member {PIXI.InteractionData} + */ + this.data = null; + } + /** + * Prevents event from reaching any objects other than the current object. + * + */ + InteractionEvent.prototype.stopPropagation = function () { + this.stopped = true; + this.stopPropagationHint = true; + this.stopsPropagatingAt = this.currentTarget; + }; + /** + * Resets the event. + */ + InteractionEvent.prototype.reset = function () { + this.stopped = false; + this.stopsPropagatingAt = null; + this.stopPropagationHint = false; + this.currentTarget = null; + this.target = null; + }; + return InteractionEvent; +}()); /** - * Creates a Canvas element, renders this target to it and then returns it. + * DisplayObjects with the {@link PIXI.interactiveTarget} mixin use this class to track interactions * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + * @class + * @private + * @memberof PIXI */ -Extract.prototype.canvas = function canvas (target) -{ - var renderer = this.renderer; - var resolution; - var frame; - var flipY = false; - var renderTexture; - var generated = false; - - if (target) - { - if (target instanceof core.RenderTexture) - { - renderTexture = target; +var InteractionTrackingData = /** @class */ (function () { + /** + * @param {number} pointerId - Unique pointer id of the event + * @private + */ + function InteractionTrackingData(pointerId) { + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + InteractionTrackingData.prototype._doSet = function (flag, yn) { + if (yn) { + this._flags = this._flags | flag; } - else - { - renderTexture = this.renderer.generateTexture(target); - generated = true; + else { + this._flags = this._flags & (~flag); } - } - - if (renderTexture) - { - resolution = renderTexture.baseTexture.resolution; - frame = renderTexture.frame; - flipY = false; - renderer.renderTexture.bind(renderTexture); - } - else - { - resolution = this.renderer.resolution; - - flipY = true; - - frame = TEMP_RECT; - frame.width = this.renderer.width; - frame.height = this.renderer.height; - - renderer.renderTexture.bind(null); - } - - var width = Math.floor((frame.width * resolution) + 1e-4); - var height = Math.floor((frame.height * resolution) + 1e-4); - - var canvasBuffer = new utils.CanvasRenderTarget(width, height, 1); - - var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); - - // read pixels to the array - var gl = renderer.gl; - - gl.readPixels( - frame.x * resolution, - frame.y * resolution, - width, - height, - gl.RGBA, - gl.UNSIGNED_BYTE, - webglPixels - ); - - // add the pixels to the canvas - var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); - - Extract.arrayPostDivide(webglPixels, canvasData.data); - - canvasBuffer.context.putImageData(canvasData, 0, 0); - - // pulling pixels - if (flipY) - { - canvasBuffer.context.scale(1, -1); - canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); - } - - if (generated) - { - renderTexture.destroy(true); - } - - // send the canvas back.. - return canvasBuffer.canvas; -}; + }; + Object.defineProperty(InteractionTrackingData.prototype, "pointerId", { + /** + * Unique pointer id of the event + * + * @readonly + * @private + * @member {number} + */ + get: function () { + return this._pointerId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "flags", { + /** + * State of the tracking data, expressed as bit flags + * + * @private + * @member {number} + */ + get: function () { + return this._flags; + }, + set: function (flags) { + this._flags = flags; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "none", { + /** + * Is the tracked event inactive (not over or down)? + * + * @private + * @member {number} + */ + get: function () { + return this._flags === InteractionTrackingData.FLAGS.NONE; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "over", { + /** + * Is the tracked event over the DisplayObject? + * + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.OVER) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.OVER, yn); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "rightDown", { + /** + * Did the right mouse button come down in the DisplayObject? + * + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.RIGHT_DOWN) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.RIGHT_DOWN, yn); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "leftDown", { + /** + * Did the left mouse button come down in the DisplayObject? + * + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.LEFT_DOWN) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.LEFT_DOWN, yn); + }, + enumerable: false, + configurable: true + }); + InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2, + }); + return InteractionTrackingData; +}()); /** - * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA - * order, with integer values between 0 and 255 (included). + * Strategy how to search through stage tree for interactive objects * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @return {Uint8Array} One-dimensional array containing the pixel data of the entire texture + * @private + * @class + * @memberof PIXI */ -Extract.prototype.pixels = function pixels (target) -{ - var renderer = this.renderer; - var resolution; - var frame; - var renderTexture; - var generated = false; - - if (target) - { - if (target instanceof core.RenderTexture) - { - renderTexture = target; - } - else - { - renderTexture = this.renderer.generateTexture(target); - generated = true; - } +var TreeSearch = /** @class */ (function () { + function TreeSearch() { + this._tempPoint = new math.Point(); } - - if (renderTexture) - { - resolution = renderTexture.baseTexture.resolution; - frame = renderTexture.frame; - - // bind the buffer - renderer.renderTexture.bind(renderTexture); - } - else - { - resolution = renderer.resolution; - - frame = TEMP_RECT; - frame.width = renderer.width; - frame.height = renderer.height; - - renderer.renderTexture.bind(null); - } - - var width = frame.width * resolution; - var height = frame.height * resolution; - - var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); - - // read pixels to the array - var gl = renderer.gl; - - gl.readPixels( - frame.x * resolution, - frame.y * resolution, - width, - height, - gl.RGBA, - gl.UNSIGNED_BYTE, - webglPixels - ); - - if (generated) - { - renderTexture.destroy(true); - } - - Extract.arrayPostDivide(webglPixels, webglPixels); - - return webglPixels; -}; - -/** - * Destroys the extract - * - */ -Extract.prototype.destroy = function destroy () -{ - this.renderer.extract = null; - this.renderer = null; -}; - -/** - * Takes premultiplied pixel data and produces regular pixel data - * - * @private - * @param pixels {number[] | Uint8Array | Uint8ClampedArray} array of pixel data - * @param out {number[] | Uint8Array | Uint8ClampedArray} output array - */ -Extract.arrayPostDivide = function arrayPostDivide (pixels, out) -{ - for (var i = 0; i < pixels.length; i += 4) - { - var alpha = out[i + 3] = pixels[i + 3]; - - if (alpha !== 0) - { - out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0)); - out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0)); - out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0)); - } - else - { - out[i] = pixels[i]; - out[i + 1] = pixels[i + 1]; - out[i + 2] = pixels[i + 2]; - } - } -}; - -/** - * This namespace provides renderer-specific plugins for exporting content from a renderer. - * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels). - * - * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property. - * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. - * @example - * // Create a new app (will auto-add extract plugin to renderer) - * const app = new PIXI.Application(); - * - * // Draw a red circle - * const graphics = new PIXI.Graphics() - * .beginFill(0xFF0000) - * .drawCircle(0, 0, 50); - * - * // Render the graphics as an HTMLImageElement - * const image = app.renderer.plugins.extract.image(graphics); - * document.body.appendChild(image); - * @namespace PIXI.extract - */ - -exports.Extract = Extract; - - -},{"@pixi/core":17,"@pixi/math":29,"@pixi/utils":47}],20:[function(require,module,exports){ -/*! - * @pixi/filter-alpha - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/filter-alpha is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var core = require('@pixi/core'); - -var fragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"; - -/** - * Simplest filter - applies alpha. - * - * Use this instead of Container's alpha property to avoid visual layering of individual elements. - * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. - * If elements are not opaque, they will blend with each other anyway. - * - * Very handy if you want to use common features of all filters: - * - * 1. Assign a blendMode to this filter, blend all elements inside display object with background. - * - * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ -var AlphaFilter = /*@__PURE__*/(function (Filter) { - function AlphaFilter(alpha) - { - if ( alpha === void 0 ) alpha = 1.0; - - Filter.call(this, core.defaultVertex, fragment, { uAlpha: 1 }); - - this.alpha = alpha; - } - - if ( Filter ) AlphaFilter.__proto__ = Filter; - AlphaFilter.prototype = Object.create( Filter && Filter.prototype ); - AlphaFilter.prototype.constructor = AlphaFilter; - - var prototypeAccessors = { alpha: { configurable: true } }; - /** - * Coefficient for alpha multiplication + * Recursive implementation for findHit * - * @member {number} - * @default 1 + * @private + * @param {PIXI.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point */ - prototypeAccessors.alpha.get = function () - { - return this.uniforms.uAlpha; - }; - - prototypeAccessors.alpha.set = function (value) // eslint-disable-line require-jsdoc - { - this.uniforms.uAlpha = value; - }; - - Object.defineProperties( AlphaFilter.prototype, prototypeAccessors ); - - return AlphaFilter; -}(core.Filter)); - -exports.AlphaFilter = AlphaFilter; - - -},{"@pixi/core":17}],21:[function(require,module,exports){ -/*! - * @pixi/filter-blur - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/filter-blur is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var core = require('@pixi/core'); -var settings = require('@pixi/settings'); - -var vertTemplate = "\n attribute vec2 aVertexPosition;\n\n uniform mat3 projectionMatrix;\n\n uniform float strength;\n\n varying vec2 vBlurTexCoords[%size%];\n\n uniform vec4 inputSize;\n uniform vec4 outputFrame;\n\n vec4 filterVertexPosition( void )\n {\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n }\n\n vec2 filterTextureCoord( void )\n {\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n }\n\n void main(void)\n {\n gl_Position = filterVertexPosition();\n\n vec2 textureCoord = filterTextureCoord();\n %blur%\n }"; - -function generateBlurVertSource(kernelSize, x) -{ - var halfLength = Math.ceil(kernelSize / 2); - - var vertSource = vertTemplate; - - var blurLoop = ''; - var template; - // let value; - - if (x) - { - template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);'; - } - else - { - template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);'; - } - - for (var i = 0; i < kernelSize; i++) - { - var blur = template.replace('%index%', i); - - // value = i; - - // if(i >= halfLength) - // { - // value = kernelSize - i - 1; - // } - - blur = blur.replace('%sampleIndex%', ((i - (halfLength - 1)) + ".0")); - - blurLoop += blur; - blurLoop += '\n'; - } - - vertSource = vertSource.replace('%blur%', blurLoop); - vertSource = vertSource.replace('%size%', kernelSize); - - return vertSource; -} - -var GAUSSIAN_VALUES = { - 5: [0.153388, 0.221461, 0.250301], - 7: [0.071303, 0.131514, 0.189879, 0.214607], - 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], - 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], - 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], - 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448], -}; - -var fragTemplate = [ - 'varying vec2 vBlurTexCoords[%size%];', - 'uniform sampler2D uSampler;', - - 'void main(void)', - '{', - ' gl_FragColor = vec4(0.0);', - ' %blur%', - '}' ].join('\n'); - -function generateBlurFragSource(kernelSize) -{ - var kernel = GAUSSIAN_VALUES[kernelSize]; - var halfLength = kernel.length; - - var fragSource = fragTemplate; - - var blurLoop = ''; - var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; - var value; - - for (var i = 0; i < kernelSize; i++) - { - var blur = template.replace('%index%', i); - - value = i; - - if (i >= halfLength) - { - value = kernelSize - i - 1; + TreeSearch.prototype.recursiveFindHit = function (interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; } - - blur = blur.replace('%value%', kernel[value]); - - blurLoop += blur; - blurLoop += '\n'; - } - - fragSource = fragSource.replace('%blur%', blurLoop); - fragSource = fragSource.replace('%size%', kernelSize); - - return fragSource; -} - -/** - * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ -var BlurFilterPass = /*@__PURE__*/(function (Filter) { - function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) - { - kernelSize = kernelSize || 5; - var vertSrc = generateBlurVertSource(kernelSize, horizontal); - var fragSrc = generateBlurFragSource(kernelSize); - - Filter.call( - // vertex shader - this, vertSrc, - // fragment shader - fragSrc - ); - - this.horizontal = horizontal; - - this.resolution = resolution || settings.settings.RESOLUTION; - - this._quality = 0; - - this.quality = quality || 4; - - this.blur = strength || 8; - } - - if ( Filter ) BlurFilterPass.__proto__ = Filter; - BlurFilterPass.prototype = Object.create( Filter && Filter.prototype ); - BlurFilterPass.prototype.constructor = BlurFilterPass; - - var prototypeAccessors = { blur: { configurable: true },quality: { configurable: true } }; - - BlurFilterPass.prototype.apply = function apply (filterManager, input, output, clear) - { - if (output) - { - if (this.horizontal) - { - this.uniforms.strength = (1 / output.width) * (output.width / input.width); - } - else - { - this.uniforms.strength = (1 / output.height) * (output.height / input.height); + var point = interactionEvent.data.global; + // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimization once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimization is that an object is not hit test directly if a child has already been hit. + interactive = displayObject.interactive || interactive; + var hit = false; + var interactiveParent = interactive; + // Flag here can set to false if the event is outside the parents hitArea or mask + var hitTestChildren = true; + // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea + // There is also no longer a need to hitTest children. + if (displayObject.hitArea) { + if (hitTest) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hitTest = false; + hitTestChildren = false; + } + else { + hit = true; + } } + interactiveParent = false; } - else - { - if (this.horizontal) // eslint-disable-line - { - this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width); - } - else - { - this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line + // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask. + // We still want to hitTestChildren, however, to ensure a mouseout can still be generated. + // https://github.com/pixijs/pixi.js/issues/5135 + else if (displayObject._mask) { + if (hitTest) { + if (!(displayObject._mask.containsPoint && displayObject._mask.containsPoint(point))) { + hitTest = false; + } } } - - // screen space! - this.uniforms.strength *= this.strength; - this.uniforms.strength /= this.passes; - - if (this.passes === 1) - { - filterManager.applyFilter(this, input, output, clear); + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent); + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } } - else - { - var renderTarget = filterManager.getFilterTexture(); - var renderer = filterManager.renderer; - - var flip = input; - var flop = renderTarget; - - this.state.blend = false; - filterManager.applyFilter(this, flip, flop, false); - - for (var i = 1; i < this.passes - 1; i++) - { - renderer.renderTexture.bind(flip, flip.filterFrame); - - this.uniforms.uSampler = flop; - - var temp = flop; - - flop = flip; - flip = temp; - - renderer.shader.bind(this); - renderer.geometry.draw(5); + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + // already tested against hitArea if it is defined + if (!displayObject.hitArea && displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + if (func) { + func(interactionEvent, displayObject, !!hit); + } } - - this.state.blend = true; - filterManager.applyFilter(this, flop, output, clear); - filterManager.returnFilterTexture(renderTarget); } + return hit; }; /** - * Sets the strength of both the blur. - * - * @member {number} - * @default 16 - */ - prototypeAccessors.blur.get = function () - { - return this.strength; - }; - - prototypeAccessors.blur.set = function (value) // eslint-disable-line require-jsdoc - { - this.padding = 1 + (Math.abs(value) * 2); - this.strength = value; - }; - - /** - * Sets the quality of the blur by modifying the number of passes. More passes means higher - * quaility bluring but the lower the performance. + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. * - * @member {number} - * @default 4 + * @private + * @param {PIXI.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @return {boolean} returns true if the displayObject hit the point */ - prototypeAccessors.quality.get = function () - { - return this._quality; + TreeSearch.prototype.findHit = function (interactionEvent, displayObject, func, hitTest) { + this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false); }; - - prototypeAccessors.quality.set = function (value) // eslint-disable-line require-jsdoc - { - this._quality = value; - this.passes = value; - }; - - Object.defineProperties( BlurFilterPass.prototype, prototypeAccessors ); - - return BlurFilterPass; -}(core.Filter)); + return TreeSearch; +}()); /** - * The BlurFilter applies a Gaussian blur to an object. + * Interface for classes that represent a hit area. * - * The strength of the blur can be set for the x-axis and y-axis separately. + * It is implemented by the following classes: + * - {@link PIXI.Circle} + * - {@link PIXI.Ellipse} + * - {@link PIXI.Polygon} + * - {@link PIXI.RoundedRectangle} * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters + * @interface IHitArea + * @memberof PIXI */ -var BlurFilter = /*@__PURE__*/(function (Filter) { - function BlurFilter(strength, quality, resolution, kernelSize) - { - Filter.call(this); - - this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize); - this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize); - - this.resolution = resolution || settings.settings.RESOLUTION; - this.quality = quality || 4; - this.blur = strength || 8; - - this.repeatEdgePixels = false; - } - - if ( Filter ) BlurFilter.__proto__ = Filter; - BlurFilter.prototype = Object.create( Filter && Filter.prototype ); - BlurFilter.prototype.constructor = BlurFilter; - - var prototypeAccessors = { blur: { configurable: true },quality: { configurable: true },blurX: { configurable: true },blurY: { configurable: true },blendMode: { configurable: true },repeatEdgePixels: { configurable: true } }; - +/** + * Checks whether the x and y coordinates given are contained within this area + * + * @method + * @name contains + * @memberof PIXI.IHitArea# + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this area + */ +/** + * Default property values of interactive objects + * Used by {@link PIXI.InteractionManager} to automatically give all DisplayObjects these properties + * + * @private + * @name interactiveTarget + * @type {Object} + * @memberof PIXI + * @example + * function MyObject() {} + * + * Object.assign( + * DisplayObject.prototype, + * PIXI.interactiveTarget + * ); + */ +var interactiveTarget = { /** - * Applies the filter. + * Enable interaction events for the DisplayObject. Touch, pointer and mouse + * events will not be emitted unless `interactive` is set to `true`. * - * @param {PIXI.systems.FilterSystem} filterManager - The manager. - * @param {PIXI.RenderTexture} input - The input target. - * @param {PIXI.RenderTexture} output - The output target. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.on('tap', (event) => { + * //handle event + * }); + * @member {boolean} + * @memberof PIXI.DisplayObject# */ - BlurFilter.prototype.apply = function apply (filterManager, input, output, clear) - { - var xStrength = Math.abs(this.blurXFilter.strength); - var yStrength = Math.abs(this.blurYFilter.strength); - - if (xStrength && yStrength) - { - var renderTarget = filterManager.getFilterTexture(); - - this.blurXFilter.apply(filterManager, input, renderTarget, true); - this.blurYFilter.apply(filterManager, renderTarget, output, clear); - - filterManager.returnFilterTexture(renderTarget); - } - else if (yStrength) - { - this.blurYFilter.apply(filterManager, input, output, clear); - } - else - { - this.blurXFilter.apply(filterManager, input, output, clear); - } - }; - - BlurFilter.prototype.updatePadding = function updatePadding () - { - if (this._repeatEdgePixels) - { - this.padding = 0; - } - else - { - this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; - } - }; - + interactive: false, /** - * Sets the strength of both the blurX and blurY properties simultaneously + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows PixiJS to bypass a recursive `hitTest` function * - * @member {number} - * @default 2 + * @member {boolean} + * @memberof PIXI.Container# */ - prototypeAccessors.blur.get = function () - { - return this.blurXFilter.blur; - }; - - prototypeAccessors.blur.set = function (value) // eslint-disable-line require-jsdoc - { - this.blurXFilter.blur = this.blurYFilter.blur = value; - this.updatePadding(); - }; - + interactiveChildren: true, /** - * Sets the number of passes for blur. More passes means higher quaility bluring. + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. * - * @member {number} - * @default 1 + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); + * @member {PIXI.IHitArea} + * @memberof PIXI.DisplayObject# */ - prototypeAccessors.quality.get = function () - { - return this.blurXFilter.quality; - }; - - prototypeAccessors.quality.set = function (value) // eslint-disable-line require-jsdoc - { - this.blurXFilter.quality = this.blurYFilter.quality = value; - }; - + hitArea: null, /** - * Sets the strength of the blurX property + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. * - * @member {number} - * @default 2 + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# */ - prototypeAccessors.blurX.get = function () - { - return this.blurXFilter.blur; - }; - - prototypeAccessors.blurX.set = function (value) // eslint-disable-line require-jsdoc - { - this.blurXFilter.blur = value; - this.updatePadding(); - }; - + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } + else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, /** - * Sets the strength of the blurY property + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. * - * @member {number} - * @default 2 + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @member {string} + * @memberof PIXI.DisplayObject# */ - prototypeAccessors.blurY.get = function () - { - return this.blurYFilter.blur; - }; - - prototypeAccessors.blurY.set = function (value) // eslint-disable-line require-jsdoc - { - this.blurYFilter.blur = value; - this.updatePadding(); - }; - + cursor: null, /** - * Sets the blendmode of the filter + * Internal set of all active pointers, by identifier * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private */ - prototypeAccessors.blendMode.get = function () - { - return this.blurYFilter.blendMode; - }; - - prototypeAccessors.blendMode.set = function (value) // eslint-disable-line require-jsdoc - { - this.blurYFilter.blendMode = value; - }; - + get trackedPointers() { + if (this._trackedPointers === undefined) + { this._trackedPointers = {}; } + return this._trackedPointers; + }, /** - * If set to true the edge of the target will be clamped + * Map of all tracked pointers, by identifier. Use trackedPointers to access. * - * @member {bool} - * @default false + * @private + * @type {Map} */ - prototypeAccessors.repeatEdgePixels.get = function () - { - return this._repeatEdgePixels; - }; - - prototypeAccessors.repeatEdgePixels.set = function (value) - { - this._repeatEdgePixels = value; - this.updatePadding(); - }; - - Object.defineProperties( BlurFilter.prototype, prototypeAccessors ); - - return BlurFilter; -}(core.Filter)); - -exports.BlurFilter = BlurFilter; -exports.BlurFilterPass = BlurFilterPass; - - -},{"@pixi/core":17,"@pixi/settings":39}],22:[function(require,module,exports){ -/*! - * @pixi/filter-color-matrix - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/filter-color-matrix is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var core = require('@pixi/core'); - -var fragment = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"; + _trackedPointers: undefined, +}; +// Mix interactiveTarget into DisplayObject.prototype, +// after deprecation has been handled +display.DisplayObject.mixin(interactiveTarget); +var MOUSE_POINTER_ID = 1; +// helpers for hitTest() - only used inside hitTest() +var hitTestEvent = { + target: null, + data: { + global: null, + }, +}; /** - * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA - * color and alpha values of every pixel on your displayObject to produce a result - * with a new set of RGBA color and alpha values. It's pretty powerful! + * The interaction manager deals with mouse, touch and pointer events. + * + * Any DisplayObject can be interactive if its `interactive` property is set to true. + * + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction` * - * ```js - * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); - * container.filters = [colorMatrix]; - * colorMatrix.contrast(2); - * ``` - * @author Clément Chenebault * @class - * @extends PIXI.Filter - * @memberof PIXI.filters + * @extends PIXI.utils.EventEmitter + * @memberof PIXI */ -var ColorMatrixFilter = /*@__PURE__*/(function (Filter) { - function ColorMatrixFilter() - { - var uniforms = { - m: new Float32Array([1, 0, 0, 0, 0, - 0, 1, 0, 0, 0, - 0, 0, 1, 0, 0, - 0, 0, 0, 1, 0]), - uAlpha: 1, +var InteractionManager = /** @class */ (function (_super) { + __extends(InteractionManager, _super); + /** + * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Maximum requency (ms) at pointer over/out states will be checked. + * @param {number} [options.useSystemTicker=true] - Whether to add {@link tickerUpdate} to {@link PIXI.Ticker.system}. + */ + function InteractionManager(renderer, options) { + var _this = _super.call(this) || this; + options = options || {}; + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.AbstractRenderer} + */ + _this.renderer = renderer; + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + /** + * Maximum requency in milliseconds at which pointer over/out states will be checked by {@link tickerUpdate}. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + /** + * The mouse data + * + * @member {PIXI.InteractionData} + */ + _this.mouse = new InteractionData(); + _this.mouse.identifier = MOUSE_POINTER_ID; + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.InteractionData[]} + */ + _this.interactionDataPool = []; + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new InteractionEvent(); + /** + * The DOM element to bind to. + * + * @protected + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM version works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how PixiJS used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + /** + * Have events been attached to the dom element? + * + * @protected + * @member {boolean} + */ + _this.eventsAdded = false; + /** + * Has the system ticker been added? + * + * @protected + * @member {boolean} + */ + _this.tickerAdded = false; + /** + * Is the mouse hovering over the renderer? + * + * @protected + * @member {boolean} + */ + _this.mouseOverRenderer = false; + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + // this will make it so that you don't have to call bind all the time + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer', }; - - Filter.call(this, core.defaultFilterVertex, fragment, uniforms); - - this.alpha = 1; + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + /** + * Delayed pointer events. Used to guarantee correct ordering of over/out events. + * + * @private + * @member {Array} + */ + _this.delayedEvents = []; + /** + * TreeSearch component that is used to hitTest stage tree + * + * @private + * @member {PIXI.TreeSearch} + */ + _this.search = new TreeSearch(); + /** + * Used as a last rendered object in case renderer doesnt have _lastObjectRendered + * @member {DisplayObject} + * @private + */ + _this._tempDisplayObject = new display.TemporaryDisplayObject(); + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * + * @event PIXI.InteractionManager#mousedown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event PIXI.InteractionManager#rightdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * + * @event PIXI.InteractionManager#mouseup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event PIXI.InteractionManager#rightup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * + * @event PIXI.InteractionManager#click + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event PIXI.InteractionManager#rightclick + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.InteractionManager#event:mousedown}. + * + * @event PIXI.InteractionManager#mouseupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.InteractionManager#event:rightdown}. + * + * @event PIXI.InteractionManager#rightupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event PIXI.InteractionManager#mousemove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event PIXI.InteractionManager#mouseover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event PIXI.InteractionManager#mouseout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event PIXI.InteractionManager#pointerdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released over the display object. + * Not always fired when some buttons are held down while others are released. In those cases, + * use [mousedown]{@link PIXI.InteractionManager#event:mousedown} and + * [mouseup]{@link PIXI.InteractionManager#event:mouseup} instead. + * + * @event PIXI.InteractionManager#pointerup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a pointer event + * + * @event PIXI.InteractionManager#pointercancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event PIXI.InteractionManager#pointertap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.InteractionManager#event:pointerdown}. + * + * @event PIXI.InteractionManager#pointerupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved while over the display object + * + * @event PIXI.InteractionManager#pointermove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved onto the display object + * + * @event PIXI.InteractionManager#pointerover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved off the display object + * + * @event PIXI.InteractionManager#pointerout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed on the display object. + * + * @event PIXI.InteractionManager#touchstart + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed from the display object. + * + * @event PIXI.InteractionManager#touchend + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a touch + * + * @event PIXI.InteractionManager#touchcancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event PIXI.InteractionManager#tap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.InteractionManager#event:touchstart}. + * + * @event PIXI.InteractionManager#touchendoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is moved along the display object. + * + * @event PIXI.InteractionManager#touchmove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#click + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchend + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#tap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + _this._useSystemTicker = options.useSystemTicker !== undefined ? options.useSystemTicker : true; + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + return _this; } - - if ( Filter ) ColorMatrixFilter.__proto__ = Filter; - ColorMatrixFilter.prototype = Object.create( Filter && Filter.prototype ); - ColorMatrixFilter.prototype.constructor = ColorMatrixFilter; - - var prototypeAccessors = { matrix: { configurable: true },alpha: { configurable: true } }; - + Object.defineProperty(InteractionManager.prototype, "useSystemTicker", { + /** + * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}. + * + * @member {boolean} + * @default true + */ + get: function () { + return this._useSystemTicker; + }, + set: function (useSystemTicker) { + this._useSystemTicker = useSystemTicker; + if (useSystemTicker) { + this.addTickerListener(); + } + else { + this.removeTickerListener(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionManager.prototype, "lastObjectRendered", { + /** + * Last rendered object or temp object + * @readonly + * @protected + * @member {PIXI.DisplayObject} + */ + get: function () { + return this.renderer._lastObjectRendered || this._tempDisplayObject; + }, + enumerable: false, + configurable: true + }); /** - * Transforms current matrix and set the new one + * Hit tests a point against the display tree, returning the first interactive object that is hit. * - * @param {number[]} matrix - 5x4 matrix - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. + * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @return {PIXI.DisplayObject} The hit display object, if any. */ - ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix (matrix, multiply) - { - if ( multiply === void 0 ) multiply = false; - - var newMatrix = matrix; - - if (multiply) - { - this._multiply(newMatrix, this.uniforms.m, matrix); - newMatrix = this._colorMatrix(newMatrix); + InteractionManager.prototype.hitTest = function (globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.lastObjectRendered; } - - // set the new matrix - this.uniforms.m = newMatrix; + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + return hitTestEvent.target; }; - /** - * Multiplies two mat5's + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate + * another DOM element to receive those events. * - * @private - * @param {number[]} out - 5x4 matrix the receiving matrix - * @param {number[]} a - 5x4 matrix the first operand - * @param {number[]} b - 5x4 matrix the second operand - * @returns {number[]} 5x4 matrix + * @param {HTMLElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). */ - ColorMatrixFilter.prototype._multiply = function _multiply (out, a, b) - { - // Red Channel - out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); - out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); - out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); - out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); - out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4]; - - // Green Channel - out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); - out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); - out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); - out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); - out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9]; - - // Blue Channel - out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); - out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); - out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); - out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); - out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14]; - - // Alpha Channel - out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); - out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); - out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); - out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); - out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19]; - - return out; + InteractionManager.prototype.setTargetElement = function (element, resolution) { + if (resolution === void 0) { resolution = 1; } + this.removeTickerListener(); + this.removeEvents(); + this.interactionDOMElement = element; + this.resolution = resolution; + this.addEvents(); + this.addTickerListener(); }; - /** - * Create a Float32 Array and normalize the offset component to 0-1 + * Add the ticker listener * * @private - * @param {number[]} matrix - 5x4 matrix - * @return {number[]} 5x4 matrix with all values between 0-1 */ - ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix (matrix) - { - // Create a Float32 Array and normalize the offset component to 0-1 - var m = new Float32Array(matrix); - - m[4] /= 255; - m[9] /= 255; - m[14] /= 255; - m[19] /= 255; - - return m; + InteractionManager.prototype.addTickerListener = function () { + if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) { + return; + } + ticker.Ticker.system.add(this.tickerUpdate, this, ticker.UPDATE_PRIORITY.INTERACTION); + this.tickerAdded = true; }; - /** - * Adjusts brightness + * Remove the ticker listener * - * @param {number} b - value of the brigthness (0-1, where 0 is black) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private */ - ColorMatrixFilter.prototype.brightness = function brightness (b, multiply) - { - var matrix = [ - b, 0, 0, 0, 0, - 0, b, 0, 0, 0, - 0, 0, b, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.removeTickerListener = function () { + if (!this.tickerAdded) { + return; + } + ticker.Ticker.system.remove(this.tickerUpdate, this); + this.tickerAdded = false; }; - /** - * Set the matrices in grey scales + * Registers all the DOM events * - * @param {number} scale - value of the grey (0-1, where 0 is black) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private */ - ColorMatrixFilter.prototype.greyscale = function greyscale (scale, multiply) - { - var matrix = [ - scale, scale, scale, 0, 0, - scale, scale, scale, 0, 0, - scale, scale, scale, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.addEvents = function () { + if (this.eventsAdded || !this.interactionDOMElement) { + return; + } + var style = this.interactionDOMElement.style; + if (window.navigator.msPointerEnabled) { + style.msContentZooming = 'none'; + style.msTouchAction = 'none'; + } + else if (this.supportsPointerEvents) { + style.touchAction = 'none'; + } + /** + * These events are added first, so that if pointer events are normalized, they are fired + * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } + else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + this.eventsAdded = true; }; - /** - * Set the black and white matrice. + * Removes all the DOM events that were previously registered * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private */ - ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite (multiply) - { - var matrix = [ - 0.3, 0.6, 0.1, 0, 0, - 0.3, 0.6, 0.1, 0, 0, - 0.3, 0.6, 0.1, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.removeEvents = function () { + if (!this.eventsAdded || !this.interactionDOMElement) { + return; + } + var style = this.interactionDOMElement.style; + if (window.navigator.msPointerEnabled) { + style.msContentZooming = ''; + style.msTouchAction = ''; + } + else if (this.supportsPointerEvents) { + style.touchAction = ''; + } + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } + else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + this.interactionDOMElement = null; + this.eventsAdded = false; }; - /** - * Set the hue property of the color + * Updates the state of interactive objects if at least {@link interactionFrequency} + * milliseconds have passed since the last invocation. * - * @param {number} rotation - in degrees - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.hue = function hue (rotation, multiply) - { - rotation = (rotation || 0) / 180 * Math.PI; - - var cosR = Math.cos(rotation); - var sinR = Math.sin(rotation); - var sqrt = Math.sqrt; - - /* a good approximation for hue rotation - This matrix is far better than the versions with magic luminance constants - formerly used here, but also used in the starling framework (flash) and known from this - old part of the internet: quasimondo.com/archives/000565.php - - This new matrix is based on rgb cube rotation in space. Look here for a more descriptive - implementation as a shader not a general matrix: - https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js - - This is the source for the code: - see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 - */ - - var w = 1 / 3; - var sqrW = sqrt(w); // weight is - - var a00 = cosR + ((1.0 - cosR) * w); - var a01 = (w * (1.0 - cosR)) - (sqrW * sinR); - var a02 = (w * (1.0 - cosR)) + (sqrW * sinR); - - var a10 = (w * (1.0 - cosR)) + (sqrW * sinR); - var a11 = cosR + (w * (1.0 - cosR)); - var a12 = (w * (1.0 - cosR)) - (sqrW * sinR); - - var a20 = (w * (1.0 - cosR)) - (sqrW * sinR); - var a21 = (w * (1.0 - cosR)) + (sqrW * sinR); - var a22 = cosR + (w * (1.0 - cosR)); - - var matrix = [ - a00, a01, a02, 0, 0, - a10, a11, a12, 0, 0, - a20, a21, a22, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); - }; - - /** - * Set the contrast matrix, increase the separation between dark and bright - * Increase contrast : shadows darker and highlights brighter - * Decrease contrast : bring the shadows up and the highlights down + * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}. * - * @param {number} amount - value of the contrast (0-1) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @param {number} deltaTime - time delta since the last call */ - ColorMatrixFilter.prototype.contrast = function contrast (amount, multiply) - { - var v = (amount || 0) + 1; - var o = -0.5 * (v - 1); - - var matrix = [ - v, 0, 0, 0, o, - 0, v, 0, 0, o, - 0, 0, v, 0, o, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.tickerUpdate = function (deltaTime) { + this._deltaTime += deltaTime; + if (this._deltaTime < this.interactionFrequency) { + return; + } + this._deltaTime = 0; + this.update(); }; - /** - * Set the saturation matrix, increase the separation between colors - * Increase saturation : increase contrast, brightness, and sharpness - * - * @param {number} amount - The saturation amount (0-1) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * Updates the state of interactive objects. */ - ColorMatrixFilter.prototype.saturate = function saturate (amount, multiply) - { - if ( amount === void 0 ) amount = 0; - - var x = (amount * 2 / 3) + 1; - var y = ((x - 1) * -0.5); - - var matrix = [ - x, y, y, 0, 0, - y, x, y, 0, 0, - y, y, x, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.update = function () { + if (!this.interactionDOMElement) { + return; + } + // if the user move the mouse this check has already been done using the mouse move! + if (this._didMove) { + this._didMove = false; + return; + } + this.cursor = null; + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, true); + } + } + } + this.setCursorMode(this.cursor); }; - /** - * Desaturate image (remove color) - * - * Call the saturate function + * Sets the current cursor mode, handling any callbacks or CSS style changes. * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary */ - ColorMatrixFilter.prototype.desaturate = function desaturate () // eslint-disable-line no-unused-vars - { - this.saturate(-1); + InteractionManager.prototype.setCursorMode = function (mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + // only do things if there is a cursor style for it + if (style) { + switch (typeof style) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } + else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } }; - /** - * Negative image (inverse of classic rgb matrix) + * Dispatches an event on the display object that was interacted with * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {PIXI.InteractionEvent} eventData - the event data object + * @private */ - ColorMatrixFilter.prototype.negative = function negative (multiply) - { - var matrix = [ - -1, 0, 0, 1, 0, - 0, -1, 0, 1, 0, - 0, 0, -1, 1, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.dispatchEvent = function (displayObject, eventString, eventData) { + // Even if the event was stopped, at least dispatch any remaining events + // for the same display object. + if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + displayObject.emit(eventString, eventData); + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } }; - /** - * Sepia image + * Puts a event on a queue to be dispatched later. This is used to guarantee correct + * ordering of over/out events. * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private */ - ColorMatrixFilter.prototype.sepia = function sepia (multiply) - { - var matrix = [ - 0.393, 0.7689999, 0.18899999, 0, 0, - 0.349, 0.6859999, 0.16799999, 0, 0, - 0.272, 0.5339999, 0.13099999, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.delayDispatchEvent = function (displayObject, eventString, eventData) { + this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData }); }; - /** - * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @param {PIXI.IPointData} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map */ - ColorMatrixFilter.prototype.technicolor = function technicolor (multiply) - { - var matrix = [ - 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, - -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, - -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.mapPositionToPoint = function (point, x, y) { + var rect; + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } + else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + var resolutionMultiplier = 1.0 / this.resolution; + point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier; + point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier; }; - /** - * Polaroid filter + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @protected + * @param {PIXI.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - indicates whether we want to calculate hits + * or just iterate through all interactive objects */ - ColorMatrixFilter.prototype.polaroid = function polaroid (multiply) - { - var matrix = [ - 1.438, -0.062, -0.062, 0, 0, - -0.122, 1.378, -0.122, 0, 0, - -0.016, -0.016, 1.483, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.processInteractive = function (interactionEvent, displayObject, func, hitTest) { + var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest); + var delayedEvents = this.delayedEvents; + if (!delayedEvents.length) { + return hit; + } + // Reset the propagation hint, because we start deeper in the tree again. + interactionEvent.stopPropagationHint = false; + var delayedLen = delayedEvents.length; + this.delayedEvents = []; + for (var i = 0; i < delayedLen; i++) { + var _a = delayedEvents[i], displayObject_1 = _a.displayObject, eventString = _a.eventString, eventData = _a.eventData; + // When we reach the object we wanted to stop propagating at, + // set the propagation hint. + if (eventData.stopsPropagatingAt === displayObject_1) { + eventData.stopPropagationHint = true; + } + this.dispatchEvent(displayObject_1, eventString, eventData); + } + return hit; }; - /** - * Filter who transforms : Red -> Blue and Blue -> Red + * Is called when the pointer button is pressed down on the renderer element * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down */ - ColorMatrixFilter.prototype.toBGR = function toBGR (multiply) - { - var matrix = [ - 0, 0, 1, 0, 0, - 0, 1, 0, 0, 0, - 1, 0, 0, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.onPointerDown = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + if (this.autoPreventDefault && events[0].isNormalized) { + var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent); + if (cancelable) { + originalEvent.preventDefault(); + } + } + var eventLen = events.length; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerDown, true); + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } }; - /** - * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * Processes the result of the pointer down check and dispatches the event if need be * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private + * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object */ - ColorMatrixFilter.prototype.kodachrome = function kodachrome (multiply) - { - var matrix = [ - 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, - -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, - -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.processPointerDown = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new InteractionTrackingData(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } + else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } + else { + displayObject.trackedPointers[id].leftDown = true; + } + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } }; - /** - * Brown delicious browni filter (thanks Dominic Szablewski) + * Is called when the pointer button is released on the renderer element * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.browni = function browni (multiply) - { - var matrix = [ - 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, - -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, - 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + InteractionManager.prototype.onPointerComplete = function (originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + var eventLen = events.length; + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.lastObjectRendered, func, cancelled || !eventAppend); + this.emit(cancelled ? 'pointercancel' : "pointerup" + eventAppend, interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + this.emit(isRightButton ? "rightup" + eventAppend : "mouseup" + eventAppend, interactionEvent); + } + else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : "touchend" + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId); + } + } }; - /** - * Vintage filter (thanks Dominic Szablewski) + * Is called when the pointer button is cancelled * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released */ - ColorMatrixFilter.prototype.vintage = function vintage (multiply) - { - var matrix = [ - 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, - 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, - 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.onPointerCancel = function (event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') + { return; } + this.onPointerComplete(event, true, this.processPointerCancel); }; - /** - * We don't know exactly what it does, kind of gradient map, but funny to play with! + * Processes the result of the pointer cancel check and dispatches the event if need be * - * @param {number} desaturation - Tone values. - * @param {number} toned - Tone values. - * @param {string} lightColor - Tone values, example: `0xFFE580` - * @param {string} darkColor - Tone values, example: `0xFFE580` - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private + * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested */ - ColorMatrixFilter.prototype.colorTone = function colorTone (desaturation, toned, lightColor, darkColor, multiply) - { - desaturation = desaturation || 0.2; - toned = toned || 0.15; - lightColor = lightColor || 0xFFE580; - darkColor = darkColor || 0x338000; - - var lR = ((lightColor >> 16) & 0xFF) / 255; - var lG = ((lightColor >> 8) & 0xFF) / 255; - var lB = (lightColor & 0xFF) / 255; - - var dR = ((darkColor >> 16) & 0xFF) / 255; - var dG = ((darkColor >> 8) & 0xFF) / 255; - var dB = (darkColor & 0xFF) / 255; - - var matrix = [ - 0.3, 0.59, 0.11, 0, 0, - lR, lG, lB, desaturation, 0, - dR, dG, dB, toned, 0, - lR - dR, lG - dG, lB - dB, 0, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.processPointerCancel = function (interactionEvent, displayObject) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } }; - /** - * Night effect + * Is called when the pointer button is released on the renderer element * - * @param {number} intensity - The intensity of the night effect. - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released */ - ColorMatrixFilter.prototype.night = function night (intensity, multiply) - { - intensity = intensity || 0.1; - var matrix = [ - intensity * (-2.0), -intensity, 0, 0, 0, - -intensity, 0, intensity, 0, 0, - 0, intensity, intensity * 2.0, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.onPointerUp = function (event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') + { return; } + this.onPointerComplete(event, false, this.processPointerUp); }; - /** - * Predator effect + * Processes the result of the pointer up check and dispatches the event if need be * - * Erase the current matrix by setting a new indepent one + * @private + * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerUp = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + var trackingData = displayObject.trackedPointers[id]; + var isTouch = data.pointerType === 'touch'; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + // need to track mouse down status in the mouse block so that we can emit + // event in a later block + var isMouseTap = false; + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + var flags = InteractionTrackingData.FLAGS; + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + var isDown = trackingData !== undefined && (trackingData.flags & test); + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap + isMouseTap = true; + } + } + else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } + else { + trackingData.leftDown = false; + } + } + } + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchend', interactionEvent); } + if (trackingData) { + // emit pointertap if not a mouse, or if the mouse block decided it was a tap + if (!isMouse || isMouseTap) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + } + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } + else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); } + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + /** + * Is called when the pointer moves across the renderer element * - * @param {number} amount - how much the predator feels his future victim - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving */ - ColorMatrixFilter.prototype.predator = function predator (amount, multiply) - { - var matrix = [ - // row 1 - 11.224130630493164 * amount, - -4.794486999511719 * amount, - -2.8746118545532227 * amount, - 0 * amount, - 0.40342438220977783 * amount, - // row 2 - -3.6330697536468506 * amount, - 9.193157196044922 * amount, - -2.951810836791992 * amount, - 0 * amount, - -1.316135048866272 * amount, - // row 3 - -3.2184197902679443 * amount, - -4.2375030517578125 * amount, - 7.476448059082031 * amount, - 0 * amount, - 0.8044459223747253 * amount, - // row 4 - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.onPointerMove = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { + this._didMove = true; + this.cursor = null; + } + var eventLen = events.length; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerMove, true); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') + { this.emit('touchmove', interactionEvent); } + if (event.pointerType === 'mouse' || event.pointerType === 'pen') + { this.emit('mousemove', interactionEvent); } + } + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + // TODO BUG for parents interactive object (border order issue) + } }; - /** - * LSD effect + * Processes the result of the pointer move check and dispatches the event if need be * - * Multiply the current matrix + * @private + * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerMove = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var isTouch = data.pointerType === 'touch'; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); } + if (isMouse) + { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); } + } + }; + /** + * Is called when the pointer is moved out of the renderer element * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out */ - ColorMatrixFilter.prototype.lsd = function lsd (multiply) - { - var matrix = [ - 2, -0.4, 0.5, 0, 0, - -0.5, 2, -0.4, 0, 0, - -0.4, -0.5, 3, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, multiply); + InteractionManager.prototype.onPointerOut = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = event; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, false); + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } + else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } }; - /** - * Erase the current matrix by setting the default one + * Processes the result of the pointer over/out check and dispatches the event if need be * + * @private + * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object */ - ColorMatrixFilter.prototype.reset = function reset () - { - var matrix = [ - 1, 0, 0, 0, 0, - 0, 1, 0, 0, 0, - 0, 0, 1, 0, 0, - 0, 0, 0, 1, 0 ]; - - this._loadMatrix(matrix, false); + InteractionManager.prototype.processPointerOverOut = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + var trackingData = displayObject.trackedPointers[id]; + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id); + } + if (trackingData === undefined) + { return; } + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } + else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } }; - /** - * The matrix of the color matrix filter + * Is called when the pointer is moved into the renderer element * - * @member {number[]} - * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view */ - prototypeAccessors.matrix.get = function () - { - return this.uniforms.m; + InteractionManager.prototype.onPointerOver = function (originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = event; + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } }; - - prototypeAccessors.matrix.set = function (value) // eslint-disable-line require-jsdoc - { - this.uniforms.m = value; + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {PIXI.InteractionData} - Interaction data for the given pointer identifier + */ + InteractionManager.prototype.getInteractionDataForPointerId = function (event) { + var pointerId = event.pointerId; + var interactionData; + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } + else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } + else { + interactionData = this.interactionDataPool.pop() || new InteractionData(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData.copyEvent(event); + return interactionData; }; - /** - * The opacity value to use when mixing the original and resultant colors. + * Return unused InteractionData to the pool, for a given pointerId * - * When the value is 0, the original color is used without modification. - * When the value is 1, the result color is used. - * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + InteractionManager.prototype.releaseInteractionDataForPointerId = function (pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData.reset(); + this.interactionDataPool.push(interactionData); + } + }; + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData * - * @member {number} - * @default 1 + * @private + * @param {PIXI.InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {PIXI.InteractionData} interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @return {PIXI.InteractionEvent} the interaction event that was passed in */ - prototypeAccessors.alpha.get = function () - { - return this.uniforms.uAlpha; + InteractionManager.prototype.configureInteractionEventForDOMEvent = function (interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + interactionData.originalEvent = pointerEvent; + interactionEvent.reset(); + return interactionEvent; }; - - prototypeAccessors.alpha.set = function (value) // eslint-disable-line require-jsdoc - { - this.uniforms.uAlpha = value; + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + InteractionManager.prototype.normalizeToPointerData = function (event) { + var normalizedEvents = []; + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + if (typeof touch.button === 'undefined') + { touch.button = event.touches.length ? 1 : 0; } + if (typeof touch.buttons === 'undefined') + { touch.buttons = event.touches.length ? 1 : 0; } + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') + { touch.width = touch.radiusX || 1; } + if (typeof touch.height === 'undefined') + { touch.height = touch.radiusY || 1; } + if (typeof touch.tiltX === 'undefined') + { touch.tiltX = 0; } + if (typeof touch.tiltY === 'undefined') + { touch.tiltY = 0; } + if (typeof touch.pointerType === 'undefined') + { touch.pointerType = 'touch'; } + if (typeof touch.pointerId === 'undefined') + { touch.pointerId = touch.identifier || 0; } + if (typeof touch.pressure === 'undefined') + { touch.pressure = touch.force || 0.5; } + if (typeof touch.twist === 'undefined') + { touch.twist = 0; } + if (typeof touch.tangentialPressure === 'undefined') + { touch.tangentialPressure = 0; } + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') + { touch.layerX = touch.offsetX = touch.clientX; } + if (typeof touch.layerY === 'undefined') + { touch.layerY = touch.offsetY = touch.clientY; } + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + var tempEvent = event; + if (typeof tempEvent.isPrimary === 'undefined') + { tempEvent.isPrimary = true; } + if (typeof tempEvent.width === 'undefined') + { tempEvent.width = 1; } + if (typeof tempEvent.height === 'undefined') + { tempEvent.height = 1; } + if (typeof tempEvent.tiltX === 'undefined') + { tempEvent.tiltX = 0; } + if (typeof tempEvent.tiltY === 'undefined') + { tempEvent.tiltY = 0; } + if (typeof tempEvent.pointerType === 'undefined') + { tempEvent.pointerType = 'mouse'; } + if (typeof tempEvent.pointerId === 'undefined') + { tempEvent.pointerId = MOUSE_POINTER_ID; } + if (typeof tempEvent.pressure === 'undefined') + { tempEvent.pressure = 0.5; } + if (typeof tempEvent.twist === 'undefined') + { tempEvent.twist = 0; } + if (typeof tempEvent.tangentialPressure === 'undefined') + { tempEvent.tangentialPressure = 0; } + // mark the mouse event as normalized, just so that we know we did it + tempEvent.isNormalized = true; + normalizedEvents.push(tempEvent); + } + else { + normalizedEvents.push(event); + } + return normalizedEvents; }; + /** + * Destroys the interaction manager + * + */ + InteractionManager.prototype.destroy = function () { + this.removeEvents(); + this.removeTickerListener(); + this.removeAllListeners(); + this.renderer = null; + this.mouse = null; + this.eventData = null; + this.interactionDOMElement = null; + this.onPointerDown = null; + this.processPointerDown = null; + this.onPointerUp = null; + this.processPointerUp = null; + this.onPointerCancel = null; + this.processPointerCancel = null; + this.onPointerMove = null; + this.processPointerMove = null; + this.onPointerOut = null; + this.processPointerOverOut = null; + this.onPointerOver = null; + this.search = null; + }; + return InteractionManager; +}(utils.EventEmitter)); - Object.defineProperties( ColorMatrixFilter.prototype, prototypeAccessors ); - - return ColorMatrixFilter; -}(core.Filter)); - -// Americanized alias -ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; - -exports.ColorMatrixFilter = ColorMatrixFilter; +exports.InteractionData = InteractionData; +exports.InteractionEvent = InteractionEvent; +exports.InteractionManager = InteractionManager; +exports.InteractionTrackingData = InteractionTrackingData; +exports.interactiveTarget = interactiveTarget; -},{"@pixi/core":17}],23:[function(require,module,exports){ +},{"@pixi/display":9,"@pixi/math":20,"@pixi/ticker":37,"@pixi/utils":38}],19:[function(require,module,exports){ /*! - * @pixi/filter-displacement - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * @pixi/loaders - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @pixi/filter-displacement is licensed under the MIT License. + * @pixi/loaders is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); +var resourceLoader = require('resource-loader'); var core = require('@pixi/core'); -var math = require('@pixi/math'); -var vertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n"; +/** +* Reference to **{@link https://github.com/englercj/resource-loader +* resource-loader}**'s Resource class. +* @see http://englercj.github.io/resource-loader/Resource.html +* @class LoaderResource +* @memberof PIXI +*/ +var LoaderResource = resourceLoader.Resource; -var fragment = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n"; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} /** - * The DisplacementFilter class uses the pixel values from the specified texture - * (called the displacement map) to perform a displacement of an object. - * - * You can use this filter to apply all manor of crazy warping effects. - * Currently the `r` property of the texture is used to offset the `x` - * and the `g` property of the texture is used to offset the `y`. - * - * The way it works is it uses the values of the displacement map to look up the - * correct pixels to output. This means it's not technically moving the original. - * Instead, it's starting at the output and asking "which pixel from the original goes here". - * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`, - * this filter will output the pixel approximately 20 pixels to the right of the original. - * + * Loader plugin for handling Texture resources. * @class - * @extends PIXI.Filter - * @memberof PIXI.filters + * @memberof PIXI + * @implements PIXI.ILoaderPlugin */ -var DisplacementFilter = /*@__PURE__*/(function (Filter) { - function DisplacementFilter(sprite, scale) - { - var maskMatrix = new math.Matrix(); - - sprite.renderable = false; - - Filter.call(this, vertex, fragment, { - mapSampler: sprite._texture, - filterMatrix: maskMatrix, - scale: { x: 1, y: 1 }, - rotation: new Float32Array([1, 0, 0, 1]), - }); - - this.maskSprite = sprite; - this.maskMatrix = maskMatrix; - - if (scale === null || scale === undefined) - { - scale = 20; - } - - /** - * scaleX, scaleY for displacements - * @member {PIXI.Point} - */ - this.scale = new math.Point(scale, scale); +var TextureLoader = /** @class */ (function () { + function TextureLoader() { } - - if ( Filter ) DisplacementFilter.__proto__ = Filter; - DisplacementFilter.prototype = Object.create( Filter && Filter.prototype ); - DisplacementFilter.prototype.constructor = DisplacementFilter; - - var prototypeAccessors = { map: { configurable: true } }; - /** - * Applies the filter. - * - * @param {PIXI.systems.FilterSystem} filterManager - The manager. - * @param {PIXI.RenderTexture} input - The input target. - * @param {PIXI.RenderTexture} output - The output target. - * @param {boolean} clear - Should the output be cleared before rendering to it. + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param {PIXI.LoaderResource} resource + * @param {function} next */ - DisplacementFilter.prototype.apply = function apply (filterManager, input, output, clear) - { - // fill maskMatrix with _normalized sprite texture coords_ - this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); - this.uniforms.scale.x = this.scale.x; - this.uniforms.scale.y = this.scale.y; - - // Extract rotation from world transform - var wt = this.maskSprite.transform.worldTransform; - var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b)); - var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d)); - - if (lenX !== 0 && lenY !== 0) - { - this.uniforms.rotation[0] = wt.a / lenX; - this.uniforms.rotation[1] = wt.b / lenX; - this.uniforms.rotation[2] = wt.c / lenY; - this.uniforms.rotation[3] = wt.d / lenY; + TextureLoader.use = function (resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = core.Texture.fromLoader(resource.data, resource.url, resource.name); } - - // draw the filter... - filterManager.applyFilter(this, input, output, clear); - }; - - /** - * The texture used for the displacement map. Must be power of 2 sized texture. - * - * @member {PIXI.Texture} - */ - prototypeAccessors.map.get = function () - { - return this.uniforms.mapSampler; - }; - - prototypeAccessors.map.set = function (value) // eslint-disable-line require-jsdoc - { - this.uniforms.mapSampler = value; + next(); }; - - Object.defineProperties( DisplacementFilter.prototype, prototypeAccessors ); - - return DisplacementFilter; -}(core.Filter)); - -exports.DisplacementFilter = DisplacementFilter; - - -},{"@pixi/core":17,"@pixi/math":29}],24:[function(require,module,exports){ -/*! - * @pixi/filter-fxaa - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/filter-fxaa is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var core = require('@pixi/core'); - -var vertex = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputPixel;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"; - -var fragment = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputPixel;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n"; + return TextureLoader; +}()); /** - * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com - * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL. + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader * - * @see https://github.com/mitsuhiko/webgl-meincraft + * ```js + * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use. + * //or + * const loader = new PIXI.Loader(); // you can also create your own if you want * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader * + * @class Loader + * @memberof PIXI + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. */ -var FXAAFilter = /*@__PURE__*/(function (Filter) { - function FXAAFilter() - { - // TODO - needs work - Filter.call(this, vertex, fragment); +var Loader = /** @class */ (function (_super) { + __extends(Loader, _super); + function Loader(baseUrl, concurrency) { + var _this = _super.call(this, baseUrl, concurrency) || this; + for (var i = 0; i < Loader._plugins.length; ++i) { + var plugin = Loader._plugins[i]; + var pre = plugin.pre, use = plugin.use; + if (pre) { + _this.pre(pre); + } + if (use) { + _this.use(use); + } + } + /** + * If this loader cannot be destroyed. + * @member {boolean} + * @default false + * @private + */ + _this._protected = false; + return _this; } - - if ( Filter ) FXAAFilter.__proto__ = Filter; - FXAAFilter.prototype = Object.create( Filter && Filter.prototype ); - FXAAFilter.prototype.constructor = FXAAFilter; - - return FXAAFilter; -}(core.Filter)); - -exports.FXAAFilter = FXAAFilter; - - -},{"@pixi/core":17}],25:[function(require,module,exports){ -/*! - * @pixi/filter-noise - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + /** + * Destroy the loader, removes references. + * @memberof PIXI.Loader# + * @method destroy + * @public + */ + Loader.prototype.destroy = function () { + if (!this._protected) { + this.reset(); + } + }; + Object.defineProperty(Loader, "shared", { + /** + * A premade instance of the loader that can be used to load resources. + * @name shared + * @type {PIXI.Loader} + * @static + * @memberof PIXI.Loader + */ + get: function () { + var shared = Loader._shared; + if (!shared) { + shared = new Loader(); + shared._protected = true; + Loader._shared = shared; + } + return shared; + }, + enumerable: false, + configurable: true + }); + /** + * Adds a Loader plugin for the global shared loader and all + * new Loader instances created. + * + * @static + * @method registerPlugin + * @memberof PIXI.Loader + * @param {PIXI.ILoaderPlugin} plugin - The plugin to add + * @return {PIXI.Loader} Reference to PIXI.Loader for chaining + */ + Loader.registerPlugin = function (plugin) { + Loader._plugins.push(plugin); + if (plugin.add) { + plugin.add(); + } + return Loader; + }; + /** + * Collection of all installed `use` middleware for Loader. + * + * @static + * @member {Array} _plugins + * @memberof PIXI.Loader + * @private + */ + Loader._plugins = []; + return Loader; +}(resourceLoader.Loader)); +// parse any blob into more usable objects (e.g. Image) +Loader.registerPlugin({ use: resourceLoader.middleware.parsing }); +// parse any Image objects into textures +Loader.registerPlugin(TextureLoader); +/** + * Plugin to be installed for handling specific Loader resources. * - * @pixi/filter-noise is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license + * @memberof PIXI + * @typedef {object} ILoaderPlugin + * @property {function} [add] - Function to call immediate after registering plugin. + * @property {PIXI.Loader.loaderMiddleware} [pre] - Middleware function to run before load, the + * arguments for this are `(resource, next)` + * @property {PIXI.Loader.loaderMiddleware} [use] - Middleware function to run after load, the + * arguments for this are `(resource, next)` */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var core = require('@pixi/core'); - -var fragment = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"; - /** - * @author Vico @vicocotea - * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + * @memberof PIXI.Loader + * @typedef {object} ICallbackID + */ +/** + * @memberof PIXI.Loader + * @typedef {function} ISignalCallback + * @param {function} callback - Callback function + * @param {object} [context] - Context + * @returns {ICallbackID} - CallbackID + */ +/** + * @memberof PIXI.Loader + * @typedef {function} ISignalDetach + * @param {ICallbackID} id - CallbackID returned by `add`/`once` methods + */ +/** + * @memberof PIXI.Loader + * @typedef ILoaderSignal + * @property {ISignalCallback} add - Register callback + * @property {ISignalCallback} once - Register oneshot callback + * @property {ISignalDetach} detach - Detach specific callback by ID + */ +/** + * @memberof PIXI.Loader + * @callback loaderMiddleware + * @param {PIXI.LoaderResource} resource + * @param {function} next + */ +/** + * @memberof PIXI.Loader# + * @description Dispatched when the loader begins to loading process. + * @member {PIXI.Loader.ILoaderSignal} onStart + */ +/** + * @memberof PIXI.Loader# + * @description Dispatched once per loaded or errored resource. + * @member {PIXI.Loader.ILoaderSignal} onProgress + */ +/** + * @memberof PIXI.Loader# + * @description Dispatched once per errored resource. + * @member {PIXI.Loader.ILoaderSignal} onError + */ +/** + * @memberof PIXI.Loader# + * @description Dispatched once per loaded resource. + * @member {PIXI.Loader.ILoaderSignal} onLoad + */ +/** + * @memberof PIXI.Loader# + * @description Dispatched when completely loaded all resources. + * @member {PIXI.Loader.ILoaderSignal} onComplete */ /** - * A Noise effect filter. - * + * Application plugin for supporting loader option. Installing the LoaderPlugin + * is not necessary if using **pixi.js** or **pixi.js-legacy**. + * @example + * import {AppLoaderPlugin} from '@pixi/loaders'; + * import {Application} from '@pixi/app'; + * Application.registerPlugin(AppLoaderPlugin); * @class - * @extends PIXI.Filter - * @memberof PIXI.filters + * @memberof PIXI */ -var NoiseFilter = /*@__PURE__*/(function (Filter) { - function NoiseFilter(noise, seed) - { - if ( noise === void 0 ) noise = 0.5; - if ( seed === void 0 ) seed = Math.random(); - - Filter.call(this, core.defaultFilterVertex, fragment, { - uNoise: 0, - uSeed: 0, - }); - - this.noise = noise; - this.seed = seed; +var AppLoaderPlugin = /** @class */ (function () { + function AppLoaderPlugin() { } - - if ( Filter ) NoiseFilter.__proto__ = Filter; - NoiseFilter.prototype = Object.create( Filter && Filter.prototype ); - NoiseFilter.prototype.constructor = NoiseFilter; - - var prototypeAccessors = { noise: { configurable: true },seed: { configurable: true } }; - /** - * The amount of noise to apply, this value should be in the range (0, 1]. - * - * @member {number} - * @default 0.5 + * Called on application constructor + * @param {object} options + * @private */ - prototypeAccessors.noise.get = function () - { - return this.uniforms.uNoise; - }; - - prototypeAccessors.noise.set = function (value) // eslint-disable-line require-jsdoc - { - this.uniforms.uNoise = value; + AppLoaderPlugin.init = function (options) { + options = Object.assign({ + sharedLoader: false, + }, options); + /** + * Loader instance to help with asset loading. + * @name PIXI.Application#loader + * @type {PIXI.Loader} + * @readonly + */ + this.loader = options.sharedLoader ? Loader.shared : new Loader(); }; - /** - * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. - * - * @member {number} + * Called when application destroyed + * @private */ - prototypeAccessors.seed.get = function () - { - return this.uniforms.uSeed; - }; - - prototypeAccessors.seed.set = function (value) // eslint-disable-line require-jsdoc - { - this.uniforms.uSeed = value; + AppLoaderPlugin.destroy = function () { + if (this.loader) { + this.loader.destroy(); + this.loader = null; + } }; + return AppLoaderPlugin; +}()); - Object.defineProperties( NoiseFilter.prototype, prototypeAccessors ); - - return NoiseFilter; -}(core.Filter)); - -exports.NoiseFilter = NoiseFilter; +exports.AppLoaderPlugin = AppLoaderPlugin; +exports.Loader = Loader; +exports.LoaderResource = LoaderResource; +exports.TextureLoader = TextureLoader; -},{"@pixi/core":17}],26:[function(require,module,exports){ +},{"@pixi/core":8,"resource-loader":50}],20:[function(require,module,exports){ /*! - * @pixi/graphics - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * @pixi/math - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @pixi/graphics is licensed under the MIT License. + * @pixi/math is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); -var core = require('@pixi/core'); -var math = require('@pixi/math'); -var utils = require('@pixi/utils'); -var constants = require('@pixi/constants'); -var display = require('@pixi/display'); - /** - * Graphics curves resolution settings. If `adaptive` flag is set to `true`, - * the resolution is calculated based on the curve's length to ensure better visual quality. - * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. + * Two Pi. * * @static - * @constant + * @constant {number} PI_2 * @memberof PIXI - * @name GRAPHICS_CURVES - * @type {object} - * @property {boolean} adaptive=false - flag indicating if the resolution should be adaptive - * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored) - * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored) - * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored) */ -var GRAPHICS_CURVES = { - adaptive: true, - maxLength: 10, - minSegments: 8, - maxSegments: 2048, - _segmentsCount: function _segmentsCount(length, defaultSegments) - { - if ( defaultSegments === void 0 ) defaultSegments = 20; - - if (!this.adaptive) - { - return defaultSegments; - } - - var result = Math.ceil(length / this.maxLength); - - if (result < this.minSegments) - { - result = this.minSegments; - } - else if (result > this.maxSegments) - { - result = this.maxSegments; - } - - return result; - }, -}; - +var PI_2 = Math.PI * 2; /** - * Fill style object for Graphics. + * Conversion factor for converting radians to degrees. * - * @class + * @static + * @constant {number} RAD_TO_DEG * @memberof PIXI */ -var FillStyle = function FillStyle() -{ - this.reset(); -}; - +var RAD_TO_DEG = 180 / Math.PI; /** - * Clones the object + * Conversion factor for converting degrees to radians. * - * @return {PIXI.FillStyle} + * @static + * @constant {number} DEG_TO_RAD + * @memberof PIXI + */ +var DEG_TO_RAD = Math.PI / 180; +(function (SHAPES) { + SHAPES[SHAPES["POLY"] = 0] = "POLY"; + SHAPES[SHAPES["RECT"] = 1] = "RECT"; + SHAPES[SHAPES["CIRC"] = 2] = "CIRC"; + SHAPES[SHAPES["ELIP"] = 3] = "ELIP"; + SHAPES[SHAPES["RREC"] = 4] = "RREC"; +})(exports.SHAPES || (exports.SHAPES = {})); +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {enum} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + * @enum {number} */ -FillStyle.prototype.clone = function clone () -{ - var obj = new FillStyle(); - - obj.color = this.color; - obj.alpha = this.alpha; - obj.texture = this.texture; - obj.matrix = this.matrix; - obj.visible = this.visible; - - return obj; -}; /** - * Reset + * Size object, contains width and height + * + * @memberof PIXI + * @typedef {object} ISize + * @property {number} width - Width component + * @property {number} height - Height component + */ +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI */ -FillStyle.prototype.reset = function reset () -{ +var Rectangle = /** @class */ (function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle(x, y, width, height) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + /** + * @member {number} + * @default 0 + */ + this.x = Number(x); + /** + * @member {number} + * @default 0 + */ + this.y = Number(y); + /** + * @member {number} + * @default 0 + */ + this.width = Number(width); + /** + * @member {number} + * @default 0 + */ + this.height = Number(height); + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = exports.SHAPES.RECT; + } + Object.defineProperty(Rectangle.prototype, "left", { + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + get: function () { + return this.x; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "right", { + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + get: function () { + return this.x + this.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "top", { + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + get: function () { + return this.y; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottom", { + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + get: function () { + return this.y + this.height; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle, "EMPTY", { + /** + * A constant empty rectangle. + * + * @static + * @constant + * @member {PIXI.Rectangle} + * @return {PIXI.Rectangle} An empty rectangle + */ + get: function () { + return new Rectangle(0, 0, 0, 0); + }, + enumerable: false, + configurable: true + }); /** - * The hex color value used when coloring the Graphics object. + * Creates a clone of this Rectangle * - * @member {number} - * @default 1 + * @return {PIXI.Rectangle} a copy of the rectangle */ - this.color = 0xFFFFFF; - + Rectangle.prototype.clone = function () { + return new Rectangle(this.x, this.y, this.width, this.height); + }; /** - * The alpha value used when filling the Graphics object. + * Copies another rectangle to this one. * - * @member {number} - * @default 1 + * @param {PIXI.Rectangle} rectangle - The rectangle to copy from. + * @return {PIXI.Rectangle} Returns itself. */ - this.alpha = 1; - + Rectangle.prototype.copyFrom = function (rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + return this; + }; /** - * The texture to be used for the fill. + * Copies this rectangle to another one. * - * @member {string} - * @default 0 + * @param {PIXI.Rectangle} rectangle - The rectangle to copy to. + * @return {PIXI.Rectangle} Returns given parameter. */ - this.texture = core.Texture.WHITE; - + Rectangle.prototype.copyTo = function (rectangle) { + rectangle.x = this.x; + rectangle.y = this.y; + rectangle.width = this.width; + rectangle.height = this.height; + return rectangle; + }; /** - * The transform aplpied to the texture. + * Checks whether the x and y coordinates given are contained within this Rectangle * - * @member {string} - * @default 0 + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle */ - this.matrix = null; - + Rectangle.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + return false; + }; /** - * If the current fill is visible. + * Pads the rectangle making it grow in all directions. + * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. * - * @member {boolean} - * @default false + * @param {number} [paddingX=0] - The horizontal padding amount. + * @param {number} [paddingY=0] - The vertical padding amount. + * @return {PIXI.Rectangle} Returns itself. */ - this.visible = false; -}; - -/** - * Destroy and don't use after this - */ -FillStyle.prototype.destroy = function destroy () -{ - this.texture = null; - this.matrix = null; -}; - -/** - * Builds a polygon to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines - */ -var buildPoly = { - - build: function build(graphicsData) - { - graphicsData.points = graphicsData.shape.points.slice(); - }, - - triangulate: function triangulate(graphicsData, graphicsGeometry) - { - var points = graphicsData.points; - var holes = graphicsData.holes; - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - - if (points.length >= 6) - { - var holeArray = []; - // Process holes.. - - for (var i = 0; i < holes.length; i++) - { - var hole = holes[i]; - - holeArray.push(points.length / 2); - points = points.concat(hole.points); - } - - // sort color - var triangles = utils.earcut(points, holeArray, 2); - - if (!triangles) - { - return; - } - - var vertPos = verts.length / 2; - - for (var i$1 = 0; i$1 < triangles.length; i$1 += 3) - { - indices.push(triangles[i$1] + vertPos); - indices.push(triangles[i$1 + 1] + vertPos); - indices.push(triangles[i$1 + 2] + vertPos); - } - - for (var i$2 = 0; i$2 < points.length; i$2++) - { - verts.push(points[i$2]); - } - } - }, -}; + Rectangle.prototype.pad = function (paddingX, paddingY) { + if (paddingX === void 0) { paddingX = 0; } + if (paddingY === void 0) { paddingY = paddingX; } + this.x -= paddingX; + this.y -= paddingY; + this.width += paddingX * 2; + this.height += paddingY * 2; + return this; + }; + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + * @return {PIXI.Rectangle} Returns itself. + */ + Rectangle.prototype.fit = function (rectangle) { + var x1 = Math.max(this.x, rectangle.x); + var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.max(this.y, rectangle.y); + var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = Math.max(x2 - x1, 0); + this.y = y1; + this.height = Math.max(y2 - y1, 0); + return this; + }; + /** + * Enlarges rectangle that way its corners lie on grid + * + * @param {number} [resolution=1] resolution + * @param {number} [eps=0.001] precision + * @return {PIXI.Rectangle} Returns itself. + */ + Rectangle.prototype.ceil = function (resolution, eps) { + if (resolution === void 0) { resolution = 1; } + if (eps === void 0) { eps = 0.001; } + var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; + var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; + this.x = Math.floor((this.x + eps) * resolution) / resolution; + this.y = Math.floor((this.y + eps) * resolution) / resolution; + this.width = x2 - this.x; + this.height = y2 - this.y; + return this; + }; + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + * @return {PIXI.Rectangle} Returns itself. + */ + Rectangle.prototype.enlarge = function (rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + return this; + }; + return Rectangle; +}()); /** - * Builds a circle to draw - * - * Ignored from docs since it is not directly exposed. + * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects. * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + * @class + * @memberof PIXI */ -var buildCircle = { - - build: function build(graphicsData) - { - // need to convert points to a nice regular data - var circleData = graphicsData.shape; - var points = graphicsData.points; - var x = circleData.x; - var y = circleData.y; - var width; - var height; - - points.length = 0; - - // TODO - bit hacky?? - if (graphicsData.type === math.SHAPES.CIRC) - { - width = circleData.radius; - height = circleData.radius; - } - else - { - width = circleData.width; - height = circleData.height; - } - - if (width === 0 || height === 0) - { - return; - } - - var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) - || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); - - totalSegs /= 2.3; - - var seg = (Math.PI * 2) / totalSegs; - - for (var i = 0; i < totalSegs; i++) - { - points.push( - x + (Math.sin(-seg * i) * width), - y + (Math.cos(-seg * i) * height) - ); - } - - points.push( - points[0], - points[1] - ); - }, - - triangulate: function triangulate(graphicsData, graphicsGeometry) - { - var points = graphicsData.points; - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - - var vertPos = verts.length / 2; - var center = vertPos; - - verts.push(graphicsData.shape.x, graphicsData.shape.y); - - for (var i = 0; i < points.length; i += 2) - { - verts.push(points[i], points[i + 1]); - - // add some uvs - indices.push(vertPos++, center, vertPos); +var Circle = /** @class */ (function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle(x, y, radius) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (radius === void 0) { radius = 0; } + /** + * @member {number} + * @default 0 + */ + this.x = x; + /** + * @member {number} + * @default 0 + */ + this.y = y; + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = exports.SHAPES.CIRC; + } + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + Circle.prototype.clone = function () { + return new Circle(this.x, this.y, this.radius); + }; + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + Circle.prototype.contains = function (x, y) { + if (this.radius <= 0) { + return false; } - }, -}; + var r2 = this.radius * this.radius; + var dx = (this.x - x); + var dy = (this.y - y); + dx *= dx; + dy *= dy; + return (dx + dy <= r2); + }; + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + Circle.prototype.getBounds = function () { + return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + return Circle; +}()); /** - * Builds a rectangle to draw - * - * Ignored from docs since it is not directly exposed. + * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects. * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + * @class + * @memberof PIXI */ -var buildRectangle = { - - build: function build(graphicsData) - { - // --- // - // need to convert points to a nice regular data - // - var rectData = graphicsData.shape; - var x = rectData.x; - var y = rectData.y; - var width = rectData.width; - var height = rectData.height; - - var points = graphicsData.points; - - points.length = 0; - - points.push(x, y, - x + width, y, - x + width, y + height, - x, y + height); - }, - - triangulate: function triangulate(graphicsData, graphicsGeometry) - { - var points = graphicsData.points; - var verts = graphicsGeometry.points; - - var vertPos = verts.length / 2; - - verts.push(points[0], points[1], - points[2], points[3], - points[6], points[7], - points[4], points[5]); - - graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, - vertPos + 1, vertPos + 2, vertPos + 3); - }, -}; +var Ellipse = /** @class */ (function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this ellipse + * @param {number} [y=0] - The Y coordinate of the center of this ellipse + * @param {number} [halfWidth=0] - The half width of this ellipse + * @param {number} [halfHeight=0] - The half height of this ellipse + */ + function Ellipse(x, y, halfWidth, halfHeight) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (halfWidth === void 0) { halfWidth = 0; } + if (halfHeight === void 0) { halfHeight = 0; } + /** + * @member {number} + * @default 0 + */ + this.x = x; + /** + * @member {number} + * @default 0 + */ + this.y = y; + /** + * @member {number} + * @default 0 + */ + this.width = halfWidth; + /** + * @member {number} + * @default 0 + */ + this.height = halfHeight; + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = exports.SHAPES.ELIP; + } + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + Ellipse.prototype.clone = function () { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + Ellipse.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + // normalize the coords to an ellipse with center 0,0 + var normx = ((x - this.x) / this.width); + var normy = ((y - this.y) / this.height); + normx *= normx; + normy *= normy; + return (normx + normy <= 1); + }; + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + Ellipse.prototype.getBounds = function () { + return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + }; + return Ellipse; +}()); /** - * Builds a rounded rectangle to draw - * - * Ignored from docs since it is not directly exposed. + * A class to define a shape via user defined co-orinates. * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + * @class + * @memberof PIXI */ -var buildRoundedRectangle = { - - build: function build(graphicsData) - { - var rrectData = graphicsData.shape; - var points = graphicsData.points; - var x = rrectData.x; - var y = rrectData.y; - var width = rrectData.width; - var height = rrectData.height; - - var radius = rrectData.radius; - - points.length = 0; - - quadraticBezierCurve(x, y + radius, - x, y, - x + radius, y, - points); - quadraticBezierCurve(x + width - radius, - y, x + width, y, - x + width, y + radius, - points); - quadraticBezierCurve(x + width, y + height - radius, - x + width, y + height, - x + width - radius, y + height, - points); - quadraticBezierCurve(x + radius, y + height, - x, y + height, - x, y + height - radius, - points); - - // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. - // TODO - fix this properly, this is not very elegant.. but it works for now. - }, - - triangulate: function triangulate(graphicsData, graphicsGeometry) - { - var points = graphicsData.points; - - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - - var vecPos = verts.length / 2; - - var triangles = utils.earcut(points, null, 2); +var Polygon = /** @class */ (function () { + /** + * @param {PIXI.IPoint[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + var arguments$1 = arguments; - for (var i = 0, j = triangles.length; i < j; i += 3) - { - indices.push(triangles[i] + vecPos); - // indices.push(triangles[i] + vecPos); - indices.push(triangles[i + 1] + vecPos); - // indices.push(triangles[i + 2] + vecPos); - indices.push(triangles[i + 2] + vecPos); + var points = []; + for (var _i = 0; _i < arguments.length; _i++) { + points[_i] = arguments$1[_i]; } - - for (var i$1 = 0, j$1 = points.length; i$1 < j$1; i$1++) - { - verts.push(points[i$1], points[++i$1]); + var flat = Array.isArray(points[0]) ? points[0] : points; + // if this is an array of points, convert it to a flat array of numbers + if (typeof flat[0] !== 'number') { + var p = []; + for (var i = 0, il = flat.length; i < il; i++) { + p.push(flat[i].x, flat[i].y); + } + flat = p; } - }, -}; - -/** - * Calculate a single point for a quadratic bezier curve. - * Utility function used by quadraticBezierCurve. - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {number} n1 - first number - * @param {number} n2 - second number - * @param {number} perc - percentage - * @return {number} the result - * - */ -function getPt(n1, n2, perc) -{ - var diff = n2 - n1; - - return n1 + (diff * perc); -} + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = flat; + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = exports.SHAPES.POLY; + /** + * `false` after moveTo, `true` after `closePath`. In all other cases it is `true`. + * @member {boolean} + * @default true + */ + this.closeStroke = true; + } + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + Polygon.prototype.clone = function () { + var points = this.points.slice(); + var polygon = new Polygon(points); + polygon.closeStroke = this.closeStroke; + return polygon; + }; + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + Polygon.prototype.contains = function (x, y) { + var inside = false; + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[(i * 2) + 1]; + var xj = this.points[j * 2]; + var yj = this.points[(j * 2) + 1]; + var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi); + if (intersect) { + inside = !inside; + } + } + return inside; + }; + return Polygon; +}()); /** - * Calculate the points for a quadratic bezier curve. (helper function..) - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * - * Ignored from docs since it is not directly exposed. + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. * - * @ignore - * @private - * @param {number} fromX - Origin point x - * @param {number} fromY - Origin point x - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. - * @return {number[]} an array of points + * @class + * @memberof PIXI */ -function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) -{ - if ( out === void 0 ) out = []; - - var n = 20; - var points = out; - - var xa = 0; - var ya = 0; - var xb = 0; - var yb = 0; - var x = 0; - var y = 0; - - for (var i = 0, j = 0; i <= n; ++i) - { - j = i / n; - - // The Green Line - xa = getPt(fromX, cpX, j); - ya = getPt(fromY, cpY, j); - xb = getPt(cpX, toX, j); - yb = getPt(cpY, toY, j); - - // The Black Dot - x = getPt(xa, xb, j); - y = getPt(ya, yb, j); - - points.push(x, y); - } - - return points; -} - -/** - * Builds a line to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output - */ -function buildLine(graphicsData, graphicsGeometry) -{ - if (graphicsData.lineStyle.native) - { - buildNativeLine(graphicsData, graphicsGeometry); - } - else - { - buildNonNativeLine(graphicsData, graphicsGeometry); - } -} - -/** - * Builds a line to draw using the polygon method. - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output - */ -function buildNonNativeLine(graphicsData, graphicsGeometry) -{ - var shape = graphicsData.shape; - var points = graphicsData.points || shape.points.slice(); - var eps = graphicsGeometry.closePointEps; - - if (points.length === 0) - { - return; - } - // if the line width is an odd number add 0.5 to align to a whole pixel - // commenting this out fixes #711 and #1620 - // if (graphicsData.lineWidth%2) - // { - // for (i = 0; i < points.length; i++) - // { - // points[i] += 0.5; - // } - // } - - var style = graphicsData.lineStyle; - - // get first and last point.. figure out the middle! - var firstPoint = new math.Point(points[0], points[1]); - var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); - var closedShape = shape.type !== math.SHAPES.POLY || shape.closeStroke; - var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps - && Math.abs(firstPoint.y - lastPoint.y) < eps; - - // if the first point is the last point - gonna have issues :) - if (closedShape) - { - // need to clone as we are going to slightly modify the shape.. - points = points.slice(); - - if (closedPath) - { - points.pop(); - points.pop(); - lastPoint.set(points[points.length - 2], points[points.length - 1]); - } - - var midPointX = lastPoint.x + ((firstPoint.x - lastPoint.x) * 0.5); - var midPointY = lastPoint.y + ((firstPoint.y - lastPoint.y) * 0.5); - - points.unshift(midPointX, midPointY); - points.push(midPointX, midPointY); +var RoundedRectangle = /** @class */ (function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle(x, y, width, height, radius) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + if (radius === void 0) { radius = 20; } + /** + * @member {number} + * @default 0 + */ + this.x = x; + /** + * @member {number} + * @default 0 + */ + this.y = y; + /** + * @member {number} + * @default 0 + */ + this.width = width; + /** + * @member {number} + * @default 0 + */ + this.height = height; + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = exports.SHAPES.RREC; } - - var verts = graphicsGeometry.points; - var length = points.length / 2; - var indexCount = points.length; - var indexStart = verts.length / 2; - - // DRAW the Line - var width = style.width / 2; - - // sort color - var p1x = points[0]; - var p1y = points[1]; - var p2x = points[2]; - var p2y = points[3]; - var p3x = 0; - var p3y = 0; - - var perpx = -(p1y - p2y); - var perpy = p1x - p2x; - var perp2x = 0; - var perp2y = 0; - var perp3x = 0; - var perp3y = 0; - - var dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); - - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - - var ratio = style.alignment;// 0.5; - var r1 = (1 - ratio) * 2; - var r2 = ratio * 2; - - // start - verts.push( - p1x - (perpx * r1), - p1y - (perpy * r1)); - - verts.push( - p1x + (perpx * r2), - p1y + (perpy * r2)); - - for (var i = 1; i < length - 1; ++i) - { - p1x = points[(i - 1) * 2]; - p1y = points[((i - 1) * 2) + 1]; - - p2x = points[i * 2]; - p2y = points[(i * 2) + 1]; - - p3x = points[(i + 1) * 2]; - p3y = points[((i + 1) * 2) + 1]; - - perpx = -(p1y - p2y); - perpy = p1x - p2x; - - dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - - perp2x = -(p2y - p3y); - perp2y = p2x - p3x; - - dist = Math.sqrt((perp2x * perp2x) + (perp2y * perp2y)); - perp2x /= dist; - perp2y /= dist; - perp2x *= width; - perp2y *= width; - - var a1 = (-perpy + p1y) - (-perpy + p2y); - var b1 = (-perpx + p2x) - (-perpx + p1x); - var c1 = ((-perpx + p1x) * (-perpy + p2y)) - ((-perpx + p2x) * (-perpy + p1y)); - var a2 = (-perp2y + p3y) - (-perp2y + p2y); - var b2 = (-perp2x + p2x) - (-perp2x + p3x); - var c2 = ((-perp2x + p3x) * (-perp2y + p2y)) - ((-perp2x + p2x) * (-perp2y + p3y)); - - var denom = (a1 * b2) - (a2 * b1); - - if (Math.abs(denom) < 0.1) - { - denom += 10.1; - verts.push( - p2x - (perpx * r1), - p2y - (perpy * r1)); - - verts.push( - p2x + (perpx * r2), - p2y + (perpy * r2)); - - continue; - } - - var px = ((b1 * c2) - (b2 * c1)) / denom; - var py = ((a2 * c1) - (a1 * c2)) / denom; - var pdist = ((px - p2x) * (px - p2x)) + ((py - p2y) * (py - p2y)); - - if (pdist > (196 * width * width)) - { - perp3x = perpx - perp2x; - perp3y = perpy - perp2y; - - dist = Math.sqrt((perp3x * perp3x) + (perp3y * perp3y)); - perp3x /= dist; - perp3y /= dist; - perp3x *= width; - perp3y *= width; - - verts.push(p2x - (perp3x * r1), p2y - (perp3y * r1)); - - verts.push(p2x + (perp3x * r2), p2y + (perp3y * r2)); - - verts.push(p2x - (perp3x * r2 * r1), p2y - (perp3y * r1)); - - indexCount++; + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + RoundedRectangle.prototype.clone = function () { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + RoundedRectangle.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; } - else - { - verts.push(p2x + ((px - p2x) * r1), p2y + ((py - p2y) * r1)); - - verts.push(p2x - ((px - p2x) * r2), p2y - ((py - p2y) * r2)); + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if ((y >= this.y + this.radius && y <= this.y + this.height - this.radius) + || (x >= this.x + this.radius && x <= this.x + this.width - this.radius)) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + } } - } - - p1x = points[(length - 2) * 2]; - p1y = points[((length - 2) * 2) + 1]; - - p2x = points[(length - 1) * 2]; - p2y = points[((length - 1) * 2) + 1]; - - perpx = -(p1y - p2y); - perpy = p1x - p2x; - - dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - - verts.push(p2x - (perpx * r1), p2y - (perpy * r1)); - - verts.push(p2x + (perpx * r2), p2y + (perpy * r2)); - - var indices = graphicsGeometry.indices; - - // indices.push(indexStart); - - for (var i$1 = 0; i$1 < indexCount - 2; ++i$1) - { - indices.push(indexStart, indexStart + 1, indexStart + 2); - - indexStart++; - } -} + return false; + }; + return RoundedRectangle; +}()); /** - * Builds a line to draw using the gl.drawArrays(gl.LINES) method - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + * Common interface for points. Both Point and ObservablePoint implement it + * @memberof PIXI + * @interface IPointData */ -function buildNativeLine(graphicsData, graphicsGeometry) -{ - var i = 0; - - var shape = graphicsData.shape; - var points = graphicsData.points || shape.points; - var closedShape = shape.type !== math.SHAPES.POLY || shape.closeStroke; - - if (points.length === 0) { return; } - - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - var length = points.length / 2; - - var startIndex = verts.length / 2; - var currentIndex = startIndex; - - verts.push(points[0], points[1]); - - for (i = 1; i < length; i++) - { - verts.push(points[i * 2], points[(i * 2) + 1]); - indices.push(currentIndex, currentIndex + 1); - - currentIndex++; - } - - if (closedShape) - { - indices.push(currentIndex, startIndex); - } -} - /** - * Builds a complex polygon to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.Graphics} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * X coord + * @memberof PIXI.IPointData# + * @member {number} x */ -function buildComplexPoly(graphicsData, webGLData) -{ - // TODO - no need to copy this as it gets turned into a Float32Array anyways.. - var points = graphicsData.points.slice(); - - if (points.length < 6) - { - return; - } - - // get first and last point.. figure out the middle! - var indices = webGLData.indices; - - webGLData.points = points; - webGLData.alpha = graphicsData.fillAlpha; - webGLData.color = utils.hex2rgb(graphicsData.fillColor); - - // calculate the bounds.. - var minX = Infinity; - var maxX = -Infinity; - - var minY = Infinity; - var maxY = -Infinity; - - var x = 0; - var y = 0; - - // get size.. - for (var i = 0; i < points.length; i += 2) - { - x = points[i]; - y = points[i + 1]; - - minX = x < minX ? x : minX; - maxX = x > maxX ? x : maxX; - - minY = y < minY ? y : minY; - maxY = y > maxY ? y : maxY; - } - - // add a quad to the end cos there is no point making another buffer! - points.push(minX, minY, - maxX, minY, - maxX, maxY, - minX, maxY); - - // push a quad onto the end.. - - // TODO - this ain't needed! - var length = points.length / 2; - - for (var i$1 = 0; i$1 < length; i$1++) - { - indices.push(i$1); - } -} - /** - * Calculate the points for a bezier curve and then draws it. - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @param {number} fromX - Starting point x - * @param {number} fromY - Starting point y - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} cpX2 - Second Control point x - * @param {number} cpY2 - Second Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number} n - Number of segments approximating the bezier curve - * @param {number[]} [path=[]] - Path array to push points into - * @return {number[]} Array of points of the curve + * Y coord + * @memberof PIXI.IPointData# + * @member {number} y */ -function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n, path) -{ - if ( path === void 0 ) path = []; - - var dt = 0; - var dt2 = 0; - var dt3 = 0; - var t2 = 0; - var t3 = 0; - - path.push(fromX, fromY); - - for (var i = 1, j = 0; i <= n; ++i) - { - j = i / n; - - dt = (1 - j); - dt2 = dt * dt; - dt3 = dt2 * dt; - - t2 = j * j; - t3 = t2 * j; - - path.push( - (dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), - (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY) - ); - } - - return path; -} /** - * Draw a star shape with an arbitrary number of points. - * - * @class - * @extends PIXI.Polygon + * Common interface for points. Both Point and ObservablePoint implement it * @memberof PIXI - * @param {number} x - Center X position of the star - * @param {number} y - Center Y position of the star - * @param {number} points - The number of points of the star, must be > 1 - * @param {number} radius - The outer radius of the star - * @param {number} [innerRadius] - The inner radius between points, default half `radius` - * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ -var Star = /*@__PURE__*/(function (Polygon) { - function Star(x, y, points, radius, innerRadius, rotation) - { - innerRadius = innerRadius || radius / 2; - - var startAngle = (-1 * Math.PI / 2) + rotation; - var len = points * 2; - var delta = math.PI_2 / len; - var polygon = []; - - for (var i = 0; i < len; i++) - { - var r = i % 2 ? innerRadius : radius; - var angle = (i * delta) + startAngle; - - polygon.push( - x + (r * Math.cos(angle)), - y + (r * Math.sin(angle)) - ); - } - - Polygon.call(this, polygon); - } - - if ( Polygon ) Star.__proto__ = Polygon; - Star.prototype = Object.create( Polygon && Polygon.prototype ); - Star.prototype.constructor = Star; - - return Star; -}(math.Polygon)); - -/** - * Utilities for arc curves - * @class - * @private + * @interface IPoint + * @extends PIXI.IPointData */ -var ArcUtils = function ArcUtils () {}; - -ArcUtils.curveTo = function curveTo (x1, y1, x2, y2, radius, points) -{ - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - - var a1 = fromY - y1; - var b1 = fromX - x1; - var a2 = y2 - y1; - var b2 = x2 - x1; - var mm = Math.abs((a1 * b2) - (b1 * a2)); - - if (mm < 1.0e-8 || radius === 0) - { - if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) - { - points.push(x1, y1); - } - - return null; - } - - var dd = (a1 * a1) + (b1 * b1); - var cc = (a2 * a2) + (b2 * b2); - var tt = (a1 * a2) + (b1 * b2); - var k1 = radius * Math.sqrt(dd) / mm; - var k2 = radius * Math.sqrt(cc) / mm; - var j1 = k1 * tt / dd; - var j2 = k2 * tt / cc; - var cx = (k1 * b2) + (k2 * b1); - var cy = (k1 * a2) + (k2 * a1); - var px = b1 * (k2 + j1); - var py = a1 * (k2 + j1); - var qx = b2 * (k1 + j2); - var qy = a2 * (k1 + j2); - var startAngle = Math.atan2(py - cy, px - cx); - var endAngle = Math.atan2(qy - cy, qx - cx); - - return { - cx: (cx + x1), - cy: (cy + y1), - radius: radius, - startAngle: startAngle, - endAngle: endAngle, - anticlockwise: (b1 * a2 > b2 * a1), - }; -}; - /** - * The arc method creates an arc/curve (used to create circles, or parts of circles). + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. * - * @private - * @param {number} startX - Start x location of arc - * @param {number} startY - Start y location of arc - * @param {number} cx - The x-coordinate of the center of the circle - * @param {number} cy - The y-coordinate of the center of the circle - * @param {number} radius - The radius of the circle - * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position - * of the arc's circle) - * @param {number} endAngle - The ending angle, in radians - * @param {boolean} anticlockwise - Specifies whether the drawing should be - * counter-clockwise or clockwise. False is default, and indicates clockwise, while true - * indicates counter-clockwise. - * @param {number} n - Number of segments - * @param {number[]} points - Collection of points to add to - */ -ArcUtils.arc = function arc (startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points) -{ - var sweep = endAngle - startAngle; - var n = GRAPHICS_CURVES._segmentsCount( - Math.abs(sweep) * radius, - Math.ceil(Math.abs(sweep) / math.PI_2) * 40 - ); - - var theta = (sweep) / (n * 2); - var theta2 = theta * 2; - var cTheta = Math.cos(theta); - var sTheta = Math.sin(theta); - var segMinus = n - 1; - var remainder = (segMinus % 1) / segMinus; - - for (var i = 0; i <= segMinus; ++i) - { - var real = i + (remainder * i); - var angle = ((theta) + startAngle + (theta2 * real)); - var c = Math.cos(angle); - var s = -Math.sin(angle); - - points.push( - (((cTheta * c) + (sTheta * s)) * radius) + cx, - (((cTheta * -s) + (sTheta * c)) * radius) + cy - ); - } -}; - -/** - * Utilities for bezier curves - * @class - * @private + * @method set + * @memberof PIXI.IPoint# + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=x] - position of the point on the y axis */ -var BezierUtils = function BezierUtils () {}; - -BezierUtils.curveLength = function curveLength (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) -{ - var n = 10; - var result = 0.0; - var t = 0.0; - var t2 = 0.0; - var t3 = 0.0; - var nt = 0.0; - var nt2 = 0.0; - var nt3 = 0.0; - var x = 0.0; - var y = 0.0; - var dx = 0.0; - var dy = 0.0; - var prevX = fromX; - var prevY = fromY; - - for (var i = 1; i <= n; ++i) - { - t = i / n; - t2 = t * t; - t3 = t2 * t; - nt = (1.0 - t); - nt2 = nt * nt; - nt3 = nt2 * nt; - - x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX); - y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY); - dx = prevX - x; - dy = prevY - y; - prevX = x; - prevY = y; - - result += Math.sqrt((dx * dx) + (dy * dy)); - } - - return result; -}; - /** - * Calculate the points for a bezier curve and then draws it. - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} cpX2 - Second Control point x - * @param {number} cpY2 - Second Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number[]} points - Path array to push points into + * Copies x and y from the given point + * @method copyFrom + * @memberof PIXI.IPoint# + * @param {PIXI.IPointData} p - The point to copy from + * @returns {this} Returns itself. */ -BezierUtils.curveTo = function curveTo (cpX, cpY, cpX2, cpY2, toX, toY, points) -{ - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - - points.length -= 2; - - var n = GRAPHICS_CURVES._segmentsCount( - BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) - ); - - var dt = 0; - var dt2 = 0; - var dt3 = 0; - var t2 = 0; - var t3 = 0; - - points.push(fromX, fromY); - - for (var i = 1, j = 0; i <= n; ++i) - { - j = i / n; - - dt = (1 - j); - dt2 = dt * dt; - dt3 = dt2 * dt; - - t2 = j * j; - t3 = t2 * j; - - points.push( - (dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), - (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY) - ); - } -}; - /** - * Utilities for quadratic curves - * @class - * @private + * Copies x and y into the given point + * @method copyTo + * @memberof PIXI.IPoint# + * @param {PIXI.IPoint} p - The point to copy. + * @returns {PIXI.IPoint} Given point with values updated */ -var QuadraticUtils = function QuadraticUtils () {}; - -QuadraticUtils.curveLength = function curveLength (fromX, fromY, cpX, cpY, toX, toY) -{ - var ax = fromX - (2.0 * cpX) + toX; - var ay = fromY - (2.0 * cpY) + toY; - var bx = (2.0 * cpX) - (2.0 * fromX); - var by = (2.0 * cpY) - (2.0 * fromY); - var a = 4.0 * ((ax * ax) + (ay * ay)); - var b = 4.0 * ((ax * bx) + (ay * by)); - var c = (bx * bx) + (by * by); - - var s = 2.0 * Math.sqrt(a + b + c); - var a2 = Math.sqrt(a); - var a32 = 2.0 * a * a2; - var c2 = 2.0 * Math.sqrt(c); - var ba = b / a2; - - return ( - (a32 * s) - + (a2 * b * (s - c2)) - + ( - ((4.0 * c * a) - (b * b)) - * Math.log(((2.0 * a2) + ba + s) / (ba + c2)) - ) - ) / (4.0 * a32); -}; - /** - * Calculate the points for a quadratic bezier curve and then draws it. - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * Returns true if the given point is equal to this point * - * @private - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number[]} points - Points to add segments to. + * @method equals + * @memberof PIXI.IPoint# + * @param {PIXI.IPointData} p - The point to check + * @returns {boolean} Whether the given point equal to this point */ -QuadraticUtils.curveTo = function curveTo (cpX, cpY, toX, toY, points) -{ - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - - var n = GRAPHICS_CURVES._segmentsCount( - QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY) - ); - - var xa = 0; - var ya = 0; - - for (var i = 1; i <= n; ++i) - { - var j = i / n; - - xa = fromX + ((cpX - fromX) * j); - ya = fromY + ((cpY - fromY) * j); - - points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), - ya + (((cpY + ((toY - cpY) * j)) - ya) * j)); - } -}; /** - * A structure to hold interim batch objects. + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. * + * @class + * @memberof PIXI + * @implements IPoint */ -var BatchPart = function BatchPart() -{ - this.reset(); -}; - -/** - * Begin batch part - * - * @param {PIXI.FillStyle | PIXI.LineStyle} style - * @param {number} startIndex - * @param {number} attribStart - */ -BatchPart.prototype.begin = function begin (style, startIndex, attribStart) -{ - this.reset(); - this.style = style; - this.start = startIndex; - this.attribStart = attribStart; -}; - -/** - * End batch part - * - * @param {number} endIndex - * @param {number} endAttrib - */ -BatchPart.prototype.end = function end (endIndex, endAttrib) -{ - this.attribSize = endAttrib - this.attribStart; - this.size = endIndex - this.start; -}; - -BatchPart.prototype.reset = function reset () -{ - this.style = null; - this.size = 0; - this.start = 0; - this.attribStart = 0; - this.attribSize = 0; -}; - -/** - * Generalized convenience utilities for Graphics. - * - * @namespace PIXI.graphicsUtils - */ - -/** - * Map of fill commands for each shape type. - * - * @member {Object} - */ -var FILL_COMMANDS = {}; -FILL_COMMANDS[math.SHAPES.POLY] = buildPoly; -FILL_COMMANDS[math.SHAPES.CIRC] = buildCircle; -FILL_COMMANDS[math.SHAPES.ELIP] = buildCircle; -FILL_COMMANDS[math.SHAPES.RECT] = buildRectangle; -FILL_COMMANDS[math.SHAPES.RREC] = buildRoundedRectangle; - -/** - * Batch pool, stores unused batches for preventing allocations. - * - * @type {Array} - */ -var BATCH_POOL = []; - -/** - * Draw call pool, stores unused draw calls for preventing allocations. - * - * @type {Array} - */ -var DRAW_CALL_POOL = []; - -var index = ({ - buildPoly: buildPoly, - buildCircle: buildCircle, - buildRectangle: buildRectangle, - buildRoundedRectangle: buildRoundedRectangle, - FILL_COMMANDS: FILL_COMMANDS, - BATCH_POOL: BATCH_POOL, - DRAW_CALL_POOL: DRAW_CALL_POOL, - buildLine: buildLine, - buildComplexPoly: buildComplexPoly, - bezierCurveTo: bezierCurveTo, - Star: Star, - ArcUtils: ArcUtils, - BezierUtils: BezierUtils, - QuadraticUtils: QuadraticUtils, - BatchPart: BatchPart -}); - -/** - * A class to contain data useful for Graphics objects - * - * @class - * @memberof PIXI - */ -var GraphicsData = function GraphicsData(shape, fillStyle, lineStyle, matrix) -{ - if ( fillStyle === void 0 ) fillStyle = null; - if ( lineStyle === void 0 ) lineStyle = null; - if ( matrix === void 0 ) matrix = null; - - /** - * The shape object to draw. - * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} - */ - this.shape = shape; - +var Point = /** @class */ (function () { /** - * The style of the line. - * @member {PIXI.LineStyle} + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis */ - this.lineStyle = lineStyle; - + function Point(x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + /** + * @member {number} + * @default 0 + */ + this.x = x; + /** + * @member {number} + * @default 0 + */ + this.y = y; + } /** - * The style of the fill. - * @member {PIXI.FillStyle} + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point */ - this.fillStyle = fillStyle; - + Point.prototype.clone = function () { + return new Point(this.x, this.y); + }; /** - * The transform matrix. - * @member {PIXI.Matrix} + * Copies x and y from the given point + * + * @param {PIXI.IPointData} p - The point to copy from + * @returns {this} Returns itself. */ - this.matrix = matrix; - + Point.prototype.copyFrom = function (p) { + this.set(p.x, p.y); + return this; + }; /** - * The type of the shape, see the Const.Shapes file for all the existing types, - * @member {number} + * Copies x and y into the given point + * + * @param {PIXI.IPoint} p - The point to copy. + * @returns {PIXI.IPoint} Given point with values updated */ - this.type = shape.type; - + Point.prototype.copyTo = function (p) { + p.set(this.x, this.y); + return p; + }; /** - * The collection of points. - * @member {number[]} + * Returns true if the given point is equal to this point + * + * @param {PIXI.IPointData} p - The point to check + * @returns {boolean} Whether the given point equal to this point */ - this.points = []; - + Point.prototype.equals = function (p) { + return (p.x === this.x) && (p.y === this.y); + }; /** - * The collection of holes. - * @member {PIXI.GraphicsData[]} + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=x] - position of the point on the y axis + * @returns {this} Returns itself. */ - this.holes = []; -}; - -/** - * Creates a new GraphicsData object with the same values as this one. - * - * @return {PIXI.GraphicsData} Cloned GraphicsData object - */ -GraphicsData.prototype.clone = function clone () -{ - return new GraphicsData( - this.shape, - this.fillStyle, - this.lineStyle, - this.matrix - ); -}; - -/** - * Destroys the Graphics data. - */ -GraphicsData.prototype.destroy = function destroy () -{ - this.shape = null; - this.holes.length = 0; - this.holes = null; - this.points.length = 0; - this.points = null; - this.lineStyle = null; - this.fillStyle = null; -}; - -var tmpPoint = new math.Point(); -var tmpBounds = new display.Bounds(); + Point.prototype.set = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = x; } + this.x = x; + this.y = y; + return this; + }; + return Point; +}()); /** - * The Graphics class contains methods used to draw primitive shapes such as lines, circles and - * rectangles to the display, and to color and fill them. + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. * - * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive - * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster. + * An ObservablePoint is a point that triggers a callback when the point's position is changed. * * @class - * @extends PIXI.BatchGeometry * @memberof PIXI + * @implements IPoint */ -var GraphicsGeometry = /*@__PURE__*/(function (BatchGeometry) { - function GraphicsGeometry() - { - BatchGeometry.call(this); - - /** - * An array of points to draw, 2 numbers per point - * - * @member {number[]} - * @protected - */ - this.points = []; - - /** - * The collection of colors - * - * @member {number[]} - * @protected - */ - this.colors = []; - - /** - * The UVs collection - * - * @member {number[]} - * @protected - */ - this.uvs = []; - - /** - * The indices of the vertices - * - * @member {number[]} - * @protected - */ - this.indices = []; - - /** - * Reference to the texture IDs. - * - * @member {number[]} - * @protected - */ - this.textureIds = []; - - /** - * The collection of drawn shapes. - * - * @member {PIXI.GraphicsData[]} - * @protected - */ - this.graphicsData = []; - +var ObservablePoint = /** @class */ (function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope, x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + this._x = x; + this._y = y; + this.cb = cb; + this.scope = scope; + } + /** + * Creates a clone of this point. + * The callback and scope params can be overidden otherwise they will default + * to the clone object's values. + * + * @override + * @param {Function} [cb=null] - callback when changed + * @param {object} [scope=null] - owner of callback + * @return {PIXI.ObservablePoint} a copy of the point + */ + ObservablePoint.prototype.clone = function (cb, scope) { + if (cb === void 0) { cb = this.cb; } + if (scope === void 0) { scope = this.scope; } + return new ObservablePoint(cb, scope, this._x, this._y); + }; + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=x] - position of the point on the y axis + * @returns {this} Returns itself. + */ + ObservablePoint.prototype.set = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = x; } + if (this._x !== x || this._y !== y) { + this._x = x; + this._y = y; + this.cb.call(this.scope); + } + return this; + }; + /** + * Copies x and y from the given point + * + * @param {PIXI.IPointData} p - The point to copy from. + * @returns {this} Returns itself. + */ + ObservablePoint.prototype.copyFrom = function (p) { + if (this._x !== p.x || this._y !== p.y) { + this._x = p.x; + this._y = p.y; + this.cb.call(this.scope); + } + return this; + }; + /** + * Copies x and y into the given point + * + * @param {PIXI.IPoint} p - The point to copy. + * @returns {PIXI.IPoint} Given point with values updated + */ + ObservablePoint.prototype.copyTo = function (p) { + p.set(this._x, this._y); + return p; + }; + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.IPointData} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + ObservablePoint.prototype.equals = function (p) { + return (p.x === this._x) && (p.y === this._y); + }; + Object.defineProperty(ObservablePoint.prototype, "x", { /** - * Used to detect if the graphics object has changed. + * The position of the displayObject on the x axis relative to the local coordinates of the parent. * * @member {number} - * @protected */ - this.dirty = 0; - + get: function () { + return this._x; + }, + set: function (value) { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObservablePoint.prototype, "y", { /** - * Batches need to regenerated if the geometry is updated. + * The position of the displayObject on the x axis relative to the local coordinates of the parent. * * @member {number} - * @protected */ - this.batchDirty = -1; + get: function () { + return this._y; + }, + set: function (value) { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + }, + enumerable: false, + configurable: true + }); + return ObservablePoint; +}()); +/** + * The PixiJS Matrix as a class makes it a lot faster. + * + * Here is a representation of it: + * ```js + * | a | c | tx| + * | b | d | ty| + * | 0 | 0 | 1 | + * ``` + * @class + * @memberof PIXI + */ +var Matrix = /** @class */ (function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - x skew + * @param {number} [c=0] - y skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix(a, b, c, d, tx, ty) { + if (a === void 0) { a = 1; } + if (b === void 0) { b = 0; } + if (c === void 0) { c = 0; } + if (d === void 0) { d = 1; } + if (tx === void 0) { tx = 0; } + if (ty === void 0) { ty = 0; } + this.array = null; /** - * Used to check if the cache is dirty. - * * @member {number} - * @protected + * @default 1 */ - this.cacheDirty = -1; - + this.a = a; /** - * Used to detect if we cleared the graphicsData. - * * @member {number} * @default 0 - * @protected - */ - this.clearDirty = 0; - - /** - * List of current draw calls drived from the batches. - * - * @member {object[]} - * @protected - */ - this.drawCalls = []; - - /** - * Intermediate abstract format sent to batch system. - * Can be converted to drawCalls or to batchable objects. - * - * @member {BatchPart[]} - * @protected */ - this.batches = []; - + this.b = b; /** - * Index of the last batched shape in the stack of calls. - * * @member {number} - * @protected - */ - this.shapeIndex = 0; - - /** - * Cached bounds. - * - * @member {PIXI.Bounds} - * @protected + * @default 0 */ - this._bounds = new display.Bounds(); - + this.c = c; /** - * The bounds dirty flag. - * * @member {number} - * @protected + * @default 1 */ - this.boundsDirty = -1; - + this.d = d; /** - * Padding to add to the bounds. - * * @member {number} * @default 0 */ - this.boundsPadding = 0; - - this.batchable = false; - - this.indicesUint16 = null; - - this.uvsFloat32 = null; - + this.tx = tx; /** - * Minimal distance between points that are considered different. - * Affects line tesselation. - * * @member {number} + * @default 0 */ - this.closePointEps = 1e-4; + this.ty = ty; } - - if ( BatchGeometry ) GraphicsGeometry.__proto__ = BatchGeometry; - GraphicsGeometry.prototype = Object.create( BatchGeometry && BatchGeometry.prototype ); - GraphicsGeometry.prototype.constructor = GraphicsGeometry; - - var prototypeAccessors = { bounds: { configurable: true } }; - /** - * Get the current bounds of the graphic geometry. + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: * - * @member {PIXI.Bounds} - * @readonly - */ - prototypeAccessors.bounds.get = function () - { - if (this.boundsDirty !== this.dirty) - { - this.boundsDirty = this.dirty; - this.calculateBounds(); - } - - return this._bounds; - }; - - /** - * Call if you changed graphicsData manually. - * Empties all batch buffers. - */ - GraphicsGeometry.prototype.invalidate = function invalidate () - { - this.boundsDirty = -1; - this.dirty++; - this.batchDirty++; - this.shapeIndex = 0; - - this.points.length = 0; - this.colors.length = 0; - this.uvs.length = 0; - this.indices.length = 0; - this.textureIds.length = 0; - - for (var i = 0; i < this.drawCalls.length; i++) - { - this.drawCalls[i].textures.length = 0; - DRAW_CALL_POOL.push(this.drawCalls[i]); - } - - this.drawCalls.length = 0; - - for (var i$1 = 0; i$1 < this.batches.length; i$1++) - { - var batch = this.batches[i$1]; - - batch.start = 0; - batch.attribStart = 0; - batch.style = null; - BATCH_POOL.push(batch); - } - - this.batches.length = 0; - }; - - /** - * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] * - * @return {PIXI.GraphicsGeometry} This GraphicsGeometry object. Good for chaining method calls + * @param {number[]} array - The array that the matrix will be populated from. */ - GraphicsGeometry.prototype.clear = function clear () - { - if (this.graphicsData.length > 0) - { - this.invalidate(); - this.clearDirty++; - this.graphicsData.length = 0; - } - - return this; + Matrix.prototype.fromArray = function (array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; }; - /** - * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * sets the matrix properties * - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. - * @param {PIXI.FillStyle} fillStyle - Defines style of the fill. - * @param {PIXI.LineStyle} lineStyle - Defines style of the lines. - * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape. - * @return {PIXI.GraphicsGeometry} Returns geometry for chaining. + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype.drawShape = function drawShape (shape, fillStyle, lineStyle, matrix) - { - var data = new GraphicsData(shape, fillStyle, lineStyle, matrix); - - this.graphicsData.push(data); - this.dirty++; - + Matrix.prototype.set = function (a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; return this; }; - /** - * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * Creates an array from the current Matrix object. * - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. - * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape. - * @return {PIXI.GraphicsGeometry} Returns geometry for chaining. + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix */ - GraphicsGeometry.prototype.drawHole = function drawHole (shape, matrix) - { - if (!this.graphicsData.length) - { - return null; + Matrix.prototype.toArray = function (transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); } - - var data = new GraphicsData(shape, null, null, matrix); - - var lastShape = this.graphicsData[this.graphicsData.length - 1]; - - data.lineStyle = lastShape.lineStyle; - - lastShape.holes.push(data); - - this.dirty++; - - return this; + var array = out || this.array; + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + return array; }; - /** - * Destroys the Graphics object. + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all - * options have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have - * their destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite + * @param {PIXI.IPointData} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix */ - GraphicsGeometry.prototype.destroy = function destroy (options) - { - BatchGeometry.prototype.destroy.call(this, options); - - // destroy each of the GraphicsData objects - for (var i = 0; i < this.graphicsData.length; ++i) - { - this.graphicsData[i].destroy(); - } - - this.points.length = 0; - this.points = null; - this.colors.length = 0; - this.colors = null; - this.uvs.length = 0; - this.uvs = null; - this.indices.length = 0; - this.indices = null; - this.indexBuffer.destroy(); - this.indexBuffer = null; - this.graphicsData.length = 0; - this.graphicsData = null; - this.drawCalls.length = 0; - this.drawCalls = null; - this.batches.length = 0; - this.batches = null; - this._bounds = null; + Matrix.prototype.apply = function (pos, newPos) { + newPos = (newPos || new Point()); + var x = pos.x; + var y = pos.y; + newPos.x = (this.a * x) + (this.c * y) + this.tx; + newPos.y = (this.b * x) + (this.d * y) + this.ty; + return newPos; }; - /** - * Check to see if a point is contained within this geometry. + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) * - * @param {PIXI.Point} point - Point to check if it's contained. - * @return {Boolean} `true` if the point is contained within geometry. + * @param {PIXI.IPointData} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix */ - GraphicsGeometry.prototype.containsPoint = function containsPoint (point) - { - var graphicsData = this.graphicsData; - - for (var i = 0; i < graphicsData.length; ++i) - { - var data = graphicsData[i]; - - if (!data.fillStyle.visible) - { - continue; - } - - // only deal with fills.. - if (data.shape) - { - if (data.matrix) - { - data.matrix.applyInverse(point, tmpPoint); - } - else - { - tmpPoint.copyFrom(point); - } - - if (data.shape.contains(tmpPoint.x, tmpPoint.y)) - { - var hitHole = false; - - if (data.holes) - { - for (var i$1 = 0; i$1 < data.holes.length; i$1++) - { - var hole = data.holes[i$1]; - - if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) - { - hitHole = true; - break; - } - } - } - - if (!hitHole) - { - return true; - } - } - } - } - - return false; + Matrix.prototype.applyInverse = function (pos, newPos) { + newPos = (newPos || new Point()); + var id = 1 / ((this.a * this.d) + (this.c * -this.b)); + var x = pos.x; + var y = pos.y; + newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id); + newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id); + return newPos; }; - /** - * Generates intermediate batch data. Either gets converted to drawCalls - * or used to convert to batch objects directly by the Graphics object. + * Translates the matrix on the x and y. + * + * @param {number} x - How much to translate x by + * @param {number} y - How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype.updateBatches = function updateBatches () - { - if (!this.graphicsData.length) - { - this.batchable = true; - - return; - } - - if (!this.validateBatching()) - { - return; - } - - this.cacheDirty = this.dirty; - - var uvs = this.uvs; - var graphicsData = this.graphicsData; - - var batchPart = null; - - var currentStyle = null; - - if (this.batches.length > 0) - { - batchPart = this.batches[this.batches.length - 1]; - currentStyle = batchPart.style; - } - - for (var i = this.shapeIndex; i < graphicsData.length; i++) - { - this.shapeIndex++; - - var data = graphicsData[i]; - var fillStyle = data.fillStyle; - var lineStyle = data.lineStyle; - var command = FILL_COMMANDS[data.type]; - - // build out the shapes points.. - command.build(data); - - if (data.matrix) - { - this.transformPoints(data.points, data.matrix); - } - - for (var j = 0; j < 2; j++) - { - var style = (j === 0) ? fillStyle : lineStyle; - - if (!style.visible) { continue; } - - var nextTexture = style.texture.baseTexture; - var index$1 = this.indices.length; - var attribIndex = this.points.length / 2; - - nextTexture.wrapMode = constants.WRAP_MODES.REPEAT; - - // close batch if style is different - if (batchPart && !this._compareStyles(currentStyle, style)) - { - batchPart.end(index$1, attribIndex); - - if (batchPart.size > 0) - { - batchPart = null; - } - } - // spawn new batch if its first batch or previous was closed - if (!batchPart) - { - batchPart = BATCH_POOL.pop() || new BatchPart(); - batchPart.begin(style, index$1, attribIndex); - this.batches.push(batchPart); - - currentStyle = style; - } - - var start = this.points.length / 2; - - if (j === 0) - { - this.processFill(data); - } - else - { - this.processLine(data); - } - - var size = (this.points.length / 2) - start; - - this.addUvs(this.points, uvs, style.texture, start, size, style.matrix); - } - } - - if (!batchPart) - { - // there are no visible styles in GraphicsData - // its possible that someone wants Graphics just for the bounds - this.batchable = true; - - return; - } - - var index = this.indices.length; - var attrib = this.points.length / 2; - - batchPart.end(index, attrib); - - this.indicesUint16 = new Uint16Array(this.indices); - - // TODO make this a const.. - this.batchable = this.isBatchable(); - - if (this.batchable) - { - this.packBatches(); - } - else - { - this.buildDrawCalls(); - } + Matrix.prototype.translate = function (x, y) { + this.tx += x; + this.ty += y; + return this; }; - /** - * Affinity check + * Applies a scale transformation to the matrix. * - * @param {PIXI.FillStyle | PIXI.LineStyle} styleA - * @param {PIXI.FillStyle | PIXI.LineStyle} styleB + * @param {number} x - The amount to scale horizontally + * @param {number} y - The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype._compareStyles = function _compareStyles (styleA, styleB) - { - if (!styleA || !styleB) - { - return false; - } - - if (styleA.texture.baseTexture !== styleB.texture.baseTexture) - { - return false; - } - - if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) - { - return false; - } - - if (!!styleA.native !== !!styleB.native) - { - return false; - } - - return true; + Matrix.prototype.scale = function (x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + return this; }; - /** - * Test geometry for batching process. + * Applies a rotation transformation to the matrix. * - * @protected + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype.validateBatching = function validateBatching () - { - if (this.dirty === this.cacheDirty || !this.graphicsData.length) - { - return false; - } - - for (var i = 0, l = this.graphicsData.length; i < l; i++) - { - var data = this.graphicsData[i]; - var fill = data.fillStyle; - var line = data.lineStyle; - - if (fill && !fill.texture.baseTexture.valid) { return false; } - if (line && !line.texture.baseTexture.valid) { return false; } - } - - return true; + Matrix.prototype.rotate = function (angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + this.a = (a1 * cos) - (this.b * sin); + this.b = (a1 * sin) + (this.b * cos); + this.c = (c1 * cos) - (this.d * sin); + this.d = (c1 * sin) + (this.d * cos); + this.tx = (tx1 * cos) - (this.ty * sin); + this.ty = (tx1 * sin) + (this.ty * cos); + return this; }; - /** - * Offset the indices so that it works with the batcher. + * Appends the given Matrix to this Matrix. * - * @protected + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype.packBatches = function packBatches () - { - this.batchDirty++; - this.uvsFloat32 = new Float32Array(this.uvs); - - var batches = this.batches; - - for (var i = 0, l = batches.length; i < l; i++) - { - var batch = batches[i]; - - for (var j = 0; j < batch.size; j++) - { - var index = batch.start + j; - - this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart; - } - } + Matrix.prototype.append = function (matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + this.a = (matrix.a * a1) + (matrix.b * c1); + this.b = (matrix.a * b1) + (matrix.b * d1); + this.c = (matrix.c * a1) + (matrix.d * c1); + this.d = (matrix.c * b1) + (matrix.d * d1); + this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx; + this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty; + return this; }; - /** - * Checks to see if this graphics geometry can be batched. - * Currently it needs to be small enough and not contain any native lines. + * Sets the matrix based on all the available properties * - * @protected + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype.isBatchable = function isBatchable () - { - var batches = this.batches; - - for (var i = 0; i < batches.length; i++) - { - if (batches[i].style.native) - { - return false; - } - } - - return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2); + Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + this.a = Math.cos(rotation + skewY) * scaleX; + this.b = Math.sin(rotation + skewY) * scaleX; + this.c = -Math.sin(rotation - skewX) * scaleY; + this.d = Math.cos(rotation - skewX) * scaleY; + this.tx = x - ((pivotX * this.a) + (pivotY * this.c)); + this.ty = y - ((pivotX * this.b) + (pivotY * this.d)); + return this; }; - /** - * Converts intermediate batches data to drawCalls. + * Prepends the given Matrix to this Matrix. * - * @protected + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype.buildDrawCalls = function buildDrawCalls () - { - var TICK = ++core.BaseTexture._globalBatch; - - for (var i = 0; i < this.drawCalls.length; i++) - { - this.drawCalls[i].textures.length = 0; - DRAW_CALL_POOL.push(this.drawCalls[i]); + Matrix.prototype.prepend = function (matrix) { + var tx1 = this.tx; + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + this.a = (a1 * matrix.a) + (this.b * matrix.c); + this.b = (a1 * matrix.b) + (this.b * matrix.d); + this.c = (c1 * matrix.a) + (this.d * matrix.c); + this.d = (c1 * matrix.b) + (this.d * matrix.d); } - - this.drawCalls.length = 0; - - var colors = this.colors; - var textureIds = this.textureIds; - - var currentGroup = DRAW_CALL_POOL.pop(); - - if (!currentGroup) - { - currentGroup = new core.BatchDrawCall(); - currentGroup.textures = new core.BatchTextureArray(); + this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx; + this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty; + return this; + }; + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform} transform - The transform to apply the properties to. + * @return {PIXI.Transform} The transform with the newly applied properties + */ + Matrix.prototype.decompose = function (transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + var delta = Math.abs(skewX + skewY); + if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) { + transform.rotation = skewY; + transform.skew.x = transform.skew.y = 0; } - currentGroup.textures.count = 0; - currentGroup.start = 0; - currentGroup.size = 0; - currentGroup.type = constants.DRAW_MODES.TRIANGLES; - - var textureCount = 0; - var currentTexture = null; - var textureId = 0; - var native = false; - var drawMode = constants.DRAW_MODES.TRIANGLES; - - var index = 0; - - this.drawCalls.push(currentGroup); - - // TODO - this can be simplified - for (var i$1 = 0; i$1 < this.batches.length; i$1++) - { - var data = this.batches[i$1]; - - // TODO add some full on MAX_TEXTURE CODE.. - var MAX_TEXTURES = 8; - - var style = data.style; - - var nextTexture = style.texture.baseTexture; - - if (native !== !!style.native) - { - native = !!style.native; - drawMode = native ? constants.DRAW_MODES.LINES : constants.DRAW_MODES.TRIANGLES; - - // force the batch to break! - currentTexture = null; - textureCount = MAX_TEXTURES; - TICK++; - } - - if (currentTexture !== nextTexture) - { - currentTexture = nextTexture; - - if (nextTexture._batchEnabled !== TICK) - { - if (textureCount === MAX_TEXTURES) - { - TICK++; - - textureCount = 0; - - if (currentGroup.size > 0) - { - currentGroup = DRAW_CALL_POOL.pop(); - if (!currentGroup) - { - currentGroup = new core.BatchDrawCall(); - currentGroup.textures = new core.BatchTextureArray(); - } - this.drawCalls.push(currentGroup); - } - - currentGroup.start = index; - currentGroup.size = 0; - currentGroup.textures.count = 0; - currentGroup.type = drawMode; - } - - // TODO add this to the render part.. - nextTexture.touched = 1;// touch; - nextTexture._batchEnabled = TICK; - nextTexture._batchLocation = textureCount; - nextTexture.wrapMode = 10497; - - currentGroup.textures.elements[currentGroup.textures.count++] = nextTexture; - textureCount++; - } - } - - currentGroup.size += data.size; - index += data.size; - - textureId = nextTexture._batchLocation; - - this.addColors(colors, style.color, style.alpha, data.attribSize); - this.addTextureIds(textureIds, textureId, data.attribSize); + else { + transform.rotation = 0; + transform.skew.x = skewX; + transform.skew.y = skewY; } - - core.BaseTexture._globalBatch = TICK; - - // upload.. - // merge for now! - this.packAttributes(); + // next set scale + transform.scale.x = Math.sqrt((a * a) + (b * b)); + transform.scale.y = Math.sqrt((c * c) + (d * d)); + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + return transform; }; - /** - * Packs attributes to single buffer. + * Inverts this matrix * - * @protected + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype.packAttributes = function packAttributes () - { - var verts = this.points; - var uvs = this.uvs; - var colors = this.colors; - var textureIds = this.textureIds; - - // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes - var glPoints = new ArrayBuffer(verts.length * 3 * 4); - var f32 = new Float32Array(glPoints); - var u32 = new Uint32Array(glPoints); - - var p = 0; - - for (var i = 0; i < verts.length / 2; i++) - { - f32[p++] = verts[i * 2]; - f32[p++] = verts[(i * 2) + 1]; - - f32[p++] = uvs[i * 2]; - f32[p++] = uvs[(i * 2) + 1]; - - u32[p++] = colors[i]; - - f32[p++] = textureIds[i]; - } - - this._buffer.update(glPoints); - this._indexBuffer.update(this.indicesUint16); + Matrix.prototype.invert = function () { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = (a1 * d1) - (b1 * c1); + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = ((c1 * this.ty) - (d1 * tx1)) / n; + this.ty = -((a1 * this.ty) - (b1 * tx1)) / n; + return this; }; - /** - * Process fill part of Graphics. + * Resets this Matrix to an identity (default) matrix. * - * @param {PIXI.GraphicsData} data - * @protected + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype.processFill = function processFill (data) - { - if (data.holes.length) - { - this.processHoles(data.holes); - - buildPoly.triangulate(data, this); - } - else - { - var command = FILL_COMMANDS[data.type]; - - command.triangulate(data, this); - } + Matrix.prototype.identity = function () { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + return this; }; - /** - * Process line part of Graphics. + * Creates a new Matrix object with the same values as this one. * - * @param {PIXI.GraphicsData} data - * @protected + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. */ - GraphicsGeometry.prototype.processLine = function processLine (data) - { - buildLine(data, this); - - for (var i = 0; i < data.holes.length; i++) - { - buildLine(data.holes[i], this); - } + Matrix.prototype.clone = function () { + var matrix = new Matrix(); + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; }; - /** - * Process the holes data. + * Changes the values of the given matrix to be the same as the ones in this matrix * - * @param {PIXI.GraphicsData[]} holes - Holes to render - * @protected + * @param {PIXI.Matrix} matrix - The matrix to copy to. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. */ - GraphicsGeometry.prototype.processHoles = function processHoles (holes) - { - for (var i = 0; i < holes.length; i++) - { - var hole = holes[i]; - var command = FILL_COMMANDS[hole.type]; - - command.build(hole); - - if (hole.matrix) - { - this.transformPoints(hole.points, hole.matrix); - } - } + Matrix.prototype.copyTo = function (matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; }; - /** - * Update the local bounds of the object. Expensive to use performance-wise. + * Changes the values of the matrix to be the same as the ones in given matrix * - * @protected + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} this */ - GraphicsGeometry.prototype.calculateBounds = function calculateBounds () - { - var bounds = this._bounds; - var sequenceBounds = tmpBounds; - var curMatrix = math.Matrix.IDENTITY; - - this._bounds.clear(); - sequenceBounds.clear(); - - for (var i = 0; i < this.graphicsData.length; i++) - { - var data = this.graphicsData[i]; - var shape = data.shape; - var type = data.type; - var lineStyle = data.lineStyle; - var nextMatrix = data.matrix || math.Matrix.IDENTITY; - var lineWidth = 0.0; - - if (lineStyle && lineStyle.visible) - { - var alignment = lineStyle.alignment; - - lineWidth = lineStyle.width; - - if (type === math.SHAPES.POLY) - { - lineWidth = lineWidth * (0.5 + Math.abs(0.5 - alignment)); - } - else - { - lineWidth = lineWidth * Math.max(0, alignment); - } - } + Matrix.prototype.copyFrom = function (matrix) { + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + return this; + }; + Object.defineProperty(Matrix, "IDENTITY", { + /** + * A default (identity) matrix + * + * @static + * @const + * @member {PIXI.Matrix} + */ + get: function () { + return new Matrix(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Matrix, "TEMP_MATRIX", { + /** + * A temp matrix + * + * @static + * @const + * @member {PIXI.Matrix} + */ + get: function () { + return new Matrix(); + }, + enumerable: false, + configurable: true + }); + return Matrix; +}()); - if (curMatrix !== nextMatrix) - { - if (!sequenceBounds.isEmpty()) - { - bounds.addBoundsMatrix(sequenceBounds, curMatrix); - sequenceBounds.clear(); +// Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group +/* + * Transform matrix for operation n is: + * | ux | vx | + * | uy | vy | + */ +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +/** + * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table} + * for the composition of each rotation in the dihederal group D8. + * + * @type number[][] + * @private + */ +var rotationCayley = []; +/** + * Matrices for each `GD8Symmetry` rotation. + * + * @type Matrix[] + * @private + */ +var rotationMatrices = []; +/* + * Alias for {@code Math.sign}. + */ +var signum = Math.sign; +/* + * Initializes `rotationCayley` and `rotationMatrices`. It is called + * only once below. + */ +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + rotationCayley.push(row); + for (var j = 0; j < 16; j++) { + /* Multiplies rotation matrices i and j. */ + var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j])); + var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j])); + var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j])); + var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j])); + /* Finds rotation matrix matching the product and pushes it. */ + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy + && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; } - curMatrix = nextMatrix; } - - if (type === math.SHAPES.RECT || type === math.SHAPES.RREC) - { - sequenceBounds.addFramePad(shape.x, shape.y, shape.x + shape.width, shape.y + shape.height, - lineWidth, lineWidth); - } - else if (type === math.SHAPES.CIRC) - { - sequenceBounds.addFramePad(shape.x, shape.y, shape.x, shape.y, - shape.radius + lineWidth, shape.radius + lineWidth); - } - else if (type === math.SHAPES.ELIP) - { - sequenceBounds.addFramePad(shape.x, shape.y, shape.x, shape.y, - shape.width + lineWidth, shape.height + lineWidth); - } - else - { - // adding directly to the bounds - bounds.addVerticesMatrix(curMatrix, shape.points, 0, shape.points.length, lineWidth, lineWidth); - } - } - - if (!sequenceBounds.isEmpty()) - { - bounds.addBoundsMatrix(sequenceBounds, curMatrix); } - - bounds.pad(this.boundsPadding, this.boundsPadding); - }; - + } + for (var i = 0; i < 16; i++) { + var mat = new Matrix(); + mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); + rotationMatrices.push(mat); + } +} +init(); +/** + * @memberof PIXI + * @typedef {number} GD8Symmetry + * @see PIXI.groupD8 + */ +/** + * Implements the dihedral group D8, which is similar to + * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}; + * D8 is the same but with diagonals, and it is used for texture + * rotations. + * + * The directions the U- and V- axes after rotation + * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))` + * and `(vX(a), vY(a))`. These aren't necessarily unit vectors. + * + * **Origin:**

+ * This is the small part of gameofbombs.com portal system. It works. + * + * @see PIXI.groupD8.E + * @see PIXI.groupD8.SE + * @see PIXI.groupD8.S + * @see PIXI.groupD8.SW + * @see PIXI.groupD8.W + * @see PIXI.groupD8.NW + * @see PIXI.groupD8.N + * @see PIXI.groupD8.NE + * @author Ivan @ivanpopelyshev + * @namespace PIXI.groupD8 + * @memberof PIXI + */ +var groupD8 = { /** - * Transform points using matrix. + * | Rotation | Direction | + * |----------|-----------| + * | 0° | East | * - * @protected - * @param {number[]} points - Points to transform - * @param {PIXI.Matrix} matrix - Transform matrix + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} */ - GraphicsGeometry.prototype.transformPoints = function transformPoints (points, matrix) - { - for (var i = 0; i < points.length / 2; i++) - { - var x = points[(i * 2)]; - var y = points[(i * 2) + 1]; - - points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx; - points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty; - } - }; - + E: 0, /** - * Add colors. + * | Rotation | Direction | + * |----------|-----------| + * | 45°↻ | Southeast | * - * @protected - * @param {number[]} colors - List of colors to add to - * @param {number} color - Color to add - * @param {number} alpha - Alpha to use - * @param {number} size - Number of colors to add + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} */ - GraphicsGeometry.prototype.addColors = function addColors (colors, color, alpha, size) - { - // TODO use the premultiply bits Ivan added - var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16); - - var rgba = utils.premultiplyTint(rgb, alpha); - - while (size-- > 0) - { - colors.push(rgba); - } - }; - + SE: 1, /** - * Add texture id that the shader/fragment wants to use. + * | Rotation | Direction | + * |----------|-----------| + * | 90°↻ | South | * - * @protected - * @param {number[]} textureIds - * @param {number} id - * @param {number} size + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} */ - GraphicsGeometry.prototype.addTextureIds = function addTextureIds (textureIds, id, size) - { - while (size-- > 0) - { - textureIds.push(id); - } - }; - + S: 2, /** - * Generates the UVs for a shape. + * | Rotation | Direction | + * |----------|-----------| + * | 135°↻ | Southwest | * - * @protected - * @param {number[]} verts - Vertices - * @param {number[]} uvs - UVs - * @param {PIXI.Texture} texture - Reference to Texture - * @param {number} start - Index buffer start index. - * @param {number} size - The size/length for index buffer. - * @param {PIXI.Matrix} [matrix] - Optional transform for all points. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} */ - GraphicsGeometry.prototype.addUvs = function addUvs (verts, uvs, texture, start, size, matrix) - { - var index = 0; - var uvsStart = uvs.length; - var frame = texture.frame; - - while (index < size) - { - var x = verts[(start + index) * 2]; - var y = verts[((start + index) * 2) + 1]; - - if (matrix) - { - var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx; - - y = (matrix.b * x) + (matrix.d * y) + matrix.ty; - x = nx; - } - - index++; - - uvs.push(x / frame.width, y / frame.height); - } - - var baseTexture = texture.baseTexture; - - if (frame.width < baseTexture.width - || frame.height < baseTexture.height) - { - this.adjustUvs(uvs, texture, uvsStart, size); - } - }; - + SW: 3, /** - * Modify uvs array according to position of texture region - * Does not work with rotated or trimmed textures + * | Rotation | Direction | + * |----------|-----------| + * | 180° | West | * - * @param {number[]} uvs array - * @param {PIXI.Texture} texture region - * @param {number} start starting index for uvs - * @param {number} size how many points to adjust + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} */ - GraphicsGeometry.prototype.adjustUvs = function adjustUvs (uvs, texture, start, size) - { - var baseTexture = texture.baseTexture; - var eps = 1e-6; - var finish = start + (size * 2); - var frame = texture.frame; - var scaleX = frame.width / baseTexture.width; - var scaleY = frame.height / baseTexture.height; - var offsetX = frame.x / frame.width; - var offsetY = frame.y / frame.height; - var minX = Math.floor(uvs[start] + eps); - var minY = Math.floor(uvs[start + 1] + eps); - - for (var i = start + 2; i < finish; i += 2) - { - minX = Math.min(minX, Math.floor(uvs[i] + eps)); - minY = Math.min(minY, Math.floor(uvs[i + 1] + eps)); - } - offsetX -= minX; - offsetY -= minY; - for (var i$1 = start; i$1 < finish; i$1 += 2) - { - uvs[i$1] = (uvs[i$1] + offsetX) * scaleX; - uvs[i$1 + 1] = (uvs[i$1 + 1] + offsetY) * scaleY; - } - }; - - Object.defineProperties( GraphicsGeometry.prototype, prototypeAccessors ); - - return GraphicsGeometry; -}(core.BatchGeometry)); - -/** - * The maximum number of points to consider an object "batchable", - * able to be batched by the renderer's batch system. - * - * @memberof PIXI.GraphicsGeometry - * @static - * @member {number} BATCHABLE_SIZE - * @default 100 - */ -GraphicsGeometry.BATCHABLE_SIZE = 100; - -/** - * Represents the line style for Graphics. - * @memberof PIXI - * @class - * @extends PIXI.FillStyle - */ -var LineStyle = /*@__PURE__*/(function (FillStyle) { - function LineStyle () { - FillStyle.apply(this, arguments); - } - - if ( FillStyle ) LineStyle.__proto__ = FillStyle; - LineStyle.prototype = Object.create( FillStyle && FillStyle.prototype ); - LineStyle.prototype.constructor = LineStyle; - - LineStyle.prototype.clone = function clone () - { - var obj = new LineStyle(); - - obj.color = this.color; - obj.alpha = this.alpha; - obj.texture = this.texture; - obj.matrix = this.matrix; - obj.visible = this.visible; - obj.width = this.width; - obj.alignment = this.alignment; - obj.native = this.native; - - return obj; - }; + W: 4, /** - * Reset the line style to default. + * | Rotation | Direction | + * |-------------|--------------| + * | -135°/225°↻ | Northwest | + * + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} */ - LineStyle.prototype.reset = function reset () - { - FillStyle.prototype.reset.call(this); - - // Override default line style color - this.color = 0x0; - - /** - * The width (thickness) of any lines drawn. - * - * @member {number} - * @default 0 - */ - this.width = 0; - - /** - * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). - * - * @member {number} - * @default 0 - */ - this.alignment = 0.5; - - /** - * If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * - * @member {boolean} - * @default false - */ - this.native = false; - }; - - return LineStyle; -}(FillStyle)); - -var temp = new Float32Array(3); - -// a default shaders map used by graphics.. -var DEFAULT_SHADERS = {}; - -/** - * The Graphics class contains methods used to draw primitive shapes such as lines, circles and - * rectangles to the display, and to color and fill them. - * - * Note that because Graphics can share a GraphicsGeometry with other instances, - * it is necessary to call `destroy()` to properly dereference the underlying - * GraphicsGeometry and avoid a memory leak. Alternatively, keep using the same - * Graphics instance and call `clear()` between redraws. + NW: 5, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -90°/270°↻ | North | + * + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + N: 6, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -45°/315°↻ | Northeast | + * + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + NE: 7, + /** + * Reflection about Y-axis. + * + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MIRROR_VERTICAL: 8, + /** + * Reflection about the main diagonal. + * + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MAIN_DIAGONAL: 10, + /** + * Reflection about X-axis. + * + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MIRROR_HORIZONTAL: 12, + /** + * Reflection about reverse diagonal. + * + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + REVERSE_DIAGONAL: 14, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @return {PIXI.GD8Symmetry} The X-component of the U-axis + * after rotating the axes. + */ + uX: function (ind) { return ux[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @return {PIXI.GD8Symmetry} The Y-component of the U-axis + * after rotating the axes. + */ + uY: function (ind) { return uy[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @return {PIXI.GD8Symmetry} The X-component of the V-axis + * after rotating the axes. + */ + vX: function (ind) { return vx[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @return {PIXI.GD8Symmetry} The Y-component of the V-axis + * after rotating the axes. + */ + vY: function (ind) { return vy[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite + * is needed. Only rotations have opposite symmetries while + * reflections don't. + * @return {PIXI.GD8Symmetry} The opposite symmetry of `rotation` + */ + inv: function (rotation) { + if (rotation & 8) // true only if between 8 & 15 (reflections) + { + return rotation & 15; // or rotation % 16 + } + return (-rotation) & 7; // or (8 - rotation) % 8 + }, + /** + * Composes the two D8 operations. + * + * Taking `^` as reflection: + * + * | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 | + * |-------|-----|-----|-----|-----|------|-------|-------|-------| + * | E=0 | E | S | W | N | E^ | S^ | W^ | N^ | + * | S=2 | S | W | N | E | S^ | W^ | N^ | E^ | + * | W=4 | W | N | E | S | W^ | N^ | E^ | S^ | + * | N=6 | N | E | S | W | N^ | E^ | S^ | W^ | + * | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S | + * | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W | + * | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N | + * | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E | + * + * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table} + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which + * is the row in the above cayley table. + * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which + * is the column in the above cayley table. + * @return {PIXI.GD8Symmetry} Composed operation + */ + add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); }, + /** + * Reverse of `add`. + * + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotationSecond - Second operation + * @param {PIXI.GD8Symmetry} rotationFirst - First operation + * @return {PIXI.GD8Symmetry} Result + */ + sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); }, + /** + * Adds 180 degrees to rotation, which is a commutative + * operation. + * + * @memberof PIXI.groupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} Rotated number + */ + rotate180: function (rotation) { return rotation ^ 4; }, + /** + * Checks if the rotation angle is vertical, i.e. south + * or north. It doesn't work for reflections. + * + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + */ + isVertical: function (rotation) { return (rotation & 3) === 2; }, + /** + * Approximates the vector `V(dx,dy)` into one of the + * eight directions provided by `groupD8`. + * + * @memberof PIXI.groupD8 + * @param {number} dx - X-component of the vector + * @param {number} dy - Y-component of the vector + * @return {PIXI.GD8Symmetry} Approximation of the vector into + * one of the eight symmetries. + */ + byDirection: function (dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return groupD8.S; + } + return groupD8.N; + } + else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return groupD8.E; + } + return groupD8.W; + } + else if (dy > 0) { + if (dx > 0) { + return groupD8.SE; + } + return groupD8.SW; + } + else if (dx > 0) { + return groupD8.NE; + } + return groupD8.NW; + }, + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.groupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function (matrix, rotation, tx, ty) { + if (tx === void 0) { tx = 0; } + if (ty === void 0) { ty = 0; } + // Packer used "rotation", we use "inv(rotation)" + var mat = rotationMatrices[groupD8.inv(rotation)]; + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + }, +}; + +/** + * Transform that takes care about its versions * * @class - * @extends PIXI.Container * @memberof PIXI */ -var Graphics = /*@__PURE__*/(function (Container) { - function Graphics(geometry) - { - if ( geometry === void 0 ) geometry = null; - - Container.call(this); +var Transform = /** @class */ (function () { + function Transform() { /** - * Includes vertex positions, face indices, normals, colors, UVs, and - * custom attributes within buffers, reducing the cost of passing all - * this data to the GPU. Can be shared between multiple Mesh or Graphics objects. - * @member {PIXI.GraphicsGeometry} - * @readonly + * The world transformation matrix. + * + * @member {PIXI.Matrix} */ - this.geometry = geometry || new GraphicsGeometry(); - - this.geometry.refCount++; - + this.worldTransform = new Matrix(); /** - * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. - * Can be shared between multiple Graphics objects. - * @member {PIXI.Shader} + * The local transformation matrix. + * + * @member {PIXI.Matrix} */ - this.shader = null; - + this.localTransform = new Matrix(); /** - * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g., - * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. - * @member {PIXI.State} + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} */ - this.state = core.State.for2d(); - + this.position = new ObservablePoint(this.onChange, this, 0, 0); /** - * Current fill style + * The scale factor of the object. * - * @member {PIXI.FillStyle} - * @protected + * @member {PIXI.ObservablePoint} */ - this._fillStyle = new FillStyle(); - + this.scale = new ObservablePoint(this.onChange, this, 1, 1); /** - * Current line style + * The pivot point of the displayObject that it rotates around. + * + * @member {PIXI.ObservablePoint} + */ + this.pivot = new ObservablePoint(this.onChange, this, 0, 0); + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + this.skew = new ObservablePoint(this.updateSkew, this, 0, 0); + /** + * The rotation amount. * - * @member {PIXI.LineStyle} * @protected + * @member {number} */ - this._lineStyle = new LineStyle(); - + this._rotation = 0; /** - * Current shape transform matrix. + * The X-coordinate value of the normalized local X axis, + * the first column of the local transformation matrix without a scale. * - * @member {PIXI.Matrix} * @protected + * @member {number} */ - this._matrix = null; - + this._cx = 1; /** - * Current hole mode is enabled. + * The Y-coordinate value of the normalized local X axis, + * the first column of the local transformation matrix without a scale. * - * @member {boolean} - * @default false * @protected + * @member {number} */ - this._holeMode = false; - + this._sx = 0; /** - * Current path + * The X-coordinate value of the normalized local Y axis, + * the second column of the local transformation matrix without a scale. * - * @member {PIXI.Polygon} * @protected + * @member {number} */ - this.currentPath = null; - + this._cy = 0; /** - * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. - * This is useful if your graphics element does not change often, as it will speed up the rendering - * of the object in exchange for taking up texture memory. It is also useful if you need the graphics - * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if - * you are constantly redrawing the graphics element. + * The Y-coordinate value of the normalized local Y axis, + * the second column of the local transformation matrix without a scale. * - * @name cacheAsBitmap - * @member {boolean} - * @memberof PIXI.Graphics# - * @default false + * @protected + * @member {number} */ - + this._sy = 1; /** - * A collections of batches! These can be drawn by the renderer batch system. + * The locally unique ID of the local transform. * * @protected - * @member {object[]} + * @member {number} */ - this.batches = []; - + this._localID = 0; /** - * Update dirty for limiting calculating tints for batches. + * The locally unique ID of the local transform + * used to calculate the current local transformation matrix. * * @protected * @member {number} - * @default -1 */ - this.batchTint = -1; - + this._currentLocalID = 0; /** - * Copy of the object vertex data. + * The locally unique ID of the world transform. * * @protected - * @member {Float32Array} + * @member {number} */ - this.vertexData = null; - - this._transformID = -1; - this.batchDirty = -1; - + this._worldID = 0; /** - * Renderer plugin for batching + * The locally unique ID of the parent's world transform + * used to calculate the current world transformation matrix. * - * @member {string} - * @default 'batch' + * @protected + * @member {number} */ - this.pluginName = 'batch'; - - // Set default - this.tint = 0xFFFFFF; - this.blendMode = constants.BLEND_MODES.NORMAL; + this._parentID = 0; } - - if ( Container ) Graphics.__proto__ = Container; - Graphics.prototype = Object.create( Container && Container.prototype ); - Graphics.prototype.constructor = Graphics; - - var prototypeAccessors = { blendMode: { configurable: true },tint: { configurable: true },fill: { configurable: true },line: { configurable: true } }; - /** - * Creates a new Graphics object with the same values as this one. - * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * Called when a value changes. * - * @return {PIXI.Graphics} A clone of the graphics object + * @protected */ - Graphics.prototype.clone = function clone () - { - this.finishPoly(); - - return new Graphics(this.geometry); + Transform.prototype.onChange = function () { + this._localID++; }; - /** - * The blend mode to be applied to the graphic shape. Apply a value of - * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * Called when the skew or the rotation changes. * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL; - * @see PIXI.BLEND_MODES + * @protected */ - prototypeAccessors.blendMode.set = function (value) - { - this.state.blendMode = value; - }; - - prototypeAccessors.blendMode.get = function () - { - return this.state.blendMode; + Transform.prototype.updateSkew = function () { + this._cx = Math.cos(this._rotation + this.skew.y); + this._sx = Math.sin(this._rotation + this.skew.y); + this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2 + this._localID++; }; - /** - * The tint applied to the graphic shape. This is a hex value. A value of - * 0xFFFFFF will remove any tint effect. - * - * @member {number} - * @default 0xFFFFFF + * Updates the local transformation matrix. */ - prototypeAccessors.tint.get = function () - { - return this._tint; - }; - prototypeAccessors.tint.set = function (value) - { - this._tint = value; + Transform.prototype.updateLocalTransform = function () { + var lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); + lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); + this._currentLocalID = this._localID; + // force an update.. + this._parentID = -1; + } }; - /** - * The current fill style. + * Updates the local and the world transformation matrices. * - * @member {PIXI.FillStyle} - * @readonly + * @param {PIXI.Transform} parentTransform - The parent transform */ - prototypeAccessors.fill.get = function () - { - return this._fillStyle; + Transform.prototype.updateTransform = function (parentTransform) { + var lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); + lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); + this._currentLocalID = this._localID; + // force an update.. + this._parentID = -1; + } + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + wt.a = (lt.a * pt.a) + (lt.b * pt.c); + wt.b = (lt.a * pt.b) + (lt.b * pt.d); + wt.c = (lt.c * pt.a) + (lt.d * pt.c); + wt.d = (lt.c * pt.b) + (lt.d * pt.d); + wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx; + wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty; + this._parentID = parentTransform._worldID; + // update the id of the transform.. + this._worldID++; + } }; - /** - * The current line style. + * Decomposes a matrix and sets the transforms properties based on it. * - * @member {PIXI.LineStyle} - * @readonly + * @param {PIXI.Matrix} matrix - The matrix to decompose */ - prototypeAccessors.line.get = function () - { - return this._lineStyle; + Transform.prototype.setFromMatrix = function (matrix) { + matrix.decompose(this); + this._localID++; }; - - /** - * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() - * method or the drawCircle() method. - * - * @method PIXI.Graphics#lineStyle - * @param {number} [width=0] - width of the line to draw, will update the objects stored style - * @param {number} [color=0x0] - color of the line to draw, will update the objects stored style - * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style - * @param {number} [alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) - * @param {boolean} [native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ + Object.defineProperty(Transform.prototype, "rotation", { + /** + * The rotation of the object in radians. + * + * @member {number} + */ + get: function () { + return this._rotation; + }, + set: function (value) { + if (this._rotation !== value) { + this._rotation = value; + this.updateSkew(); + } + }, + enumerable: false, + configurable: true + }); /** - * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() - * method or the drawCircle() method. + * A default (identity) transform * - * @param {object} [options] - Line style options - * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style - * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style - * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style - * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) - * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * @static + * @constant + * @member {PIXI.Transform} */ - Graphics.prototype.lineStyle = function lineStyle (options) - { - // Support non-object params: (width, color, alpha, alignment, native) - if (typeof options === 'number') - { - var args = arguments; + Transform.IDENTITY = new Transform(); + return Transform; +}()); - options = { - width: args[0] || 0, - color: args[1] || 0x0, - alpha: args[2] !== undefined ? args[2] : 1, - alignment: args[3] !== undefined ? args[3] : 0.5, - native: !!args[4], - }; - } +/** + * Math classes and utilities mixed into PIXI namespace. + * + * @lends PIXI + */ - return this.lineTextureStyle(options); - }; +exports.Circle = Circle; +exports.DEG_TO_RAD = DEG_TO_RAD; +exports.Ellipse = Ellipse; +exports.Matrix = Matrix; +exports.ObservablePoint = ObservablePoint; +exports.PI_2 = PI_2; +exports.Point = Point; +exports.Polygon = Polygon; +exports.RAD_TO_DEG = RAD_TO_DEG; +exports.Rectangle = Rectangle; +exports.RoundedRectangle = RoundedRectangle; +exports.Transform = Transform; +exports.groupD8 = groupD8; - /** - * Like line style but support texture for line fill. - * - * @param {object} [options] - Collection of options for setting line style. - * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style - * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use - * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style. - * Default 0xFFFFFF if texture present. - * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style - * @param {PIXI.Matrix} [options.matrix=null] Texture matrix to transform texture - * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) - * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.lineTextureStyle = function lineTextureStyle (options) - { - // backward compatibility with params: (width, texture, - // color, alpha, matrix, alignment, native) - if (typeof options === 'number') - { - utils.deprecation('v5.2.0', 'Please use object-based options for Graphics#lineTextureStyle'); - - var width = arguments[0]; - var texture = arguments[1]; - var color = arguments[2]; - var alpha = arguments[3]; - var matrix = arguments[4]; - var alignment = arguments[5]; - var native = arguments[6]; - - options = { width: width, texture: texture, color: color, alpha: alpha, matrix: matrix, alignment: alignment, native: native }; - // Remove undefined keys - Object.keys(options).forEach(function (key) { return options[key] === undefined && delete options[key]; }); - } +},{}],21:[function(require,module,exports){ +/*! + * @pixi/mesh-extras - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/mesh-extras is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - // Apply defaults - options = Object.assign({ - width: 0, - texture: core.Texture.WHITE, - color: (options && options.texture) ? 0xFFFFFF : 0x0, - alpha: 1, - matrix: null, - alignment: 0.5, - native: false, - }, options); +Object.defineProperty(exports, '__esModule', { value: true }); - if (this.currentPath) - { - this.startPoly(); - } +var mesh = require('@pixi/mesh'); +var constants = require('@pixi/constants'); +var core = require('@pixi/core'); - var visible = options.width > 0 && options.alpha > 0; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} - if (!visible) - { - this._lineStyle.reset(); +var PlaneGeometry = /** @class */ (function (_super) { + __extends(PlaneGeometry, _super); + function PlaneGeometry(width, height, segWidth, segHeight) { + if (width === void 0) { width = 100; } + if (height === void 0) { height = 100; } + if (segWidth === void 0) { segWidth = 10; } + if (segHeight === void 0) { segHeight = 10; } + var _this = _super.call(this) || this; + _this.segWidth = segWidth; + _this.segHeight = segHeight; + _this.width = width; + _this.height = height; + _this.build(); + return _this; + } + /** + * Refreshes plane coordinates + * @private + */ + PlaneGeometry.prototype.build = function () { + var total = this.segWidth * this.segHeight; + var verts = []; + var uvs = []; + var indices = []; + var segmentsX = this.segWidth - 1; + var segmentsY = this.segHeight - 1; + var sizeX = (this.width) / segmentsX; + var sizeY = (this.height) / segmentsY; + for (var i = 0; i < total; i++) { + var x = (i % this.segWidth); + var y = ((i / this.segWidth) | 0); + verts.push(x * sizeX, y * sizeY); + uvs.push(x / segmentsX, y / segmentsY); } - else - { - if (options.matrix) - { - options.matrix = options.matrix.clone(); - options.matrix.invert(); - } - - Object.assign(this._lineStyle, { visible: visible }, options); + var totalSub = segmentsX * segmentsY; + for (var i = 0; i < totalSub; i++) { + var xpos = i % segmentsX; + var ypos = (i / segmentsX) | 0; + var value = (ypos * this.segWidth) + xpos; + var value2 = (ypos * this.segWidth) + xpos + 1; + var value3 = ((ypos + 1) * this.segWidth) + xpos; + var value4 = ((ypos + 1) * this.segWidth) + xpos + 1; + indices.push(value, value2, value3, value2, value4, value3); } - - return this; + this.buffers[0].data = new Float32Array(verts); + this.buffers[1].data = new Float32Array(uvs); + this.indexBuffer.data = new Uint16Array(indices); + // ensure that the changes are uploaded + this.buffers[0].update(); + this.buffers[1].update(); + this.indexBuffer.update(); }; + return PlaneGeometry; +}(mesh.MeshGeometry)); +/** + * RopeGeometry allows you to draw a geometry across several points and then manipulate these points. + * + * ```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * const rope = new PIXI.RopeGeometry(100, points); + * ``` + * + * @class + * @extends PIXI.MeshGeometry + * @memberof PIXI + * + */ +var RopeGeometry = /** @class */ (function (_super) { + __extends(RopeGeometry, _super); /** - * Start a polygon object internally - * @protected + * @param {number} [width=200] - The width (i.e., thickness) of the rope. + * @param {PIXI.Point[]} [points] - An array of {@link PIXI.Point} objects to construct this rope. + * @param {number} [textureScale=0] - By default the rope texture will be stretched to match + * rope length. If textureScale is positive this value will be treated as a scaling + * factor and the texture will preserve its aspect ratio instead. To create a tiling rope + * set baseTexture.wrapMode to {@link PIXI.WRAP_MODES.REPEAT} and use a power of two texture, + * then set textureScale=1 to keep the original texture pixel size. + * In order to reduce alpha channel artifacts provide a larger texture and downsample - + * i.e. set textureScale=0.5 to scale it down twice. */ - Graphics.prototype.startPoly = function startPoly () - { - if (this.currentPath) - { - var points = this.currentPath.points; - var len = this.currentPath.points.length; - - if (len > 2) - { - this.drawShape(this.currentPath); - this.currentPath = new math.Polygon(); - this.currentPath.closeStroke = false; - this.currentPath.points.push(points[len - 2], points[len - 1]); + function RopeGeometry(width, points, textureScale) { + if (width === void 0) { width = 200; } + if (textureScale === void 0) { textureScale = 0; } + var _this = _super.call(this, new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)) || this; + /** + * An array of points that determine the rope + * @member {PIXI.Point[]} + */ + _this.points = points; + /** + * The width (i.e., thickness) of the rope. + * @member {number} + * @readOnly + */ + _this._width = width; + /** + * Rope texture scale, if zero then the rope texture is stretched. + * @member {number} + * @readOnly + */ + _this.textureScale = textureScale; + _this.build(); + return _this; + } + Object.defineProperty(RopeGeometry.prototype, "width", { + /** + * The width (i.e., thickness) of the rope. + * @member {number} + * @readOnly + */ + get: function () { + return this._width; + }, + enumerable: false, + configurable: true + }); + /** + * Refreshes Rope indices and uvs + * @private + */ + RopeGeometry.prototype.build = function () { + var points = this.points; + if (!points) + { return; } + var vertexBuffer = this.getBuffer('aVertexPosition'); + var uvBuffer = this.getBuffer('aTextureCoord'); + var indexBuffer = this.getIndex(); + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1) { + return; + } + // if the number of points has changed we will need to recreate the arraybuffers + if (vertexBuffer.data.length / 4 !== points.length) { + vertexBuffer.data = new Float32Array(points.length * 4); + uvBuffer.data = new Float32Array(points.length * 4); + indexBuffer.data = new Uint16Array((points.length - 1) * 6); + } + var uvs = uvBuffer.data; + var indices = indexBuffer.data; + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + var amount = 0; + var prev = points[0]; + var textureWidth = this._width * this.textureScale; + var total = points.length; // - 1; + for (var i = 0; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + if (this.textureScale > 0) { + // calculate pixel distance from previous point + var dx = prev.x - points[i].x; + var dy = prev.y - points[i].y; + var distance = Math.sqrt((dx * dx) + (dy * dy)); + prev = points[i]; + amount += distance / textureWidth; } + else { + // stretch texture + amount = i / (total - 1); + } + uvs[index] = amount; + uvs[index + 1] = 0; + uvs[index + 2] = amount; + uvs[index + 3] = 1; } - else - { - this.currentPath = new math.Polygon(); - this.currentPath.closeStroke = false; + var indexCount = 0; + for (var i = 0; i < total - 1; i++) { + var index = i * 2; + indices[indexCount++] = index; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 3; } + // ensure that the changes are uploaded + uvBuffer.update(); + indexBuffer.update(); + this.updateVertices(); }; - /** - * Finish the polygon object. - * @protected + * refreshes vertices of Rope mesh */ - Graphics.prototype.finishPoly = function finishPoly () - { - if (this.currentPath) - { - if (this.currentPath.points.length > 2) - { - this.drawShape(this.currentPath); - this.currentPath = null; + RopeGeometry.prototype.updateVertices = function () { + var points = this.points; + if (points.length < 1) { + return; + } + var lastPoint = points[0]; + var nextPoint; + var perpX = 0; + var perpY = 0; + var vertices = this.buffers[0].data; + var total = points.length; + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + if (i < points.length - 1) { + nextPoint = points[i + 1]; } - else - { - this.currentPath.points.length = 0; + else { + nextPoint = point; } + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY)); + var num = this.textureScale > 0 ? this.textureScale * this._width / 2 : this._width / 2; + perpX /= perpLength; + perpY /= perpLength; + perpX *= num; + perpY *= num; + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + lastPoint = point; } + this.buffers[0].update(); }; - - /** - * Moves the current drawing position to x, y. - * - * @param {number} x - the X coordinate to move to - * @param {number} y - the Y coordinate to move to - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.moveTo = function moveTo (x, y) - { - this.startPoly(); - this.currentPath.points[0] = x; - this.currentPath.points[1] = y; - - return this; + RopeGeometry.prototype.update = function () { + if (this.textureScale > 0) { + this.build(); // we need to update UVs + } + else { + this.updateVertices(); + } }; + return RopeGeometry; +}(mesh.MeshGeometry)); +/** + * The rope allows you to draw a texture across several points and then manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.Mesh + * @memberof PIXI + * + */ +var SimpleRope = /** @class */ (function (_super) { + __extends(SimpleRope, _super); /** - * Draws a line using the current line style from the current drawing position to (x, y); - * The current drawing position is then set to (x, y). - * - * @param {number} x - the X coordinate to draw to - * @param {number} y - the Y coordinate to draw to - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + * @param {number} [textureScale=0] - Optional. Positive values scale rope texture + * keeping its aspect ratio. You can reduce alpha channel artifacts by providing a larger texture + * and downsampling here. If set to zero, texture will be streched instead. */ - Graphics.prototype.lineTo = function lineTo (x, y) - { - if (!this.currentPath) - { - this.moveTo(0, 0); + function SimpleRope(texture, points, textureScale) { + if (textureScale === void 0) { textureScale = 0; } + var _this = this; + var ropeGeometry = new RopeGeometry(texture.height, points, textureScale); + var meshMaterial = new mesh.MeshMaterial(texture); + if (textureScale > 0) { + // attempt to set UV wrapping, will fail on non-power of two textures + texture.baseTexture.wrapMode = constants.WRAP_MODES.REPEAT; } - - // remove duplicates.. - var points = this.currentPath.points; - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - - if (fromX !== x || fromY !== y) - { - points.push(x, y); + _this = _super.call(this, ropeGeometry, meshMaterial) || this; + /** + * re-calculate vertices by rope points each frame + * + * @member {boolean} + */ + _this.autoUpdate = true; + return _this; + } + SimpleRope.prototype._render = function (renderer) { + var geometry = this.geometry; + if (this.autoUpdate || geometry._width !== this.shader.texture.height) { + geometry._width = this.shader.texture.height; + geometry.update(); } - - return this; + _super.prototype._render.call(this, renderer); }; + return SimpleRope; +}(mesh.Mesh)); +/** + * The SimplePlane allows you to draw a texture across several points and then manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.Mesh + * @memberof PIXI + * + */ +var SimplePlane = /** @class */ (function (_super) { + __extends(SimplePlane, _super); /** - * Initialize the curve - * - * @protected - * @param {number} [x=0] - * @param {number} [y=0] + * @param {PIXI.Texture} texture - The texture to use on the SimplePlane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis */ - Graphics.prototype._initCurve = function _initCurve (x, y) - { - if ( x === void 0 ) x = 0; - if ( y === void 0 ) y = 0; - - if (this.currentPath) - { - if (this.currentPath.points.length === 0) - { - this.currentPath.points = [x, y]; + function SimplePlane(texture, verticesX, verticesY) { + var _this = this; + var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY); + var meshMaterial = new mesh.MeshMaterial(core.Texture.WHITE); + _this = _super.call(this, planeGeometry, meshMaterial) || this; + // lets call the setter to ensure all necessary updates are performed + _this.texture = texture; + return _this; + } + /** + * Method used for overrides, to do something in case texture frame was changed. + * Meshes based on plane can override it and change more details based on texture. + */ + SimplePlane.prototype.textureUpdated = function () { + this._textureID = this.shader.texture._updateID; + var geometry = this.geometry; + geometry.width = this.shader.texture.width; + geometry.height = this.shader.texture.height; + geometry.build(); + }; + Object.defineProperty(SimplePlane.prototype, "texture", { + get: function () { + return this.shader.texture; + }, + set: function (value) { + // Track texture same way sprite does. + // For generated meshes like NineSlicePlane it can change the geometry. + // Unfortunately, this method might not work if you directly change texture in material. + if (this.shader.texture === value) { + return; } + this.shader.texture = value; + this._textureID = -1; + if (value.baseTexture.valid) { + this.textureUpdated(); + } + else { + value.once('update', this.textureUpdated, this); + } + }, + enumerable: false, + configurable: true + }); + SimplePlane.prototype._render = function (renderer) { + if (this._textureID !== this.shader.texture._updateID) { + this.textureUpdated(); } - else - { - this.moveTo(x, y); - } + _super.prototype._render.call(this, renderer); }; + return SimplePlane; +}(mesh.Mesh)); +/** + * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments. + * For more robust customization, use {@link PIXI.Mesh}. + * + * @class + * @extends PIXI.Mesh + * @memberof PIXI + */ +var SimpleMesh = /** @class */ (function (_super) { + __extends(SimpleMesh, _super); /** - * Calculate the points for a quadratic bezier curve and then draws it. - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * @param {PIXI.Texture} [texture=Texture.EMPTY] - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts */ - Graphics.prototype.quadraticCurveTo = function quadraticCurveTo (cpX, cpY, toX, toY) - { - this._initCurve(); - - var points = this.currentPath.points; - - if (points.length === 0) - { - this.moveTo(0, 0); + function SimpleMesh(texture, vertices, uvs, indices, drawMode) { + if (texture === void 0) { texture = core.Texture.EMPTY; } + var _this = this; + var geometry = new mesh.MeshGeometry(vertices, uvs, indices); + geometry.getBuffer('aVertexPosition').static = false; + var meshMaterial = new mesh.MeshMaterial(texture); + _this = _super.call(this, geometry, meshMaterial, null, drawMode) || this; + /** + * upload vertices buffer each frame + * @member {boolean} + */ + _this.autoUpdate = true; + return _this; + } + Object.defineProperty(SimpleMesh.prototype, "vertices", { + /** + * Collection of vertices data. + * @member {Float32Array} + */ + get: function () { + return this.geometry.getBuffer('aVertexPosition').data; + }, + set: function (value) { + this.geometry.getBuffer('aVertexPosition').data = value; + }, + enumerable: false, + configurable: true + }); + SimpleMesh.prototype._render = function (renderer) { + if (this.autoUpdate) { + this.geometry.getBuffer('aVertexPosition').update(); } - - QuadraticUtils.curveTo(cpX, cpY, toX, toY, points); - - return this; + _super.prototype._render.call(this, renderer); }; + return SimpleMesh; +}(mesh.Mesh)); + +var DEFAULT_BORDER_SIZE = 10; +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
 
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.SimplePlane + * @memberof PIXI + * + */ +var NineSlicePlane = /** @class */ (function (_super) { + __extends(NineSlicePlane, _super); /** - * Calculate the points for a bezier curve and then draws it. - * - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} cpX2 - Second Control point x - * @param {number} cpY2 - Second Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {number} [leftWidth=10] - size of the left vertical bar (A) + * @param {number} [topHeight=10] - size of the top horizontal bar (C) + * @param {number} [rightWidth=10] - size of the right vertical bar (B) + * @param {number} [bottomHeight=10] - size of the bottom horizontal bar (D) */ - Graphics.prototype.bezierCurveTo = function bezierCurveTo (cpX, cpY, cpX2, cpY2, toX, toY) - { - this._initCurve(); - - BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points); - - return this; + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + if (leftWidth === void 0) { leftWidth = DEFAULT_BORDER_SIZE; } + if (topHeight === void 0) { topHeight = DEFAULT_BORDER_SIZE; } + if (rightWidth === void 0) { rightWidth = DEFAULT_BORDER_SIZE; } + if (bottomHeight === void 0) { bottomHeight = DEFAULT_BORDER_SIZE; } + var _this = _super.call(this, core.Texture.WHITE, 4, 4) || this; + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @override + */ + _this._width = _this._origWidth; + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @override + */ + _this._height = _this._origHeight; + /** + * The width of the left column (a) + * + * @member {number} + * @private + */ + _this._leftWidth = leftWidth; + /** + * The width of the right column (b) + * + * @member {number} + * @private + */ + _this._rightWidth = rightWidth; + /** + * The height of the top row (c) + * + * @member {number} + * @private + */ + _this._topHeight = topHeight; + /** + * The height of the bottom row (d) + * + * @member {number} + * @private + */ + _this._bottomHeight = bottomHeight; + // lets call the setter to ensure all necessary updates are performed + _this.texture = texture; + return _this; + } + NineSlicePlane.prototype.textureUpdated = function () { + this._textureID = this.shader.texture._updateID; + this._refresh(); }; - + Object.defineProperty(NineSlicePlane.prototype, "vertices", { + get: function () { + return this.geometry.getBuffer('aVertexPosition').data; + }, + set: function (value) { + this.geometry.getBuffer('aVertexPosition').data = value; + }, + enumerable: false, + configurable: true + }); /** - * The arcTo() method creates an arc/curve between two tangents on the canvas. - * - * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * Updates the horizontal vertices. * - * @param {number} x1 - The x-coordinate of the first tangent point of the arc - * @param {number} y1 - The y-coordinate of the first tangent point of the arc - * @param {number} x2 - The x-coordinate of the end of the arc - * @param {number} y2 - The y-coordinate of the end of the arc - * @param {number} radius - The radius of the arc - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Graphics.prototype.arcTo = function arcTo (x1, y1, x2, y2, radius) - { - this._initCurve(x1, y1); - - var points = this.currentPath.points; - - var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points); - - if (result) - { - var cx = result.cx; - var cy = result.cy; - var radius$1 = result.radius; - var startAngle = result.startAngle; - var endAngle = result.endAngle; - var anticlockwise = result.anticlockwise; - - this.arc(cx, cy, radius$1, startAngle, endAngle, anticlockwise); - } - - return this; + NineSlicePlane.prototype.updateHorizontalVertices = function () { + var vertices = this.vertices; + var scale = this._getMinScale(); + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale); + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; }; - /** - * The arc method creates an arc/curve (used to create circles, or parts of circles). + * Updates the vertical vertices. * - * @param {number} cx - The x-coordinate of the center of the circle - * @param {number} cy - The y-coordinate of the center of the circle - * @param {number} radius - The radius of the circle - * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position - * of the arc's circle) - * @param {number} endAngle - The ending angle, in radians - * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be - * counter-clockwise or clockwise. False is default, and indicates clockwise, while true - * indicates counter-clockwise. - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */ - Graphics.prototype.arc = function arc (cx, cy, radius, startAngle, endAngle, anticlockwise) - { - if ( anticlockwise === void 0 ) anticlockwise = false; - - if (startAngle === endAngle) - { - return this; - } - - if (!anticlockwise && endAngle <= startAngle) - { - endAngle += math.PI_2; - } - else if (anticlockwise && startAngle <= endAngle) - { - startAngle += math.PI_2; - } - - var sweep = endAngle - startAngle; - - if (sweep === 0) - { - return this; - } - - var startX = cx + (Math.cos(startAngle) * radius); - var startY = cy + (Math.sin(startAngle) * radius); - var eps = this.geometry.closePointEps; - - // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. - var points = this.currentPath ? this.currentPath.points : null; - - if (points) - { - // TODO: make a better fix. - - // We check how far our start is from the last existing point - var xDiff = Math.abs(points[points.length - 2] - startX); - var yDiff = Math.abs(points[points.length - 1] - startY); - - if (xDiff < eps && yDiff < eps) - ; - else - { - points.push(startX, startY); - } - } - else - { - this.moveTo(startX, startY); - points = this.currentPath.points; - } - - ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points); - - return this; + NineSlicePlane.prototype.updateVerticalVertices = function () { + var vertices = this.vertices; + var scale = this._getMinScale(); + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale); + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; }; - /** - * Specifies a simple one-color fill that subsequent calls to other Graphics methods - * (such as lineTo() or drawCircle()) use when drawing. + * Returns the smaller of a set of vertical and horizontal scale of nine slice corners. * - * @param {number} [color=0] - the color of the fill - * @param {number} [alpha=1] - the alpha of the fill - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * @return {number} Smaller number of vertical and horizontal scale. + * @private */ - Graphics.prototype.beginFill = function beginFill (color, alpha) - { - if ( color === void 0 ) color = 0; - if ( alpha === void 0 ) alpha = 1; - - return this.beginTextureFill({ texture: core.Texture.WHITE, color: color, alpha: alpha }); + NineSlicePlane.prototype._getMinScale = function () { + var w = this._leftWidth + this._rightWidth; + var scaleW = this._width > w ? 1.0 : this._width / w; + var h = this._topHeight + this._bottomHeight; + var scaleH = this._height > h ? 1.0 : this._height / h; + var scale = Math.min(scaleW, scaleH); + return scale; }; - + Object.defineProperty(NineSlicePlane.prototype, "width", { + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + get: function () { + return this._width; + }, + set: function (value) { + this._width = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "height", { + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + get: function () { + return this._height; + }, + set: function (value) { + this._height = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "leftWidth", { + /** + * The width of the left column + * + * @member {number} + */ + get: function () { + return this._leftWidth; + }, + set: function (value) { + this._leftWidth = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "rightWidth", { + /** + * The width of the right column + * + * @member {number} + */ + get: function () { + return this._rightWidth; + }, + set: function (value) { + this._rightWidth = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "topHeight", { + /** + * The height of the top row + * + * @member {number} + */ + get: function () { + return this._topHeight; + }, + set: function (value) { + this._topHeight = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "bottomHeight", { + /** + * The height of the bottom row + * + * @member {number} + */ + get: function () { + return this._bottomHeight; + }, + set: function (value) { + this._bottomHeight = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); /** - * Begin the texture fill - * - * @param {object} [options] - Object object. - * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill - * @param {number} [options.color=0xffffff] - Background to fill behind texture - * @param {number} [options.alpha=1] - Alpha of fill - * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * Refreshes NineSlicePlane coords. All of them. */ - Graphics.prototype.beginTextureFill = function beginTextureFill (options) - { - // backward compatibility with params: (texture, color, alpha, matrix) - if (options instanceof core.Texture) - { - utils.deprecation('v5.2.0', 'Please use object-based options for Graphics#beginTextureFill'); - - var texture = arguments[0]; - var color = arguments[1]; - var alpha = arguments[2]; - var matrix = arguments[3]; - - options = { texture: texture, color: color, alpha: alpha, matrix: matrix }; - - // Remove undefined keys - Object.keys(options).forEach(function (key) { return options[key] === undefined && delete options[key]; }); - } - - // Apply defaults - options = Object.assign({ - texture: core.Texture.WHITE, - color: 0xFFFFFF, - alpha: 1, - matrix: null, - }, options); - - if (this.currentPath) - { - this.startPoly(); - } - - var visible = options.alpha > 0; - - if (!visible) - { - this._fillStyle.reset(); - } - else - { - if (options.matrix) - { - options.matrix = options.matrix.clone(); - options.matrix.invert(); - } + NineSlicePlane.prototype._refresh = function () { + var texture = this.texture; + var uvs = this.geometry.buffers[1].data; + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth); + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight); + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + this.geometry.buffers[0].update(); + this.geometry.buffers[1].update(); + }; + return NineSlicePlane; +}(SimplePlane)); - Object.assign(this._fillStyle, { visible: visible }, options); - } +exports.NineSlicePlane = NineSlicePlane; +exports.PlaneGeometry = PlaneGeometry; +exports.RopeGeometry = RopeGeometry; +exports.SimpleMesh = SimpleMesh; +exports.SimplePlane = SimplePlane; +exports.SimpleRope = SimpleRope; - return this; - }; - /** - * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. - * - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.endFill = function endFill () - { - this.finishPoly(); +},{"@pixi/constants":7,"@pixi/core":8,"@pixi/mesh":22}],22:[function(require,module,exports){ +/*! + * @pixi/mesh - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/mesh is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - this._fillStyle.reset(); +Object.defineProperty(exports, '__esModule', { value: true }); - return this; - }; +var core = require('@pixi/core'); +var math = require('@pixi/math'); +var constants = require('@pixi/constants'); +var display = require('@pixi/display'); +var settings = require('@pixi/settings'); +var utils = require('@pixi/utils'); - /** - * Draws a rectangle shape. - * - * @param {number} x - The X coord of the top-left of the rectangle - * @param {number} y - The Y coord of the top-left of the rectangle - * @param {number} width - The width of the rectangle - * @param {number} height - The height of the rectangle - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawRect = function drawRect (x, y, width, height) - { - return this.drawShape(new math.Rectangle(x, y, width, height)); - }; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +/** + * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space. + * + * @class + * @memberof PIXI + */ +var MeshBatchUvs = /** @class */ (function () { /** - * Draw a rectangle shape with rounded/beveled corners. - * - * @param {number} x - The X coord of the top-left of the rectangle - * @param {number} y - The Y coord of the top-left of the rectangle - * @param {number} width - The width of the rectangle - * @param {number} height - The height of the rectangle - * @param {number} radius - Radius of the rectangle corners - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * @param {PIXI.Buffer} uvBuffer - Buffer with normalized uv's + * @param {PIXI.TextureMatrix} uvMatrix - Material UV matrix */ - Graphics.prototype.drawRoundedRect = function drawRoundedRect (x, y, width, height, radius) - { - return this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); - }; - + function MeshBatchUvs(uvBuffer, uvMatrix) { + /** + * Buffer with normalized UV's + * @member {PIXI.Buffer} + */ + this.uvBuffer = uvBuffer; + /** + * Material UV matrix + * @member {PIXI.TextureMatrix} + */ + this.uvMatrix = uvMatrix; + /** + * UV Buffer data + * @member {Float32Array} + * @readonly + */ + this.data = null; + this._bufferUpdateId = -1; + this._textureUpdateId = -1; + this._updateID = 0; + } /** - * Draws a circle. + * updates * - * @param {number} x - The X coordinate of the center of the circle - * @param {number} y - The Y coordinate of the center of the circle - * @param {number} radius - The radius of the circle - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * @param {boolean} [forceUpdate] - force the update */ - Graphics.prototype.drawCircle = function drawCircle (x, y, radius) - { - return this.drawShape(new math.Circle(x, y, radius)); + MeshBatchUvs.prototype.update = function (forceUpdate) { + if (!forceUpdate + && this._bufferUpdateId === this.uvBuffer._updateID + && this._textureUpdateId === this.uvMatrix._updateID) { + return; + } + this._bufferUpdateId = this.uvBuffer._updateID; + this._textureUpdateId = this.uvMatrix._updateID; + var data = this.uvBuffer.data; + if (!this.data || this.data.length !== data.length) { + this.data = new Float32Array(data.length); + } + this.uvMatrix.multiplyUvs(data, this.data); + this._updateID++; }; + return MeshBatchUvs; +}()); +var tempPoint = new math.Point(); +var tempPolygon = new math.Polygon(); +/** + * Base mesh class. + * + * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of. + * This class assumes a certain level of WebGL knowledge. + * If you know a bit this should abstract enough away to make you life easier! + * + * Pretty much ALL WebGL can be broken down into the following: + * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc.. + * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry) + * - State - This is the state of WebGL required to render the mesh. + * + * Through a combination of the above elements you can render anything you want, 2D or 3D! + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ +var Mesh = /** @class */ (function (_super) { + __extends(Mesh, _super); /** - * Draws an ellipse. - * - * @param {number} x - The X coordinate of the center of the ellipse - * @param {number} y - The Y coordinate of the center of the ellipse - * @param {number} width - The half width of the ellipse - * @param {number} height - The half height of the ellipse - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * @param {PIXI.Geometry} geometry - the geometry the mesh will use + * @param {PIXI.MeshMaterial} shader - the shader the mesh will use + * @param {PIXI.State} [state] - the state that the WebGL context is required to be in to render the mesh + * if no state is provided, uses {@link PIXI.State.for2d} to create a 2D state for PixiJS. + * @param {number} [drawMode=PIXI.DRAW_MODES.TRIANGLES] - the drawMode, can be any of the PIXI.DRAW_MODES consts */ - Graphics.prototype.drawEllipse = function drawEllipse (x, y, width, height) - { - return this.drawShape(new math.Ellipse(x, y, width, height)); - }; - + function Mesh(geometry, shader, state, drawMode) { + if (drawMode === void 0) { drawMode = constants.DRAW_MODES.TRIANGLES; } + var _this = _super.call(this) || this; + /** + * Includes vertex positions, face indices, normals, colors, UVs, and + * custom attributes within buffers, reducing the cost of passing all + * this data to the GPU. Can be shared between multiple Mesh objects. + * @member {PIXI.Geometry} + * @readonly + */ + _this.geometry = geometry; + geometry.refCount++; + /** + * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. + * Can be shared between multiple Mesh objects. + * @member {PIXI.Shader|PIXI.MeshMaterial} + */ + _this.shader = shader; + /** + * Represents the WebGL state the Mesh required to render, excludes shader and geometry. E.g., + * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. + * @member {PIXI.State} + */ + _this.state = state || core.State.for2d(); + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.DRAW_MODES} constants. + * + * @member {number} + * @see PIXI.DRAW_MODES + */ + _this.drawMode = drawMode; + /** + * Typically the index of the IndexBuffer where to start drawing. + * @member {number} + * @default 0 + */ + _this.start = 0; + /** + * How much of the geometry to draw, by default `0` renders everything. + * @member {number} + * @default 0 + */ + _this.size = 0; + /** + * thease are used as easy access for batching + * @member {Float32Array} + * @private + */ + _this.uvs = null; + /** + * thease are used as easy access for batching + * @member {Uint16Array} + * @private + */ + _this.indices = null; + /** + * this is the caching layer used by the batcher + * @member {Float32Array} + * @private + */ + _this.vertexData = new Float32Array(1); + /** + * If geometry is changed used to decide to re-transform + * the vertexData. + * @member {number} + * @private + */ + _this.vertexDirty = 0; + _this._transformID = -1; + // Inherited from DisplayMode, set defaults + _this.tint = 0xFFFFFF; + _this.blendMode = constants.BLEND_MODES.NORMAL; + /** + * Internal roundPixels field + * + * @member {boolean} + * @private + */ + _this._roundPixels = settings.settings.ROUND_PIXELS; + /** + * Batched UV's are cached for atlas textures + * @member {PIXI.MeshBatchUvs} + * @private + */ + _this.batchUvs = null; + return _this; + } + Object.defineProperty(Mesh.prototype, "uvBuffer", { + /** + * To change mesh uv's, change its uvBuffer data and increment its _updateID. + * @member {PIXI.Buffer} + * @readonly + */ + get: function () { + return this.geometry.buffers[1]; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "verticesBuffer", { + /** + * To change mesh vertices, change its uvBuffer data and increment its _updateID. + * Incrementing _updateID is optional because most of Mesh objects do it anyway. + * @member {PIXI.Buffer} + * @readonly + */ + get: function () { + return this.geometry.buffers[0]; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "material", { + get: function () { + return this.shader; + }, + /** + * Alias for {@link PIXI.Mesh#shader}. + * @member {PIXI.MeshMaterial} + */ + set: function (value) { + this.shader = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "blendMode", { + get: function () { + return this.state.blendMode; + }, + /** + * The blend mode to be applied to the Mesh. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "roundPixels", { + get: function () { + return this._roundPixels; + }, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} + * + * @member {boolean} + * @default false + */ + set: function (value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "tint", { + /** + * The multiply tint applied to the Mesh. This is a hex value. A value of + * `0xFFFFFF` will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + get: function () { + return this.shader.tint; + }, + set: function (value) { + this.shader.tint = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "texture", { + /** + * The texture that the Mesh uses. + * + * @member {PIXI.Texture} + */ + get: function () { + return this.shader.texture; + }, + set: function (value) { + this.shader.texture = value; + }, + enumerable: false, + configurable: true + }); /** - * Draws a polygon using the given path. - * - * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon. - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * Standard renderer draw. + * @protected + * @param {PIXI.Renderer} renderer - Instance to renderer. */ - Graphics.prototype.drawPolygon = function drawPolygon (path) - { - var arguments$1 = arguments; - - // prevents an argument assignment deopt - // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments - var points = path; - - var closeStroke = true;// !!this._fillStyle; - - // check if data has points.. - if (points.points) - { - closeStroke = points.closeStroke; - points = points.points; + Mesh.prototype._render = function (renderer) { + // set properties for batching.. + // TODO could use a different way to grab verts? + var vertices = this.geometry.buffers[0].data; + // TODO benchmark check for attribute size.. + if (this.shader.batchable + && this.drawMode === constants.DRAW_MODES.TRIANGLES + && vertices.length < Mesh.BATCHABLE_SIZE * 2) { + this._renderToBatch(renderer); } - - if (!Array.isArray(points)) - { - // prevents an argument leak deopt - // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments - points = new Array(arguments.length); - - for (var i = 0; i < points.length; ++i) - { - points[i] = arguments$1[i]; // eslint-disable-line prefer-rest-params - } + else { + this._renderDefault(renderer); } - - var shape = new math.Polygon(points); - - shape.closeStroke = closeStroke; - - this.drawShape(shape); - - return this; }; - /** - * Draw any shape. - * - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + * Standard non-batching way of rendering. + * @protected + * @param {PIXI.Renderer} renderer - Instance to renderer. */ - Graphics.prototype.drawShape = function drawShape (shape) - { - if (!this._holeMode) - { - this.geometry.drawShape( - shape, - this._fillStyle.clone(), - this._lineStyle.clone(), - this._matrix - ); + Mesh.prototype._renderDefault = function (renderer) { + var shader = this.shader; + shader.alpha = this.worldAlpha; + if (shader.update) { + shader.update(); } - else - { - this.geometry.drawHole(shape, this._matrix); + renderer.batch.flush(); + if (shader.program.uniformData.translationMatrix) { + shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true); } - - return this; - }; - - /** - * Draw a star shape with an arbitrary number of points. - * - * @param {number} x - Center X position of the star - * @param {number} y - Center Y position of the star - * @param {number} points - The number of points of the star, must be > 1 - * @param {number} radius - The outer radius of the star - * @param {number} [innerRadius] - The inner radius between points, default half `radius` - * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawStar = function drawStar (x, y, points, radius, innerRadius, rotation) - { - if ( rotation === void 0 ) rotation = 0; - - return this.drawPolygon(new Star(x, y, points, radius, innerRadius, rotation)); - }; - - /** - * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. - * - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.clear = function clear () - { - this.geometry.clear(); - this._lineStyle.reset(); - this._fillStyle.reset(); - - this._matrix = null; - this._holeMode = false; - this.currentPath = null; - - return this; - }; - - /** - * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and - * masked with gl.scissor. - * - * @returns {boolean} True if only 1 rect. - */ - Graphics.prototype.isFastRect = function isFastRect () - { - return this.geometry.graphicsData.length === 1 - && this.geometry.graphicsData[0].shape.type === math.SHAPES.RECT - && !this.geometry.graphicsData[0].lineWidth; - }; - - /** - * Renders the object using the WebGL renderer - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Graphics.prototype._render = function _render (renderer) - { - this.finishPoly(); - - var geometry = this.geometry; - - // batch part.. - // batch it! - geometry.updateBatches(); - - if (geometry.batchable) - { - if (this.batchDirty !== geometry.batchDirty) - { - this._populateBatches(); - } - - this._renderBatched(renderer); - } - else - { - // no batching... - renderer.batch.flush(); - - this._renderDirect(renderer); - } - }; - - /** - * Populating batches for rendering - * - * @protected - */ - Graphics.prototype._populateBatches = function _populateBatches () - { - var geometry = this.geometry; - var blendMode = this.blendMode; - - this.batches = []; - this.batchTint = -1; - this._transformID = -1; - this.batchDirty = geometry.batchDirty; - - this.vertexData = new Float32Array(geometry.points); - - for (var i = 0, l = geometry.batches.length; i < l; i++) - { - var gI = geometry.batches[i]; - var color = gI.style.color; - var vertexData = new Float32Array(this.vertexData.buffer, - gI.attribStart * 4 * 2, - gI.attribSize * 2); - - var uvs = new Float32Array(geometry.uvsFloat32.buffer, - gI.attribStart * 4 * 2, - gI.attribSize * 2); - - var indices = new Uint16Array(geometry.indicesUint16.buffer, - gI.start * 2, - gI.size); - - var batch = { - vertexData: vertexData, - blendMode: blendMode, - indices: indices, - uvs: uvs, - _batchRGB: utils.hex2rgb(color), - _tintRGB: color, - _texture: gI.style.texture, - alpha: gI.style.alpha, - worldAlpha: 1 }; - - this.batches[i] = batch; - } - }; - - /** - * Renders the batches using the BathedRenderer plugin - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Graphics.prototype._renderBatched = function _renderBatched (renderer) - { - if (!this.batches.length) - { - return; - } - - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - - this.calculateVertices(); - this.calculateTints(); - - for (var i = 0, l = this.batches.length; i < l; i++) - { - var batch = this.batches[i]; - - batch.worldAlpha = this.worldAlpha * batch.alpha; - - renderer.plugins[this.pluginName].render(batch); - } - }; - - /** - * Renders the graphics direct - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Graphics.prototype._renderDirect = function _renderDirect (renderer) - { - var shader = this._resolveDirectShader(renderer); - - var geometry = this.geometry; - var tint = this.tint; - var worldAlpha = this.worldAlpha; - var uniforms = shader.uniforms; - var drawCalls = geometry.drawCalls; - - // lets set the transfomr - uniforms.translationMatrix = this.transform.worldTransform; - - // and then lets set the tint.. - uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha; - uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha; - uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha; - uniforms.tint[3] = worldAlpha; - - // the first draw call, we can set the uniforms of the shader directly here. - - // this means that we can tack advantage of the sync function of pixi! // bind and sync uniforms.. - // there is a way to optimise this.. renderer.shader.bind(shader); - renderer.geometry.bind(geometry, shader); - // set state.. renderer.state.set(this.state); - - // then render the rest of them... - for (var i = 0, l = drawCalls.length; i < l; i++) - { - this._renderDrawCallDirect(renderer, geometry.drawCalls[i]); - } - }; - - /** - * Renders specific DrawCall - * - * @param {PIXI.Renderer} renderer - * @param {PIXI.BatchDrawCall} drawCall - */ - Graphics.prototype._renderDrawCallDirect = function _renderDrawCallDirect (renderer, drawCall) - { - var textures = drawCall.textures; - var type = drawCall.type; - var size = drawCall.size; - var start = drawCall.start; - var groupTextureCount = textures.count; - - for (var j = 0; j < groupTextureCount; j++) - { - renderer.texture.bind(textures.elements[j], j); - } - - renderer.geometry.draw(type, size, start); - }; - - /** - * Resolves shader for direct rendering - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Graphics.prototype._resolveDirectShader = function _resolveDirectShader (renderer) - { - var shader = this.shader; - - var pluginName = this.pluginName; - - if (!shader) - { - // if there is no shader here, we can use the default shader. - // and that only gets created if we actually need it.. - // but may be more than one plugins for graphics - if (!DEFAULT_SHADERS[pluginName]) - { - var sampleValues = new Int32Array(16); - - for (var i = 0; i < 16; i++) - { - sampleValues[i] = i; - } - - var uniforms = { - tint: new Float32Array([1, 1, 1, 1]), - translationMatrix: new math.Matrix(), - default: core.UniformGroup.from({ uSamplers: sampleValues }, true), - }; - - var program = renderer.plugins[pluginName]._shader.program; - - DEFAULT_SHADERS[pluginName] = new core.Shader(program, uniforms); - } - - shader = DEFAULT_SHADERS[pluginName]; - } - - return shader; + // bind the geometry... + renderer.geometry.bind(this.geometry, shader); + // then render it + renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); }; - /** - * Retrieves the bounds of the graphic shape as a rectangle object - * + * Rendering by using the Batch system. * @protected + * @param {PIXI.Renderer} renderer - Instance to renderer. */ - Graphics.prototype._calculateBounds = function _calculateBounds () - { - this.finishPoly(); - + Mesh.prototype._renderToBatch = function (renderer) { var geometry = this.geometry; - - // skipping when graphics is empty, like a container - if (!geometry.graphicsData.length) - { - return; - } - - var ref = geometry.bounds; - var minX = ref.minX; - var minY = ref.minY; - var maxX = ref.maxX; - var maxY = ref.maxY; - - this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); - }; - - /** - * Tests if a point is inside this graphics object - * - * @param {PIXI.Point} point - the point to test - * @return {boolean} the result of the test - */ - Graphics.prototype.containsPoint = function containsPoint (point) - { - this.worldTransform.applyInverse(point, Graphics._TEMP_POINT); - - return this.geometry.containsPoint(Graphics._TEMP_POINT); - }; - - /** - * Recalcuate the tint by applying tin to batches using Graphics tint. - * @protected - */ - Graphics.prototype.calculateTints = function calculateTints () - { - if (this.batchTint !== this.tint) - { - this.batchTint = this.tint; - - var tintRGB = utils.hex2rgb(this.tint, temp); - - for (var i = 0; i < this.batches.length; i++) - { - var batch = this.batches[i]; - - var batchTint = batch._batchRGB; - - var r = (tintRGB[0] * batchTint[0]) * 255; - var g = (tintRGB[1] * batchTint[1]) * 255; - var b = (tintRGB[2] * batchTint[2]) * 255; - - // TODO Ivan, can this be done in one go? - var color = (r << 16) + (g << 8) + (b | 0); - - batch._tintRGB = (color >> 16) - + (color & 0xff00) - + ((color & 0xff) << 16); - } + if (this.shader.uvMatrix) { + this.shader.uvMatrix.update(); + this.calculateUvs(); } + // set properties for batching.. + this.calculateVertices(); + this.indices = geometry.indexBuffer.data; + this._tintRGB = this.shader._tintRGB; + this._texture = this.shader.texture; + var pluginName = this.material.pluginName; + renderer.batch.setObjectRenderer(renderer.plugins[pluginName]); + renderer.plugins[pluginName].render(this); }; - /** - * If there's a transform update or a change to the shape of the - * geometry, recaculate the vertices. - * @protected + * Updates vertexData field based on transform and vertices */ - Graphics.prototype.calculateVertices = function calculateVertices () - { - if (this._transformID === this.transform._worldID) - { + Mesh.prototype.calculateVertices = function () { + var geometry = this.geometry; + var vertices = geometry.buffers[0].data; + if (geometry.vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) { return; } - this._transformID = this.transform._worldID; - + if (this.vertexData.length !== vertices.length) { + this.vertexData = new Float32Array(vertices.length); + } var wt = this.transform.worldTransform; var a = wt.a; var b = wt.b; @@ -24163,25199 +25570,20774 @@ var Graphics = /*@__PURE__*/(function (Container) { var d = wt.d; var tx = wt.tx; var ty = wt.ty; - - var data = this.geometry.points;// batch.vertexDataOriginal; var vertexData = this.vertexData; - - var count = 0; - - for (var i = 0; i < data.length; i += 2) - { - var x = data[i]; - var y = data[i + 1]; - - vertexData[count++] = (a * x) + (c * y) + tx; - vertexData[count++] = (d * y) + (b * x) + ty; + for (var i = 0; i < vertexData.length / 2; i++) { + var x = vertices[(i * 2)]; + var y = vertices[(i * 2) + 1]; + vertexData[(i * 2)] = (a * x) + (c * y) + tx; + vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty; + } + if (this._roundPixels) { + var resolution = settings.settings.RESOLUTION; + for (var i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); + } } + this.vertexDirty = geometry.vertexDirtyId; }; - /** - * Closes the current path. - * - * @return {PIXI.Graphics} Returns itself. + * Updates uv field based on from geometry uv's or batchUvs */ - Graphics.prototype.closePath = function closePath () - { - var currentPath = this.currentPath; - - if (currentPath) - { - // we don't need to add extra point in the end because buildLine will take care of that - currentPath.closeStroke = true; + Mesh.prototype.calculateUvs = function () { + var geomUvs = this.geometry.buffers[1]; + if (!this.shader.uvMatrix.isSimple) { + if (!this.batchUvs) { + this.batchUvs = new MeshBatchUvs(geomUvs, this.shader.uvMatrix); + } + this.batchUvs.update(); + this.uvs = this.batchUvs.data; + } + else { + this.uvs = geomUvs.data; } - - return this; }; - /** - * Apply a matrix to the positional data. + * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly. * - * @param {PIXI.Matrix} matrix - Matrix to use for transform current shape. - * @return {PIXI.Graphics} Returns itself. - */ - Graphics.prototype.setMatrix = function setMatrix (matrix) - { - this._matrix = matrix; - - return this; - }; - - /** - * Begin adding holes to the last draw shape - * IMPORTANT: holes must be fully inside a shape to work - * Also weirdness ensues if holes overlap! - * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer, - * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle. - * @return {PIXI.Graphics} Returns itself. + * @protected */ - Graphics.prototype.beginHole = function beginHole () - { - this.finishPoly(); - this._holeMode = true; - - return this; + Mesh.prototype._calculateBounds = function () { + this.calculateVertices(); + this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); }; - /** - * End adding holes to the last draw shape - * @return {PIXI.Graphics} Returns itself. + * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES. + * + * @param {PIXI.IPointData} point - the point to test + * @return {boolean} the result of the test */ - Graphics.prototype.endHole = function endHole () - { - this.finishPoly(); - this._holeMode = false; - - return this; + Mesh.prototype.containsPoint = function (point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + this.worldTransform.applyInverse(point, tempPoint); + var vertices = this.geometry.getBuffer('aVertexPosition').data; + var points = tempPolygon.points; + var indices = this.geometry.getIndex().data; + var len = indices.length; + var step = this.drawMode === 4 ? 3 : 1; + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + return false; }; - /** - * Destroys the Graphics object. + * Destroys the Mesh object. * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all * options have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have * their destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite */ - Graphics.prototype.destroy = function destroy (options) - { - Container.prototype.destroy.call(this, options); - + Mesh.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); this.geometry.refCount--; - if (this.geometry.refCount === 0) - { + if (this.geometry.refCount === 0) { this.geometry.dispose(); } - - this._matrix = null; - this.currentPath = null; - this._lineStyle.destroy(); - this._lineStyle = null; - this._fillStyle.destroy(); - this._fillStyle = null; this.geometry = null; this.shader = null; + this.state = null; + this.uvs = null; + this.indices = null; this.vertexData = null; - this.batches.length = 0; - this.batches = null; - - Container.prototype.destroy.call(this, options); }; - - Object.defineProperties( Graphics.prototype, prototypeAccessors ); - - return Graphics; + /** + * The maximum number of vertices to consider batchable. Generally, the complexity + * of the geometry. + * @memberof PIXI.Mesh + * @static + * @member {number} BATCHABLE_SIZE + */ + Mesh.BATCHABLE_SIZE = 100; + return Mesh; }(display.Container)); -/** - * Temporary point to use for containsPoint - * - * @static - * @private - * @member {PIXI.Point} - */ -Graphics._TEMP_POINT = new math.Point(); - -exports.FillStyle = FillStyle; -exports.GRAPHICS_CURVES = GRAPHICS_CURVES; -exports.Graphics = Graphics; -exports.GraphicsData = GraphicsData; -exports.GraphicsGeometry = GraphicsGeometry; -exports.LineStyle = LineStyle; -exports.graphicsUtils = index; - - -},{"@pixi/constants":16,"@pixi/core":17,"@pixi/display":18,"@pixi/math":29,"@pixi/utils":47}],27:[function(require,module,exports){ -/*! - * @pixi/interaction - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/interaction is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); +var fragment = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"; -var math = require('@pixi/math'); -var ticker = require('@pixi/ticker'); -var display = require('@pixi/display'); -var utils = require('@pixi/utils'); +var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n"; /** - * Holds all information related to an Interaction event - * + * Slightly opinionated default shader for PixiJS 2D objects. * @class - * @memberof PIXI.interaction + * @memberof PIXI + * @extends PIXI.Shader */ -var InteractionData = function InteractionData() -{ - /** - * This point stores the global coords of where the touch/mouse event happened - * - * @member {PIXI.Point} - */ - this.global = new math.Point(); - - /** - * The target Sprite that was interacted with - * - * @member {PIXI.Sprite} - */ - this.target = null; - - /** - * When passed to an event handler, this will be the original DOM Event that was captured - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent - * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent - * @member {MouseEvent|TouchEvent|PointerEvent} - */ - this.originalEvent = null; - - /** - * Unique identifier for this interaction - * - * @member {number} - */ - this.identifier = null; - - /** - * Indicates whether or not the pointer device that created the event is the primary pointer. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary - * @type {Boolean} - */ - this.isPrimary = false; - - /** - * Indicates which button was pressed on the mouse or pointer device to trigger the event. - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button - * @type {number} - */ - this.button = 0; - - /** - * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons - * @type {number} - */ - this.buttons = 0; - - /** - * The width of the pointer's contact along the x-axis, measured in CSS pixels. - * radiusX of TouchEvents will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width - * @type {number} - */ - this.width = 0; - - /** - * The height of the pointer's contact along the y-axis, measured in CSS pixels. - * radiusY of TouchEvents will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height - * @type {number} - */ - this.height = 0; - - /** - * The angle, in degrees, between the pointer device and the screen. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX - * @type {number} - */ - this.tiltX = 0; - - /** - * The angle, in degrees, between the pointer device and the screen. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY - * @type {number} - */ - this.tiltY = 0; - - /** - * The type of pointer that triggered the event. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType - * @type {string} - */ - this.pointerType = null; - +var MeshMaterial = /** @class */ (function (_super) { + __extends(MeshMaterial, _super); /** - * Pressure applied by the pointing device during the event. A Touch's force property - * will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure - * @type {number} + * @param {PIXI.Texture} uSampler - Texture that material uses to render. + * @param {object} [options] - Additional options + * @param {number} [options.alpha=1] - Default alpha. + * @param {number} [options.tint=0xFFFFFF] - Default tint. + * @param {string} [options.pluginName='batch'] - Renderer plugin for batching. + * @param {PIXI.Program} [options.program=0xFFFFFF] - Custom program. + * @param {object} [options.uniforms] - Custom uniforms. */ - this.pressure = 0; - - /** - * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. - * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle - * @type {number} - */ - this.rotationAngle = 0; - + function MeshMaterial(uSampler, options) { + var _this = this; + var uniforms = { + uSampler: uSampler, + alpha: 1, + uTextureMatrix: math.Matrix.IDENTITY, + uColor: new Float32Array([1, 1, 1, 1]), + }; + // Set defaults + options = Object.assign({ + tint: 0xFFFFFF, + alpha: 1, + pluginName: 'batch', + }, options); + if (options.uniforms) { + Object.assign(uniforms, options.uniforms); + } + _this = _super.call(this, options.program || core.Program.from(vertex, fragment), uniforms) || this; + /** + * Only do update if tint or alpha changes. + * @member {boolean} + * @private + * @default false + */ + _this._colorDirty = false; + /** + * TextureMatrix instance for this Mesh, used to track Texture changes + * + * @member {PIXI.TextureMatrix} + * @readonly + */ + _this.uvMatrix = new core.TextureMatrix(uSampler); + /** + * `true` if shader can be batch with the renderer's batch system. + * @member {boolean} + * @default true + */ + _this.batchable = options.program === undefined; + /** + * Renderer plugin for batching + * + * @member {string} + * @default 'batch' + */ + _this.pluginName = options.pluginName; + _this.tint = options.tint; + _this.alpha = options.alpha; + return _this; + } + Object.defineProperty(MeshMaterial.prototype, "texture", { + /** + * Reference to the texture being rendered. + * @member {PIXI.Texture} + */ + get: function () { + return this.uniforms.uSampler; + }, + set: function (value) { + if (this.uniforms.uSampler !== value) { + this.uniforms.uSampler = value; + this.uvMatrix.texture = value; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(MeshMaterial.prototype, "alpha", { + get: function () { + return this._alpha; + }, + /** + * This gets automatically set by the object using this. + * + * @default 1 + * @member {number} + */ + set: function (value) { + if (value === this._alpha) + { return; } + this._alpha = value; + this._colorDirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(MeshMaterial.prototype, "tint", { + get: function () { + return this._tint; + }, + /** + * Multiply tint for the material. + * @member {number} + * @default 0xFFFFFF + */ + set: function (value) { + if (value === this._tint) + { return; } + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + this._colorDirty = true; + }, + enumerable: false, + configurable: true + }); /** - * Twist of a stylus pointer. - * @see https://w3c.github.io/pointerevents/#pointerevent-interface - * @type {number} + * Gets called automatically by the Mesh. Intended to be overridden for custom + * MeshMaterial objects. */ - this.twist = 0; + MeshMaterial.prototype.update = function () { + if (this._colorDirty) { + this._colorDirty = false; + var baseTexture = this.texture.baseTexture; + utils.premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode); + } + if (this.uvMatrix.update()) { + this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord; + } + }; + return MeshMaterial; +}(core.Shader)); +/** + * Standard 2D geometry used in PixiJS. + * + * Geometry can be defined without passing in a style or data if required. + * + * ```js + * const geometry = new PIXI.Geometry(); + * + * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); + * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2); + * geometry.addIndex([0,1,2,1,3,2]); + * + * ``` + * @class + * @memberof PIXI + * @extends PIXI.Geometry + */ +var MeshGeometry = /** @class */ (function (_super) { + __extends(MeshGeometry, _super); /** - * Barrel pressure on a stylus pointer. - * @see https://w3c.github.io/pointerevents/#pointerevent-interface - * @type {number} + * @param {Float32Array|number[]} [vertices] - Positional data on geometry. + * @param {Float32Array|number[]} [uvs] - Texture UVs. + * @param {Uint16Array|number[]} [index] - IndexBuffer */ - this.tangentialPressure = 0; -}; - -var prototypeAccessors = { pointerId: { configurable: true } }; + function MeshGeometry(vertices, uvs, index) { + var _this = _super.call(this) || this; + var verticesBuffer = new core.Buffer(vertices); + var uvsBuffer = new core.Buffer(uvs, true); + var indexBuffer = new core.Buffer(index, true, true); + _this.addAttribute('aVertexPosition', verticesBuffer, 2, false, constants.TYPES.FLOAT) + .addAttribute('aTextureCoord', uvsBuffer, 2, false, constants.TYPES.FLOAT) + .addIndex(indexBuffer); + /** + * Dirty flag to limit update calls on Mesh. For example, + * limiting updates on a single Mesh instance with a shared Geometry + * within the render loop. + * @private + * @member {number} + * @default -1 + */ + _this._updateId = -1; + return _this; + } + Object.defineProperty(MeshGeometry.prototype, "vertexDirtyId", { + /** + * If the vertex position is updated. + * @member {number} + * @readonly + * @private + */ + get: function () { + return this.buffers[0]._updateID; + }, + enumerable: false, + configurable: true + }); + return MeshGeometry; +}(core.Geometry)); -/** - * The unique identifier of the pointer. It will be the same as `identifier`. - * @readonly - * @member {number} - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId - */ -prototypeAccessors.pointerId.get = function () -{ - return this.identifier; -}; +exports.Mesh = Mesh; +exports.MeshBatchUvs = MeshBatchUvs; +exports.MeshGeometry = MeshGeometry; +exports.MeshMaterial = MeshMaterial; -/** - * This will return the local coordinates of the specified displayObject for this InteractionData - * - * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local - * coords off - * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise - * will create a new point) - * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional - * (otherwise will use the current global coords) - * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative - * to the DisplayObject - */ -InteractionData.prototype.getLocalPosition = function getLocalPosition (displayObject, point, globalPos) -{ - return displayObject.worldTransform.applyInverse(globalPos || this.global, point); -}; -/** - * Copies properties from normalized event data. +},{"@pixi/constants":7,"@pixi/core":8,"@pixi/display":9,"@pixi/math":20,"@pixi/settings":30,"@pixi/utils":38}],23:[function(require,module,exports){ +/*! + * @pixi/mixin-cache-as-bitmap - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @param {Touch|MouseEvent|PointerEvent} event The normalized event data + * @pixi/mixin-cache-as-bitmap is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license */ -InteractionData.prototype.copyEvent = function copyEvent (event) -{ - // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite - // it with "false" on later events when our shim for it on touch events might not be - // accurate - if (event.isPrimary) - { - this.isPrimary = true; - } - this.button = event.button; - // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard - // event.which property instead, which conveys the same information. - this.buttons = Number.isInteger(event.buttons) ? event.buttons : event.which; - this.width = event.width; - this.height = event.height; - this.tiltX = event.tiltX; - this.tiltY = event.tiltY; - this.pointerType = event.pointerType; - this.pressure = event.pressure; - this.rotationAngle = event.rotationAngle; - this.twist = event.twist || 0; - this.tangentialPressure = event.tangentialPressure || 0; -}; +'use strict'; -/** - * Resets the data for pooling. - */ -InteractionData.prototype.reset = function reset () -{ - // isPrimary is the only property that we really need to reset - everything else is - // guaranteed to be overwritten - this.isPrimary = false; -}; +Object.defineProperty(exports, '__esModule', { value: true }); -Object.defineProperties( InteractionData.prototype, prototypeAccessors ); +var core = require('@pixi/core'); +var sprite = require('@pixi/sprite'); +var display = require('@pixi/display'); +var math = require('@pixi/math'); +var utils = require('@pixi/utils'); +var settings = require('@pixi/settings'); +var _tempMatrix = new math.Matrix(); +display.DisplayObject.prototype._cacheAsBitmap = false; +display.DisplayObject.prototype._cacheData = null; +// figured there's no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. /** - * Event class that mimics native DOM events. - * * @class - * @memberof PIXI.interaction + * @ignore */ -var InteractionEvent = function InteractionEvent() -{ - /** - * Whether this event will continue propagating in the tree. - * - * Remaining events for the {@link stopsPropagatingAt} object - * will still be dispatched. - * - * @member {boolean} - */ - this.stopped = false; - +var CacheData = /** @class */ (function () { + function CacheData() { + this.textureCacheId = null; + this.originalRender = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + this.originalUpdateTransform = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.originalContainsPoint = null; + this.sprite = null; + } + return CacheData; +}()); +Object.defineProperties(display.DisplayObject.prototype, { /** - * At which object this event stops propagating. + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to `false` * - * @private - * @member {PIXI.DisplayObject} - */ - this.stopsPropagatingAt = null; - - /** - * Whether we already reached the element we want to - * stop propagating at. This is important for delayed events, - * where we start over deeper in the tree again. + * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. * - * @private * @member {boolean} + * @memberof PIXI.DisplayObject# */ - this.stopPropagationHint = false; - - /** - * The object which caused this event to be dispatched. - * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. - * - * @member {PIXI.DisplayObject} - */ - this.target = null; - - /** - * The object whose event listener’s callback is currently being invoked. - * - * @member {PIXI.DisplayObject} - */ - this.currentTarget = null; - - /** - * Type of the event - * - * @member {string} - */ - this.type = null; - - /** - * InteractionData related to this event - * - * @member {PIXI.interaction.InteractionData} - */ - this.data = null; -}; - + cacheAsBitmap: { + get: function () { + return this._cacheAsBitmap; + }, + set: function (value) { + if (this._cacheAsBitmap === value) { + return; + } + this._cacheAsBitmap = value; + var data; + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + data = this._cacheData; + data.originalRender = this.render; + data.originalRenderCanvas = this.renderCanvas; + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this.calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + data.originalDestroy = this.destroy; + data.originalContainsPoint = this.containsPoint; + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + this.render = this._renderCached; + this.renderCanvas = this._renderCachedCanvas; + this.destroy = this._cacheAsBitmapDestroy; + } + else { + data = this._cacheData; + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + this.render = data.originalRender; + this.renderCanvas = data.originalRenderCanvas; + this.calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + this.destroy = data.originalDestroy; + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + }, + }, +}); /** - * Prevents event from reaching any objects other than the current object. + * Renders a cached version of the sprite with WebGL * + * @private + * @function _renderCached + * @memberof PIXI.DisplayObject# + * @param {PIXI.Renderer} renderer - the WebGL renderer */ -InteractionEvent.prototype.stopPropagation = function stopPropagation () -{ - this.stopped = true; - this.stopPropagationHint = true; - this.stopsPropagatingAt = this.currentTarget; +display.DisplayObject.prototype._renderCached = function _renderCached(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObject(renderer); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._render(renderer); }; - /** - * Resets the event. + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @function _initCachedDisplayObject + * @memberof PIXI.DisplayObject# + * @param {PIXI.Renderer} renderer - the WebGL renderer */ -InteractionEvent.prototype.reset = function reset () -{ - this.stopped = false; - this.stopsPropagatingAt = null; - this.stopPropagationHint = false; - this.currentTarget = null; - this.target = null; +display.DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + this.alpha = 1; + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.batch.flush(); + // this.filters= []; + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds(null, true).clone(); + // add some padding! + if (this.filters) { + var padding = this.filters[0].padding; + bounds.pad(padding); + } + bounds.ceil(settings.settings.RESOLUTION); + // for now we cache the current renderTarget that the WebGL renderer is currently using. + // this could be more elegant.. + var cachedRenderTexture = renderer.renderTexture.current; + var cachedSourceFrame = renderer.renderTexture.sourceFrame.clone(); + var cachedProjectionTransform = renderer.projection.transform; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + // const stack = renderer.filterManager.filterStack; + // this renderTexture will be used to store the cached DisplayObject + var renderTexture = core.RenderTexture.create({ width: bounds.width, height: bounds.height }); + var textureCacheId = "cacheAsBitmap_" + utils.uid(); + this._cacheData.textureCacheId = textureCacheId; + core.BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + core.Texture.addToCache(renderTexture, textureCacheId); + // need to set // + var m = this.transform.localTransform.copyTo(_tempMatrix).invert().translate(-bounds.x, -bounds.y); + // set all properties to there original so we can render to a texture + this.render = this._cacheData.originalRender; + renderer.render(this, renderTexture, true, m, false); + // now restore the state be setting the new properties + renderer.projection.transform = cachedProjectionTransform; + renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame); + // renderer.filterManager.filterStack = stack; + this.render = this._renderCached; + // the rest is the same as for Canvas + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + // create our cached sprite + var cachedSprite = new sprite.Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.enableTempParent(); + this.updateTransform(); + this.disableTempParent(null); + } + else { + this.updateTransform(); + } + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); }; - /** - * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * Renders a cached version of the sprite with canvas * - * @class * @private - * @memberof PIXI.interaction + * @function _renderCachedCanvas + * @memberof PIXI.DisplayObject# + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer */ -var InteractionTrackingData = function InteractionTrackingData(pointerId) -{ - this._pointerId = pointerId; - this._flags = InteractionTrackingData.FLAGS.NONE; +display.DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObjectCanvas(renderer); + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderCanvas(renderer); }; - -var prototypeAccessors$1 = { pointerId: { configurable: true },flags: { configurable: true },none: { configurable: true },over: { configurable: true },rightDown: { configurable: true },leftDown: { configurable: true } }; - +// TODO this can be the same as the WebGL version.. will need to do a little tweaking first though.. /** + * Prepares the Canvas renderer to cache the sprite * * @private - * @param {number} flag - The interaction flag to set - * @param {boolean} yn - Should the flag be set or unset + * @function _initCachedDisplayObjectCanvas + * @memberof PIXI.DisplayObject# + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer */ -InteractionTrackingData.prototype._doSet = function _doSet (flag, yn) -{ - if (yn) - { - this._flags = this._flags | flag; +display.DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; } - else - { - this._flags = this._flags & (~flag); + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(null, true); + var cacheAlpha = this.alpha; + this.alpha = 1; + var cachedRenderTarget = renderer.context; + var cachedProjectionTransform = renderer._projTransform; + bounds.ceil(settings.settings.RESOLUTION); + var renderTexture = core.RenderTexture.create({ width: bounds.width, height: bounds.height }); + var textureCacheId = "cacheAsBitmap_" + utils.uid(); + this._cacheData.textureCacheId = textureCacheId; + core.BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + core.Texture.addToCache(renderTexture, textureCacheId); + // need to set // + var m = _tempMatrix; + this.transform.localTransform.copyTo(m); + m.invert(); + m.tx -= bounds.x; + m.ty -= bounds.y; + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + renderer.render(this, renderTexture, true, m, false); + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + renderer._projTransform = cachedProjectionTransform; + this.renderCanvas = this._renderCachedCanvas; + // the rest is the same as for WebGL + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + // create our cached sprite + var cachedSprite = new sprite.Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } + else { + this.updateTransform(); } + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); }; - /** - * Unique pointer id of the event + * Calculates the bounds of the cached sprite * - * @readonly * @private - * @member {number} */ -prototypeAccessors$1.pointerId.get = function () -{ - return this._pointerId; +display.DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._bounds.clear(); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite._calculateBounds(); + this._bounds.updateID = this._boundsID; }; - /** - * State of the tracking data, expressed as bit flags + * Gets the bounds of the cached sprite. * * @private - * @member {number} + * @return {Rectangle} The local bounds. */ -prototypeAccessors$1.flags.get = function () -{ - return this._flags; -}; - -prototypeAccessors$1.flags.set = function (flags) // eslint-disable-line require-jsdoc -{ - this._flags = flags; +display.DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(null); }; - /** - * Is the tracked event inactive (not over or down)? + * Destroys the cached sprite. * * @private - * @member {number} */ -prototypeAccessors$1.none.get = function () -{ - return this._flags === this.constructor.FLAGS.NONE; +display.DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + core.BaseTexture.removeFromCache(this._cacheData.textureCacheId); + core.Texture.removeFromCache(this._cacheData.textureCacheId); + this._cacheData.textureCacheId = null; }; - /** - * Is the tracked event over the DisplayObject? + * Destroys the cached object. * * @private - * @member {boolean} + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. */ -prototypeAccessors$1.over.get = function () -{ - return (this._flags & this.constructor.FLAGS.OVER) !== 0; +display.DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); }; -prototypeAccessors$1.over.set = function (yn) // eslint-disable-line require-jsdoc -{ - this._doSet(this.constructor.FLAGS.OVER, yn); -}; +exports.CacheData = CacheData; -/** - * Did the right mouse button come down in the DisplayObject? + +},{"@pixi/core":8,"@pixi/display":9,"@pixi/math":20,"@pixi/settings":30,"@pixi/sprite":33,"@pixi/utils":38}],24:[function(require,module,exports){ +/*! + * @pixi/mixin-get-child-by-name - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @private - * @member {boolean} + * @pixi/mixin-get-child-by-name is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license */ -prototypeAccessors$1.rightDown.get = function () -{ - return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; -}; +'use strict'; -prototypeAccessors$1.rightDown.set = function (yn) // eslint-disable-line require-jsdoc -{ - this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); -}; +var display = require('@pixi/display'); /** - * Did the left mouse button come down in the DisplayObject? + * The instance name of the object. * - * @private - * @member {boolean} + * @memberof PIXI.DisplayObject# + * @member {string} name */ -prototypeAccessors$1.leftDown.get = function () -{ - return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; +display.DisplayObject.prototype.name = null; +/** + * Returns the display object in the container. + * + * Recursive searches are done in a preorder traversal. + * + * @method getChildByName + * @memberof PIXI.Container# + * @param {string} name - Instance name. + * @param {boolean}[deep=false] - Whether to search recursively + * @return {PIXI.DisplayObject} The child with the specified name. + */ +display.Container.prototype.getChildByName = function getChildByName(name, deep) { + for (var i = 0, j = this.children.length; i < j; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + if (deep) { + for (var i = 0, j = this.children.length; i < j; i++) { + var child = this.children[i]; + if (!child.getChildByName) { + continue; + } + var target = this.children[i].getChildByName(name, true); + if (target) { + return target; + } + } + } + return null; }; -prototypeAccessors$1.leftDown.set = function (yn) // eslint-disable-line require-jsdoc -{ - this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); -}; -Object.defineProperties( InteractionTrackingData.prototype, prototypeAccessors$1 ); +},{"@pixi/display":9}],25:[function(require,module,exports){ +/*! + * @pixi/mixin-get-global-position - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/mixin-get-global-position is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; -InteractionTrackingData.FLAGS = Object.freeze({ - NONE: 0, - OVER: 1 << 0, - LEFT_DOWN: 1 << 1, - RIGHT_DOWN: 1 << 2, -}); +var display = require('@pixi/display'); +var math = require('@pixi/math'); /** - * Strategy how to search through stage tree for interactive objects + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. * - * @private - * @class - * @memberof PIXI.interaction + * @method getGlobalPosition + * @memberof PIXI.DisplayObject# + * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to. + * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost. + * @return {PIXI.Point} The updated point. */ -var TreeSearch = function TreeSearch() -{ - this._tempPoint = new math.Point(); +display.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) { + if (point === void 0) { point = new math.Point(); } + if (skipUpdate === void 0) { skipUpdate = false; } + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } + else { + point.x = this.position.x; + point.y = this.position.y; + } + return point; }; -/** - * Recursive implementation for findHit + +},{"@pixi/display":9,"@pixi/math":20}],26:[function(require,module,exports){ +/*! + * @pixi/particles - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that - * is tested for collision - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param {Function} [func] - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point - * @param {boolean} [interactive] - Whether the displayObject is interactive - * @return {boolean} returns true if the displayObject hit the point - */ -TreeSearch.prototype.recursiveFindHit = function recursiveFindHit (interactionEvent, displayObject, func, hitTest, interactive) -{ - if (!displayObject || !displayObject.visible) - { - return false; - } + * @pixi/particles is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - var point = interactionEvent.data.global; +Object.defineProperty(exports, '__esModule', { value: true }); - // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^ - // - // This function will now loop through all objects and then only hit test the objects it HAS - // to, not all of them. MUCH faster.. - // An object will be hit test if the following is true: - // - // 1: It is interactive. - // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. - // - // As another little optimization once an interactive object has been hit we can carry on - // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests - // A final optimization is that an object is not hit test directly if a child has already been hit. - - interactive = displayObject.interactive || interactive; - - var hit = false; - var interactiveParent = interactive; - - // Flag here can set to false if the event is outside the parents hitArea or mask - var hitTestChildren = true; - - // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea - // There is also no longer a need to hitTest children. - if (displayObject.hitArea) - { - if (hitTest) - { - displayObject.worldTransform.applyInverse(point, this._tempPoint); - if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) - { - hitTest = false; - hitTestChildren = false; - } - else - { - hit = true; - } - } - interactiveParent = false; - } - // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask. - // We still want to hitTestChildren, however, to ensure a mouseout can still be generated. - // https://github.com/pixijs/pixi.js/issues/5135 - else if (displayObject._mask) - { - if (hitTest) - { - if (!(displayObject._mask.containsPoint && displayObject._mask.containsPoint(point))) - { - hitTest = false; - } - } - } - - // ** FREE TIP **! If an object is not interactive or has no buttons in it - // (such as a game scene!) set interactiveChildren to false for that displayObject. - // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. - if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) - { - var children = displayObject.children; - - for (var i = children.length - 1; i >= 0; i--) - { - var child = children[i]; - - // time to get recursive.. if this function will return if something is hit.. - var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent); - - if (childHit) - { - // its a good idea to check if a child has lost its parent. - // this means it has been removed whilst looping so its best - if (!child.parent) - { - continue; - } - - // we no longer need to hit test any more objects in this container as we we - // now know the parent has been hit - interactiveParent = false; - - // If the child is interactive , that means that the object hit was actually - // interactive and not just the child of an interactive object. - // This means we no longer need to hit test anything else. We still need to run - // through all objects, but we don't need to perform any hit tests. - - if (childHit) - { - if (interactionEvent.target) - { - hitTest = false; - } - hit = true; - } - } - } - } - - // no point running this if the item is not interactive or does not have an interactive parent. - if (interactive) - { - // if we are hit testing (as in we have no hit any objects yet) - // We also don't need to worry about hit testing if once of the displayObjects children - // has already been hit - but only if it was interactive, otherwise we need to keep - // looking for an interactive child, just in case we hit one - if (hitTest && !interactionEvent.target) - { - // already tested against hitArea if it is defined - if (!displayObject.hitArea && displayObject.containsPoint) - { - if (displayObject.containsPoint(point)) - { - hit = true; - } - } - } - - if (displayObject.interactive) - { - if (hit && !interactionEvent.target) - { - interactionEvent.target = displayObject; - } - - if (func) - { - func(interactionEvent, displayObject, !!hit); - } - } - } - - return hit; -}; - -/** - * This function is provides a neat way of crawling through the scene graph and running a - * specified function on all interactive objects it finds. It will also take care of hit - * testing the interactive objects and passes the hit across in the function. - * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that - * is tested for collision - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param {Function} [func] - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point - * @return {boolean} returns true if the displayObject hit the point - */ -TreeSearch.prototype.findHit = function findHit (interactionEvent, displayObject, func, hitTest) -{ - this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false); -}; - -/** - * Interface for classes that represent a hit area. - * - * It is implemented by the following classes: - * - {@link PIXI.Circle} - * - {@link PIXI.Ellipse} - * - {@link PIXI.Polygon} - * - {@link PIXI.RoundedRectangle} - * - * @interface IHitArea - * @memberof PIXI - */ +var constants = require('@pixi/constants'); +var display = require('@pixi/display'); +var utils = require('@pixi/utils'); +var core = require('@pixi/core'); +var math = require('@pixi/math'); -/** - * Checks whether the x and y coordinates given are contained within this area - * - * @method - * @name contains - * @memberof PIXI.IHitArea# - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this area - */ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} /** - * Default property values of interactive objects - * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. * - * @private - * @name interactiveTarget - * @type {Object} - * @memberof PIXI.interaction - * @example - * function MyObject() {} + * The tradeoff of the ParticleContainer is that most advanced functionality will not work. + * ParticleContainer implements the basic object transform (position, scale, rotation) + * and some advanced functionality like tint (as of v4.5.6). * - * Object.assign( - * DisplayObject.prototype, - * PIXI.interaction.interactiveTarget - * ); - */ -var interactiveTarget = { - - /** - * Enable interaction events for the DisplayObject. Touch, pointer and mouse - * events will not be emitted unless `interactive` is set to `true`. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.on('tap', (event) => { - * //handle event - * }); - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - interactive: false, - - /** - * Determines if the children to the displayObject can be clicked/touched - * Setting this to false allows PixiJS to bypass a recursive `hitTest` function - * - * @member {boolean} - * @memberof PIXI.Container# - */ - interactiveChildren: true, - - /** - * Interaction shape. Children will be hit first, then this shape will be checked. - * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); - * @member {PIXI.IHitArea} - * @memberof PIXI.DisplayObject# - */ - hitArea: null, - - /** - * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive - * Setting this changes the 'cursor' property to `'pointer'`. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.buttonMode = true; - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - get buttonMode() - { - return this.cursor === 'pointer'; - }, - set buttonMode(value) - { - if (value) - { - this.cursor = 'pointer'; - } - else if (this.cursor === 'pointer') - { - this.cursor = null; - } - }, - - /** - * This defines what cursor mode is used when the mouse cursor - * is hovered over the displayObject. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.cursor = 'wait'; - * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor - * - * @member {string} - * @memberof PIXI.DisplayObject# - */ - cursor: null, - - /** - * Internal set of all active pointers, by identifier - * - * @member {Map} - * @memberof PIXI.DisplayObject# - * @private - */ - get trackedPointers() - { - if (this._trackedPointers === undefined) { this._trackedPointers = {}; } - - return this._trackedPointers; - }, - - /** - * Map of all tracked pointers, by identifier. Use trackedPointers to access. - * - * @private - * @type {Map} - */ - _trackedPointers: undefined, -}; - -// Mix interactiveTarget into DisplayObject.prototype, -// after deprecation has been handled -display.DisplayObject.mixin(interactiveTarget); - -var MOUSE_POINTER_ID = 1; - -// helpers for hitTest() - only used inside hitTest() -var hitTestEvent = { - target: null, - data: { - global: null, - }, -}; - -/** - * The interaction manager deals with mouse, touch and pointer events. + * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. * - * Any DisplayObject can be interactive if its `interactive` property is set to true. + * It's extremely easy to use: + * ```js + * let container = new ParticleContainer(); * - * This manager also supports multitouch. + * for (let i = 0; i < 100; ++i) + * { + * let sprite = PIXI.Sprite.from("myImage.png"); + * container.addChild(sprite); + * } + * ``` * - * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction` + * And here you have a hundred sprites that will be rendered at the speed of light. * * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI.interaction + * @extends PIXI.Container + * @memberof PIXI */ -var InteractionManager = /*@__PURE__*/(function (EventEmitter) { - function InteractionManager(renderer, options) - { - EventEmitter.call(this); - - options = options || {}; - +var ParticleContainer = /** @class */ (function (_super) { + __extends(ParticleContainer, _super); + /** + * @param {number} [maxSize=1500] - The maximum number of particles that can be rendered by the container. + * Affects size of allocated buffers. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. + * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. + * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. + * @param {boolean} [autoResize=false] - If true, container allocates more batches in case + * there are more than `maxSize` particles. + */ + function ParticleContainer(maxSize, properties, batchSize, autoResize) { + if (maxSize === void 0) { maxSize = 1500; } + if (batchSize === void 0) { batchSize = 16384; } + if (autoResize === void 0) { autoResize = false; } + var _this = _super.call(this) || this; + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var maxBatchSize = 16384; + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } /** - * The renderer this interaction manager works for. + * Set properties to be dynamic (true) / static (false) * - * @member {PIXI.AbstractRenderer} + * @member {boolean[]} + * @private */ - this.renderer = renderer; - + _this._properties = [false, true, false, false, false]; /** - * Should default browser actions automatically be prevented. - * Does not apply to pointer events for backwards compatibility - * preventDefault on pointer events stops mouse events from firing - * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. - * - * @member {boolean} - * @default true + * @member {number} + * @private */ - this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; - + _this._maxSize = maxSize; /** - * Frequency in milliseconds that the mousemove, mouseover & mouseout interaction events will be checked. - * * @member {number} - * @default 10 + * @private */ - this.interactionFrequency = options.interactionFrequency || 10; - + _this._batchSize = batchSize; /** - * The mouse data - * - * @member {PIXI.interaction.InteractionData} + * @member {Array} + * @private */ - this.mouse = new InteractionData(); - this.mouse.identifier = MOUSE_POINTER_ID; - - // setting the mouse to start off far off screen will mean that mouse over does - // not get called before we even move the mouse. - this.mouse.global.set(-999999); - + _this._buffers = null; /** - * Actively tracked InteractionData - * + * for every batch stores _updateID corresponding to the last change in that batch + * @member {number[]} * @private - * @member {Object.} */ - this.activeInteractionData = {}; - this.activeInteractionData[MOUSE_POINTER_ID] = this.mouse; - + _this._bufferUpdateIDs = []; /** - * Pool of unused InteractionData - * + * when child inserted, removed or changes position this number goes up + * @member {number[]} * @private - * @member {PIXI.interaction.InteractionData[]} */ - this.interactionDataPool = []; - + _this._updateID = 0; /** - * An event data object to handle all the event tracking/dispatching + * @member {boolean} * - * @member {object} */ - this.eventData = new InteractionEvent(); - + _this.interactiveChildren = false; /** - * The DOM element to bind to. + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. * - * @protected - * @member {HTMLElement} + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES */ - this.interactionDOMElement = null; - + _this.blendMode = constants.BLEND_MODES.NORMAL; /** - * This property determines if mousemove and touchmove events are fired only when the cursor - * is over the object. - * Setting to true will make things work more in line with how the DOM version works. - * Setting to false can make things easier for things like dragging - * It is currently set to false as this is how PixiJS used to work. This will be set to true in - * future versions of pixi. - * + * If true, container allocates more batches in case there are more than `maxSize` particles. * @member {boolean} * @default false */ - this.moveWhenInside = false; - - /** - * Have events been attached to the dom element? - * - * @protected - * @member {boolean} - */ - this.eventsAdded = false; - + _this.autoResize = autoResize; /** - * Is the mouse hovering over the renderer? + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * Default to true here as performance is usually the priority for particles. * - * @protected * @member {boolean} + * @default true */ - this.mouseOverRenderer = false; - + _this.roundPixels = true; /** - * Does the device support touch events - * https://www.w3.org/TR/touch-events/ + * The texture used to render the children. * * @readonly - * @member {boolean} + * @member {PIXI.BaseTexture} */ - this.supportsTouchEvents = 'ontouchstart' in window; - + _this.baseTexture = null; + _this.setProperties(properties); /** - * Does the device support pointer events - * https://www.w3.org/Submission/pointer-events/ + * The tint applied to the container. + * This is a hex value. A value of 0xFFFFFF will remove any tint effect. * - * @readonly - * @member {boolean} - */ - this.supportsPointerEvents = !!window.PointerEvent; - - // this will make it so that you don't have to call bind all the time - - /** - * @private - * @member {Function} - */ - this.onPointerUp = this.onPointerUp.bind(this); - this.processPointerUp = this.processPointerUp.bind(this); - - /** - * @private - * @member {Function} - */ - this.onPointerCancel = this.onPointerCancel.bind(this); - this.processPointerCancel = this.processPointerCancel.bind(this); - - /** * @private - * @member {Function} + * @member {number} + * @default 0xFFFFFF */ - this.onPointerDown = this.onPointerDown.bind(this); - this.processPointerDown = this.processPointerDown.bind(this); - + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + ParticleContainer.prototype.setProperties = function (properties) { + if (properties) { + this._properties[0] = 'vertices' in properties || 'scale' in properties + ? !!properties.vertices || !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'tint' in properties || 'alpha' in properties + ? !!properties.tint || !!properties.alpha : this._properties[4]; + } + }; + /** + * Updates the object transform for rendering + * + * @private + */ + ParticleContainer.prototype.updateTransform = function () { + // TODO don't need to! + this.displayObjectUpdateTransform(); + }; + Object.defineProperty(ParticleContainer.prototype, "tint", { /** - * @private - * @member {Function} + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + ** IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. + * @member {number} + * @default 0xFFFFFF */ - this.onPointerMove = this.onPointerMove.bind(this); - this.processPointerMove = this.processPointerMove.bind(this); + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + utils.hex2rgb(value, this.tintRgb); + }, + enumerable: false, + configurable: true + }); + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.Renderer} renderer - The webgl renderer + */ + ParticleContainer.prototype.render = function (renderer) { + var _this = this; + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.valid) { + this.baseTexture.once('update', function () { return _this.onChildrenChange(0); }); + } + } + renderer.batch.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + while (this._bufferUpdateIDs.length < bufferIndex) { + this._bufferUpdateIDs.push(0); + } + this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + }; + ParticleContainer.prototype.dispose = function () { + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + this._buffers = null; + } + }; + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + ParticleContainer.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this.dispose(); + this._properties = null; + this._buffers = null; + this._bufferUpdateIDs = null; + }; + return ParticleContainer; +}(display.Container)); +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = /** @class */ (function () { + /** + * @private + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(properties, dynamicPropertyFlags, size) { + this.geometry = new core.Geometry(); + this.indexBuffer = null; /** + * The number of particles the buffer can hold + * * @private - * @member {Function} + * @member {number} */ - this.onPointerOut = this.onPointerOut.bind(this); - this.processPointerOverOut = this.processPointerOverOut.bind(this); - + this.size = size; /** + * A list of the properties that are dynamic. + * * @private - * @member {Function} - */ - this.onPointerOver = this.onPointerOver.bind(this); - - /** - * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor - * values, objects are handled as dictionaries of CSS values for interactionDOMElement, - * and functions are called instead of changing the CSS. - * Default CSS cursor values are provided for 'default' and 'pointer' modes. - * @member {Object.} + * @member {object[]} */ - this.cursorStyles = { - default: 'inherit', - pointer: 'pointer', - }; - + this.dynamicProperties = []; /** - * The mode of the cursor that is being used. - * The value of this is a key from the cursorStyles dictionary. + * A list of the properties that are static. * - * @member {string} + * @private + * @member {object[]} */ - this.currentCursorMode = null; - + this.staticProperties = []; + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attributeName: property.attributeName, + size: property.size, + uploadFunction: property.uploadFunction, + type: property.type || constants.TYPES.FLOAT, + offset: property.offset, + }; + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } + else { + this.staticProperties.push(property); + } + } + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this._updateID = 0; + this.initBuffers(); + } + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + ParticleBuffer.prototype.initBuffers = function () { + var geometry = this.geometry; + var dynamicOffset = 0; /** - * Internal cached let. + * Holds the indices of the geometry (quads) to draw * + * @member {Uint16Array} * @private - * @member {string} */ - this.cursor = null; - - /** - * The current resolution / device pixel ratio. - * - * @member {number} - * @default 1 - */ - this.resolution = 1; + this.indexBuffer = new core.Buffer(utils.createIndicesForQuads(this.size), true, true); + geometry.addIndex(this.indexBuffer); + this.dynamicStride = 0; + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = new core.Buffer(this.dynamicData, false, false); + // static // + var staticOffset = 0; + this.staticStride = 0; + for (var i = 0; i < this.staticProperties.length; ++i) { + var property = this.staticProperties[i]; + property.offset = staticOffset; + staticOffset += property.size; + this.staticStride += property.size; + } + var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = new core.Buffer(this.staticData, true, false); + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + geometry.addAttribute(property.attributeName, this.dynamicBuffer, 0, property.type === constants.TYPES.UNSIGNED_BYTE, property.type, this.dynamicStride * 4, property.offset * 4); + } + for (var i = 0; i < this.staticProperties.length; ++i) { + var property = this.staticProperties[i]; + geometry.addAttribute(property.attributeName, this.staticBuffer, 0, property.type === constants.TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4); + } + }; + /** + * Uploads the dynamic properties. + * + * @private + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + ParticleBuffer.prototype.uploadDynamic = function (children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === constants.TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + this.dynamicBuffer._updateID++; + }; + /** + * Uploads the static properties. + * + * @private + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + ParticleBuffer.prototype.uploadStatic = function (children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === constants.TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + this.staticBuffer._updateID++; + }; + /** + * Destroys the ParticleBuffer. + * + * @private + */ + ParticleBuffer.prototype.destroy = function () { + this.indexBuffer = null; + this.dynamicProperties = null; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this.staticProperties = null; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + // all buffers are destroyed inside geometry + this.geometry.destroy(); + }; + return ParticleBuffer; +}()); - /** - * Delayed pointer events. Used to guarantee correct ordering of over/out events. - * - * @private - * @member {Array} - */ - this.delayedEvents = []; +var fragment = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}"; - /** - * TreeSearch component that is used to hitTest stage tree - * - * @private - * @member {PIXI.interaction.TreeSearch} - */ - this.search = new TreeSearch(); +var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n"; +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ +/** + * Renderer for Particles that is designer for speed over feature set. + * + * @class + * @memberof PIXI + */ +var ParticleRenderer = /** @class */ (function (_super) { + __extends(ParticleRenderer, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; /** - * Fired when a pointer device button (usually a mouse left-button) is pressed on the display - * object. + * The default shader that is used if a sprite doesn't have a more specific one. * - * @event PIXI.interaction.InteractionManager#mousedown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * @member {PIXI.Shader} */ - + _this.shader = null; + _this.properties = null; + _this.tempMatrix = new math.Matrix(); + _this.properties = [ + // verticesData + { + attributeName: 'aVertexPosition', + size: 2, + uploadFunction: _this.uploadVertices, + offset: 0, + }, + // positionData + { + attributeName: 'aPositionCoord', + size: 2, + uploadFunction: _this.uploadPosition, + offset: 0, + }, + // rotationData + { + attributeName: 'aRotation', + size: 1, + uploadFunction: _this.uploadRotation, + offset: 0, + }, + // uvsData + { + attributeName: 'aTextureCoord', + size: 2, + uploadFunction: _this.uploadUvs, + offset: 0, + }, + // tintData + { + attributeName: 'aColor', + size: 1, + type: constants.TYPES.UNSIGNED_BYTE, + uploadFunction: _this.uploadTint, + offset: 0, + } ]; + _this.shader = core.Shader.from(vertex, fragment, {}); /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * on the display object. + * The WebGL state in which this renderer will work. * - * @event PIXI.interaction.InteractionManager#rightdown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * @member {PIXI.State} + * @readonly */ + _this.state = core.State.for2d(); + return _this; + } + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + ParticleRenderer.prototype.render = function (container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + if (totalChildren === 0) { + return; + } + else if (totalChildren > maxSize && !container.autoResize) { + totalChildren = maxSize; + } + var buffers = container._buffers; + if (!buffers) { + buffers = container._buffers = this.generateBuffers(container); + } + var baseTexture = children[0]._texture.baseTexture; + // if the uvs have not updated then no point rendering just yet! + this.state.blendMode = utils.correctBlendMode(container.blendMode, baseTexture.alphaMode); + renderer.state.set(this.state); + var gl = renderer.gl; + var m = container.worldTransform.copyTo(this.tempMatrix); + m.prepend(renderer.globalUniforms.uniforms.projectionMatrix); + this.shader.uniforms.translationMatrix = m.toArray(true); + this.shader.uniforms.uColor = utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.alphaMode); + this.shader.uniforms.uSampler = baseTexture; + this.renderer.shader.bind(this.shader); + var updateStatic = false; + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = (totalChildren - i); + if (amount > batchSize) { + amount = batchSize; + } + if (j >= buffers.length) { + buffers.push(this._generateOneMoreBuffer(container)); + } + var buffer = buffers[j]; + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + var bid = container._bufferUpdateIDs[j] || 0; + updateStatic = updateStatic || (buffer._updateID < bid); + // we only upload the static content when we have to! + if (updateStatic) { + buffer._updateID = container._updateID; + buffer.uploadStatic(children, i, amount); + } + // bind the buffer + renderer.geometry.bind(buffer.geometry); + gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + } + }; + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + * @private + */ + ParticleRenderer.prototype.generateBuffers = function (container) { + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + for (var i = 0; i < size; i += batchSize) { + buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize)); + } + return buffers; + }; + /** + * Creates one more particle buffer, because container has autoResize feature + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer} generated buffer + * @private + */ + ParticleRenderer.prototype._generateOneMoreBuffer = function (container) { + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize); + }; + /** + * Uploads the vertices. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - (sprite.anchor.x * orig.width); + w0 = w1 + trim.width; + h1 = trim.y - (sprite.anchor.y * orig.height); + h0 = h1 + trim.height; + } + else { + w0 = (orig.width) * (1 - sprite.anchor.x); + w1 = (orig.width) * -sprite.anchor.x; + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + array[offset + (stride * 2)] = w0 * sx; + array[offset + (stride * 2) + 1] = h0 * sy; + array[offset + (stride * 3)] = w1 * sx; + array[offset + (stride * 3) + 1] = h0 * sy; + offset += stride * 4; + } + }; + /** + * Uploads the position. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadPosition = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + array[offset + (stride * 2)] = spritePosition.x; + array[offset + (stride * 2) + 1] = spritePosition.y; + array[offset + (stride * 3)] = spritePosition.x; + array[offset + (stride * 3) + 1] = spritePosition.y; + offset += stride * 4; + } + }; + /** + * Uploads the rotation. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadRotation = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + (stride * 2)] = spriteRotation; + array[offset + (stride * 3)] = spriteRotation; + offset += stride * 4; + } + }; + /** + * Uploads the Uvs + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadUvs = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + array[offset + (stride * 2)] = textureUvs.x2; + array[offset + (stride * 2) + 1] = textureUvs.y2; + array[offset + (stride * 3)] = textureUvs.x3; + array[offset + (stride * 3) + 1] = textureUvs.y3; + offset += stride * 4; + } + else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + array[offset + (stride * 2)] = 0; + array[offset + (stride * 2) + 1] = 0; + array[offset + (stride * 3)] = 0; + array[offset + (stride * 3) + 1] = 0; + offset += stride * 4; + } + } + }; + /** + * Uploads the tint. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadTint = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var premultiplied = sprite._texture.baseTexture.alphaMode > 0; + var alpha = sprite.alpha; + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && premultiplied + ? utils.premultiplyTint(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + array[offset] = argb; + array[offset + stride] = argb; + array[offset + (stride * 2)] = argb; + array[offset + (stride * 3)] = argb; + offset += stride * 4; + } + }; + /** + * Destroys the ParticleRenderer. + */ + ParticleRenderer.prototype.destroy = function () { + _super.prototype.destroy.call(this); + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + this.tempMatrix = null; + }; + return ParticleRenderer; +}(core.ObjectRenderer)); - /** - * Fired when a pointer device button (usually a mouse left-button) is released over the display - * object. - * - * @event PIXI.interaction.InteractionManager#mouseup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +exports.ParticleContainer = ParticleContainer; +exports.ParticleRenderer = ParticleRenderer; - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * over the display object. - * - * @event PIXI.interaction.InteractionManager#rightup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed and released on - * the display object. - * - * @event PIXI.interaction.InteractionManager#click - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +},{"@pixi/constants":7,"@pixi/core":8,"@pixi/display":9,"@pixi/math":20,"@pixi/utils":38}],27:[function(require,module,exports){ +/*! + * @pixi/polyfill - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/polyfill is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * and released on the display object. - * - * @event PIXI.interaction.InteractionManager#rightclick - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - /** - * Fired when a pointer device button (usually a mouse left-button) is released outside the - * display object that initially registered a - * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. - * - * @event PIXI.interaction.InteractionManager#mouseupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +var es6PromisePolyfill = require('es6-promise-polyfill'); +var objectAssign = _interopDefault(require('object-assign')); - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * outside the display object that initially registered a - * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. - * - * @event PIXI.interaction.InteractionManager#rightupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +// Support for IE 9 - 11 which does not include Promises +if (!window.Promise) { + window.Promise = es6PromisePolyfill.Polyfill; +} - /** - * Fired when a pointer device (usually a mouse) is moved while over the display object - * - * @event PIXI.interaction.InteractionManager#mousemove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +// References: +if (!Object.assign) { + Object.assign = objectAssign; +} - /** - * Fired when a pointer device (usually a mouse) is moved onto the display object - * - * @event PIXI.interaction.InteractionManager#mouseover - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` +var ONE_FRAME_TIME = 16; +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} +// performance.now +if (!(window.performance && window.performance.now)) { + var startTime_1 = Date.now(); + if (!window.performance) { + window.performance = {}; + } + window.performance.now = function () { return Date.now() - startTime_1; }; +} +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; +for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { + var p = vendors[x]; + window.requestAnimationFrame = window[p + "RequestAnimationFrame"]; + window.cancelAnimationFrame = window[p + "CancelAnimationFrame"] + || window[p + "CancelRequestAnimationFrame"]; +} +if (!window.requestAnimationFrame) { + window.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + "is not a function"); + } + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + if (delay < 0) { + delay = 0; + } + lastTime = currentTime; + return window.setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} +if (!window.cancelAnimationFrame) { + window.cancelAnimationFrame = function (id) { return clearTimeout(id); }; +} - /** - * Fired when a pointer device (usually a mouse) is moved off the display object - * - * @event PIXI.interaction.InteractionManager#mouseout - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + if (x === 0 || isNaN(x)) { + return x; + } + return x > 0 ? 1 : -1; + }; +} - /** - * Fired when a pointer device button is pressed on the display object. - * - * @event PIXI.interaction.InteractionManager#pointerdown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger +if (!Number.isInteger) { + Number.isInteger = function numberIsInteger(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; + }; +} - /** - * Fired when a pointer device button is released over the display object. - * Not always fired when some buttons are held down while others are released. In those cases, - * use [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown} and - * [mouseup]{@link PIXI.interaction.InteractionManager#event:mouseup} instead. - * - * @event PIXI.interaction.InteractionManager#pointerup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} +if (!window.Float32Array) { + window.Float32Array = Array; +} +if (!window.Uint32Array) { + window.Uint32Array = Array; +} +if (!window.Uint16Array) { + window.Uint16Array = Array; +} +if (!window.Uint8Array) { + window.Uint8Array = Array; +} +if (!window.Int32Array) { + window.Int32Array = Array; +} - /** - * Fired when the operating system cancels a pointer event - * - * @event PIXI.interaction.InteractionManager#pointercancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is pressed and released on the display object. - * - * @event PIXI.interaction.InteractionManager#pointertap - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +},{"es6-promise-polyfill":40,"object-assign":46}],28:[function(require,module,exports){ +/*! + * @pixi/prepare - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/prepare is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - /** - * Fired when a pointer device button is released outside the display object that initially - * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. - * - * @event PIXI.interaction.InteractionManager#pointerupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +Object.defineProperty(exports, '__esModule', { value: true }); - /** - * Fired when a pointer device is moved while over the display object - * - * @event PIXI.interaction.InteractionManager#pointermove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +var settings = require('@pixi/settings'); +var core = require('@pixi/core'); +var graphics = require('@pixi/graphics'); +var ticker = require('@pixi/ticker'); +var display = require('@pixi/display'); +var text = require('@pixi/text'); - /** - * Fired when a pointer device is moved onto the display object - * - * @event PIXI.interaction.InteractionManager#pointerover - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +settings.settings.UPLOADS_PER_FRAME = 4; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = /** @class */ (function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { /** - * Fired when a pointer device is moved off the display object - * - * @event PIXI.interaction.InteractionManager#pointerout - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * The maximum number of items that can be prepared each frame. + * @type {number} + * @private */ - + this.maxItemsPerFrame = maxItemsPerFrame; /** - * Fired when a touch point is placed on the display object. - * - * @event PIXI.interaction.InteractionManager#touchstart - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is removed from the display object. - * - * @event PIXI.interaction.InteractionManager#touchend - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when the operating system cancels a touch - * - * @event PIXI.interaction.InteractionManager#touchcancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is placed and removed from the display object. - * - * @event PIXI.interaction.InteractionManager#tap - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is removed outside of the display object that initially - * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. - * - * @event PIXI.interaction.InteractionManager#touchendoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a touch point is moved along the display object. - * - * @event PIXI.interaction.InteractionManager#touchmove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. - * object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mousedown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightdown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is released over the display - * object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed and released on - * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#click - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightclick - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button (usually a mouse left-button) is released outside the - * display object that initially registered a - * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * outside the display object that initially registered a - * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device (usually a mouse) is moved while over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mousemove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device (usually a mouse) is moved onto the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseover - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device (usually a mouse) is moved off the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseout - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is pressed on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerdown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is released over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when the operating system cancels a pointer event. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointercancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is pressed and released on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointertap - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ - - /** - * Fired when a pointer device button is released outside the display object that initially - * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerupoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * The number of items that can be prepared in the current frame. + * @type {number} + * @private */ + this.itemsLeft = 0; + } + /** + * Resets any counting properties to start fresh on a new frame. + */ + CountLimiter.prototype.beginFrame = function () { + this.itemsLeft = this.maxItemsPerFrame; + }; + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + CountLimiter.prototype.allowedToUpload = function () { + return this.itemsLeft-- > 0; + }; + return CountLimiter; +}()); +/** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findMultipleBaseTextures(item, queue) { + var result = false; + // Objects with multiple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof core.Texture) { + var baseTexture = item._textures[i].baseTexture; + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + return result; +} +/** + * Built-in hook to find BaseTextures from Texture. + * + * @private + * @param {PIXI.Texture} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTexture(item, queue) { + if (item.baseTexture instanceof core.BaseTexture) { + var texture = item.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; +} +/** + * Built-in hook to find textures from objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findTexture(item, queue) { + if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; +} +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.AbstractRenderer|PIXI.BasePrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function drawText(_helper, item) { + if (item instanceof text.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + return true; + } + return false; +} +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.AbstractRenderer|PIXI.BasePrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(_helper, item) { + if (item instanceof text.TextStyle) { + var font = item.toFontString(); + text.TextMetrics.measureFont(font); + return true; + } + return false; +} +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof text.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; +} +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof text.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + return true; + } + return false; +} +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * BasePrepare handles basic queuing functionality and is extended by + * {@link PIXI.Prepare} and {@link PIXI.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @example + * // Create a sprite + * const sprite = PIXI.Sprite.from('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * + * @abstract + * @class + * @memberof PIXI + */ +var BasePrepare = /** @class */ (function () { + /** + * @param {PIXI.AbstractRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; /** - * Fired when a pointer device is moved while over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointermove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.CountLimiter|PIXI.TimeLimiter} */ - + this.limiter = new CountLimiter(settings.settings.UPLOADS_PER_FRAME); /** - * Fired when a pointer device is moved onto the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerover - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * Reference to the renderer. + * @type {PIXI.AbstractRenderer} + * @protected */ - + this.renderer = renderer; /** - * Fired when a pointer device is moved off the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerout - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * The only real difference between CanvasPrepare and Prepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {object} + * @protected */ - + this.uploadHookHelper = null; /** - * Fired when a touch point is placed on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchstart - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * Collection of items to uploads at once. + * @type {Array<*>} + * @private */ - + this.queue = []; /** - * Fired when a touch point is removed from the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchend - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * Collection of additional hooks for finding assets. + * @type {Array} + * @private */ - + this.addHooks = []; /** - * Fired when the operating system cancels a touch. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchcancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * Collection of additional hooks for processing assets. + * @type {Array} + * @private */ - + this.uploadHooks = []; /** - * Fired when a touch point is placed and removed from the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#tap - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * Callback to call after completed. + * @type {Array} + * @private */ - + this.completes = []; /** - * Fired when a touch point is removed outside of the display object that initially - * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchendoutside - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * If prepare is ticking (running). + * @type {boolean} + * @private */ - + this.ticking = false; /** - * Fired when a touch point is moved along the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchmove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event + * 'bound' call for prepareItems(). + * @type {Function} + * @private */ - - this.setTargetElement(this.renderer.view, this.renderer.resolution); + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); } - - if ( EventEmitter ) InteractionManager.__proto__ = EventEmitter; - InteractionManager.prototype = Object.create( EventEmitter && EventEmitter.prototype ); - InteractionManager.prototype.constructor = InteractionManager; - /** - * Hit tests a point against the display tree, returning the first interactive object that is hit. + * Upload all the textures and graphics to the GPU. * - * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. - * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults - * to the last rendered root of the associated renderer. - * @return {PIXI.DisplayObject} The hit display object, if any. + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed */ - InteractionManager.prototype.hitTest = function hitTest (globalPoint, root) - { - // clear the target for our hit test - hitTestEvent.target = null; - // assign the global point - hitTestEvent.data.global = globalPoint; - // ensure safety of the root - if (!root) - { - root = this.renderer._lastObjectRendered; + BasePrepare.prototype.upload = function (item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + if (!this.ticking) { + this.ticking = true; + ticker.Ticker.system.addOnce(this.tick, this, ticker.UPDATE_PRIORITY.UTILITY); + } + } + else if (done) { + done(); } - // run the hit test - this.processInteractive(hitTestEvent, root, null, true); - // return our found object - it'll be null if we didn't hit anything - - return hitTestEvent.target; }; - /** - * Sets the DOM element which will receive mouse/touch events. This is useful for when you have - * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate - * another DOM element to receive those events. + * Handle tick update * - * @param {HTMLElement} element - the DOM element which will receive mouse and touch events. - * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + * @private */ - InteractionManager.prototype.setTargetElement = function setTargetElement (element, resolution) - { - if ( resolution === void 0 ) resolution = 1; - - this.removeEvents(); - - this.interactionDOMElement = element; - - this.resolution = resolution; - - this.addEvents(); + BasePrepare.prototype.tick = function () { + setTimeout(this.delayedTick, 0); }; - /** - * Registers all the DOM events + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. * * @private */ - InteractionManager.prototype.addEvents = function addEvents () - { - if (!this.interactionDOMElement) - { - return; - } - - ticker.Ticker.system.add(this.update, this, ticker.UPDATE_PRIORITY.INTERACTION); - - if (window.navigator.msPointerEnabled) - { - this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; - this.interactionDOMElement.style['-ms-touch-action'] = 'none'; - } - else if (this.supportsPointerEvents) - { - this.interactionDOMElement.style['touch-action'] = 'none'; - } - - /** - * These events are added first, so that if pointer events are normalized, they are fired - * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd - */ - if (this.supportsPointerEvents) - { - window.document.addEventListener('pointermove', this.onPointerMove, true); - this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); - // pointerout is fired in addition to pointerup (for touch events) and pointercancel - // we already handle those, so for the purposes of what we do in onPointerOut, we only - // care about the pointerleave event - this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); - this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); - window.addEventListener('pointercancel', this.onPointerCancel, true); - window.addEventListener('pointerup', this.onPointerUp, true); + BasePrepare.prototype.prepareItems = function () { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + if (!uploaded) { + this.queue.shift(); + } } - else - { - window.document.addEventListener('mousemove', this.onPointerMove, true); - this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); - this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); - this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); - window.addEventListener('mouseup', this.onPointerUp, true); + // We're finished + if (!this.queue.length) { + this.ticking = false; + var completes = this.completes.slice(0); + this.completes.length = 0; + for (var i = 0, len = completes.length; i < len; i++) { + completes[i](); + } } - - // always look directly for touch events so that we can provide original data - // In a future version we should change this to being just a fallback and rely solely on - // PointerEvents whenever available - if (this.supportsTouchEvents) - { - this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); - this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); - this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); - this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + else { + // if we are not finished, on the next rAF do this again + ticker.Ticker.system.addOnce(this.tick, this, ticker.UPDATE_PRIORITY.UTILITY); } - - this.eventsAdded = true; }; - /** - * Removes all the DOM events that were previously registered + * Adds hooks for finding items. * - * @private + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @return {this} Instance of plugin for chaining. */ - InteractionManager.prototype.removeEvents = function removeEvents () - { - if (!this.interactionDOMElement) - { - return; + BasePrepare.prototype.registerFindHook = function (addHook) { + if (addHook) { + this.addHooks.push(addHook); } - - ticker.Ticker.system.remove(this.update, this); - - if (window.navigator.msPointerEnabled) - { - this.interactionDOMElement.style['-ms-content-zooming'] = ''; - this.interactionDOMElement.style['-ms-touch-action'] = ''; - } - else if (this.supportsPointerEvents) - { - this.interactionDOMElement.style['touch-action'] = ''; - } - - if (this.supportsPointerEvents) - { - window.document.removeEventListener('pointermove', this.onPointerMove, true); - this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); - this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); - this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); - window.removeEventListener('pointercancel', this.onPointerCancel, true); - window.removeEventListener('pointerup', this.onPointerUp, true); + return this; + }; + /** + * Adds hooks for uploading items. + * + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {this} Instance of plugin for chaining. + */ + BasePrepare.prototype.registerUploadHook = function (uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); } - else - { - window.document.removeEventListener('mousemove', this.onPointerMove, true); - this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); - this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); - this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); - window.removeEventListener('mouseup', this.onPointerUp, true); + return this; + }; + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {this} Instance of plugin for chaining. + */ + BasePrepare.prototype.add = function (item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } } - - if (this.supportsTouchEvents) - { - this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); - this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); - this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); - this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + // Get children recursively + if (item instanceof display.Container) { + for (var i = item.children.length - 1; i >= 0; i--) { + this.add(item.children[i]); + } } - - this.interactionDOMElement = null; - - this.eventsAdded = false; + return this; }; - /** - * Updates the state of interactive objects. - * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}. + * Destroys the plugin, don't use after this. * - * @param {number} deltaTime - time delta since last tick */ - InteractionManager.prototype.update = function update (deltaTime) - { - this._deltaTime += deltaTime; - - if (this._deltaTime < this.interactionFrequency) - { - return; - } - - this._deltaTime = 0; - - if (!this.interactionDOMElement) - { - return; + BasePrepare.prototype.destroy = function () { + if (this.ticking) { + ticker.Ticker.system.remove(this.tick, this); } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + return BasePrepare; +}()); - // if the user move the mouse this check has already been done using the mouse move! - if (this.didMove) - { - this.didMove = false; - - return; +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.Renderer} renderer - instance of the webgl renderer + * @param {PIXI.BaseTexture} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.texture.bind(item); + } + return true; + } + return false; +} +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.Renderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (!(item instanceof graphics.Graphics)) { + return false; + } + var geometry = item.geometry; + // update dirty graphics to get batches + item.finishPoly(); + geometry.updateBatches(); + var batches = geometry.batches; + // upload all textures found in styles + for (var i = 0; i < batches.length; i++) { + var texture = batches[i].style.texture; + if (texture) { + uploadBaseTextures(renderer, texture.baseTexture); } + } + // if its not batchable - update vao for particular shader + if (!geometry.batchable) { + renderer.geometry.bind(geometry, item._resolveDirectShader(renderer)); + } + return true; +} +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof graphics.Graphics) { + queue.push(item); + return true; + } + return false; +} +/** + * The prepare plugin provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for + * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed. + * + * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. + * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. + * @example + * // Create a new application + * const app = new PIXI.Application(); + * document.body.appendChild(app.view); + * + * // Don't start rendering right away + * app.stop(); + * + * // create a display object + * const rect = new PIXI.Graphics() + * .beginFill(0x00ff00) + * .drawRect(40, 40, 200, 200); + * + * // Add to the stage + * app.stage.addChild(rect); + * + * // Don't start rendering until the graphic is uploaded to the GPU + * app.renderer.plugins.prepare.upload(app.stage, () => { + * app.start(); + * }); + * + * @class + * @extends PIXI.BasePrepare + * @memberof PIXI + */ +var Prepare = /** @class */ (function (_super) { + __extends(Prepare, _super); + /** + * @param {PIXI.Renderer} renderer - A reference to the current renderer + */ + function Prepare(renderer) { + var _this = _super.call(this, renderer) || this; + _this.uploadHookHelper = _this.renderer; + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + return Prepare; +}(BasePrepare)); - this.cursor = null; +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = /** @class */ (function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @type {number} + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + /** + * Resets any counting properties to start fresh on a new frame. + */ + TimeLimiter.prototype.beginFrame = function () { + this.frameStart = Date.now(); + }; + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + TimeLimiter.prototype.allowedToUpload = function () { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + return TimeLimiter; +}()); - // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, - // but there was a scenario of a display object moving under a static mouse cursor. - // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function - for (var k in this.activeInteractionData) - { - // eslint-disable-next-line no-prototype-builtins - if (this.activeInteractionData.hasOwnProperty(k)) - { - var interactionData = this.activeInteractionData[k]; +exports.BasePrepare = BasePrepare; +exports.CountLimiter = CountLimiter; +exports.Prepare = Prepare; +exports.TimeLimiter = TimeLimiter; - if (interactionData.originalEvent && interactionData.pointerType !== 'touch') - { - var interactionEvent = this.configureInteractionEventForDOMEvent( - this.eventData, - interactionData.originalEvent, - interactionData - ); - - this.processInteractive( - interactionEvent, - this.renderer._lastObjectRendered, - this.processPointerOverOut, - true - ); - } - } - } - this.setCursorMode(this.cursor); - }; +},{"@pixi/core":8,"@pixi/display":9,"@pixi/graphics":17,"@pixi/settings":30,"@pixi/text":36,"@pixi/ticker":37}],29:[function(require,module,exports){ +/*! + * @pixi/runner - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/runner is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); +/** + * A Runner is a highly performant and simple alternative to signals. Best used in situations + * where events are dispatched to many objects at high frequency (say every frame!) + * + * + * like a signal.. + * ``` + * import { Runner } from '@pixi/runner'; + * + * const myObject = { + * loaded: new Runner('loaded') + * } + * + * const listener = { + * loaded: function(){ + * // thin + * } + * } + * + * myObject.update.add(listener); + * + * myObject.loaded.emit(); + * ``` + * + * Or for handling calling the same function on many items + * ``` + * import { Runner } from '@pixi/runner'; + * + * const myGame = { + * update: new Runner('update') + * } + * + * const gameObject = { + * update: function(time){ + * // update my gamey state + * } + * } + * + * myGame.update.add(gameObject1); + * + * myGame.update.emit(time); + * ``` + * @class + * @memberof PIXI + */ +var Runner = /** @class */ (function () { /** - * Sets the current cursor mode, handling any callbacks or CSS style changes. - * - * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + * @param {string} name - the function name that will be executed on the listeners added to this Runner. */ - InteractionManager.prototype.setCursorMode = function setCursorMode (mode) - { - mode = mode || 'default'; - // if the mode didn't actually change, bail early - if (this.currentCursorMode === mode) - { - return; + function Runner(name) { + this.items = []; + this._name = name; + this._aliasCount = 0; + } + /** + * Dispatch/Broadcast Runner to all listeners added to the queue. + * @param {...any} params - optional parameters to pass to each listener + * @return {PIXI.Runner} + */ + Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) { + if (arguments.length > 8) { + throw new Error('max arguments reached'); } - this.currentCursorMode = mode; - var style = this.cursorStyles[mode]; - - // only do things if there is a cursor style for it - if (style) - { - switch (typeof style) - { - case 'string': - // string styles are handled as cursor CSS - this.interactionDOMElement.style.cursor = style; - break; - case 'function': - // functions are just called, and passed the cursor mode - style(mode); - break; - case 'object': - // if it is an object, assume that it is a dictionary of CSS styles, - // apply it to the interactionDOMElement - Object.assign(this.interactionDOMElement.style, style); - break; - } + var _a = this, name = _a.name, items = _a.items; + this._aliasCount++; + for (var i = 0, len = items.length; i < len; i++) { + items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); } - else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) - { - // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry - // for the mode, then assume that the dev wants it to be CSS for the cursor. - this.interactionDOMElement.style.cursor = mode; + if (items === this.items) { + this._aliasCount--; + } + return this; + }; + Runner.prototype.ensureNonAliasedItems = function () { + if (this._aliasCount > 0 && this.items.length > 1) { + this._aliasCount = 0; + this.items = this.items.slice(0); } }; - /** - * Dispatches an event on the display object that was interacted with + * Add a listener to the Runner * - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the display object in question - * @param {string} eventString - the name of the event (e.g, mousedown) - * @param {object} eventData - the event data object - * @private + * Runners do not need to have scope or functions passed to them. + * All that is required is to pass the listening object and ensure that it has contains a function that has the same name + * as the name provided to the Runner when it was created. + * + * Eg A listener passed to this Runner will require a 'complete' function. + * + * ``` + * import { Runner } from '@pixi/runner'; + * + * const complete = new Runner('complete'); + * ``` + * + * The scope used will be the object itself. + * + * @param {any} item - The object that will be listening. + * @return {PIXI.Runner} */ - InteractionManager.prototype.dispatchEvent = function dispatchEvent (displayObject, eventString, eventData) - { - // Even if the event was stopped, at least dispatch any remaining events - // for the same display object. - if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) - { - eventData.currentTarget = displayObject; - eventData.type = eventString; - - displayObject.emit(eventString, eventData); - - if (displayObject[eventString]) - { - displayObject[eventString](eventData); - } + Runner.prototype.add = function (item) { + if (item[this._name]) { + this.ensureNonAliasedItems(); + this.remove(item); + this.items.push(item); } + return this; }; - /** - * Puts a event on a queue to be dispatched later. This is used to guarantee correct - * ordering of over/out events. - * - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the display object in question - * @param {string} eventString - the name of the event (e.g, mousedown) - * @param {object} eventData - the event data object - * @private + * Remove a single listener from the dispatch queue. + * @param {any} item - The listenr that you would like to remove. + * @return {PIXI.Runner} */ - InteractionManager.prototype.delayDispatchEvent = function delayDispatchEvent (displayObject, eventString, eventData) - { - this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData }); + Runner.prototype.remove = function (item) { + var index = this.items.indexOf(item); + if (index !== -1) { + this.ensureNonAliasedItems(); + this.items.splice(index, 1); + } + return this; }; - /** - * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The - * resulting value is stored in the point. This takes into account the fact that the DOM - * element could be scaled and positioned anywhere on the screen. - * - * @param {PIXI.Point} point - the point that the result will be stored in - * @param {number} x - the x coord of the position to map - * @param {number} y - the y coord of the position to map + * Check to see if the listener is already in the Runner + * @param {any} item - The listener that you would like to check. */ - InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint (point, x, y) - { - var rect; - - // IE 11 fix - if (!this.interactionDOMElement.parentElement) - { - rect = { x: 0, y: 0, width: 0, height: 0 }; - } - else - { - rect = this.interactionDOMElement.getBoundingClientRect(); - } - - var resolutionMultiplier = 1.0 / this.resolution; - - point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier; - point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier; + Runner.prototype.contains = function (item) { + return this.items.indexOf(item) !== -1; }; - /** - * This function is provides a neat way of crawling through the scene graph and running a - * specified function on all interactive objects it finds. It will also take care of hit - * testing the interactive objects and passes the hit across in the function. - * - * @protected - * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that - * is tested for collision - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param {Function} [func] - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param {boolean} [hitTest] - indicates whether we want to calculate hits - * or just iterate through all interactive objects + * Remove all listeners from the Runner + * @return {PIXI.Runner} */ - InteractionManager.prototype.processInteractive = function processInteractive (interactionEvent, displayObject, func, hitTest) - { - var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest); - - var delayedEvents = this.delayedEvents; - - if (!delayedEvents.length) - { - return hit; - } - // Reset the propagation hint, because we start deeper in the tree again. - interactionEvent.stopPropagationHint = false; - - var delayedLen = delayedEvents.length; - - this.delayedEvents = []; - - for (var i = 0; i < delayedLen; i++) - { - var ref = delayedEvents[i]; - var displayObject$1 = ref.displayObject; - var eventString = ref.eventString; - var eventData = ref.eventData; - - // When we reach the object we wanted to stop propagating at, - // set the propagation hint. - if (eventData.stopsPropagatingAt === displayObject$1) - { - eventData.stopPropagationHint = true; - } - - this.dispatchEvent(displayObject$1, eventString, eventData); - } - - return hit; + Runner.prototype.removeAll = function () { + this.ensureNonAliasedItems(); + this.items.length = 0; + return this; }; - /** - * Is called when the pointer button is pressed down on the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + * Remove all references, don't use after this. */ - InteractionManager.prototype.onPointerDown = function onPointerDown (originalEvent) - { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') { return; } - - var events = this.normalizeToPointerData(originalEvent); - + Runner.prototype.destroy = function () { + this.removeAll(); + this.items = null; + this._name = null; + }; + Object.defineProperty(Runner.prototype, "empty", { /** - * No need to prevent default on natural pointer events, as there are no side effects - * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, - * so still need to be prevented. + * `true` if there are no this Runner contains no listeners + * + * @member {boolean} + * @readonly */ + get: function () { + return this.items.length === 0; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Runner.prototype, "name", { + /** + * The name of the runner. + * + * @member {string} + * @readonly + */ + get: function () { + return this._name; + }, + enumerable: false, + configurable: true + }); + return Runner; +}()); +Object.defineProperties(Runner.prototype, { + /** + * Alias for `emit` + * @memberof PIXI.Runner# + * @method dispatch + * @see PIXI.Runner#emit + */ + dispatch: { value: Runner.prototype.emit }, + /** + * Alias for `emit` + * @memberof PIXI.Runner# + * @method run + * @see PIXI.Runner#emit + */ + run: { value: Runner.prototype.emit }, +}); - // Guaranteed that there will be at least one event in events, and all events must have the same pointer type - - if (this.autoPreventDefault && events[0].isNormalized) - { - var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent); - - if (cancelable) - { - originalEvent.preventDefault(); - } - } - - var eventLen = events.length; +exports.Runner = Runner; - for (var i = 0; i < eventLen; i++) - { - var event = events[i]; - var interactionData = this.getInteractionDataForPointerId(event); +},{}],30:[function(require,module,exports){ +/*! + * @pixi/settings - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/settings is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); +Object.defineProperty(exports, '__esModule', { value: true }); - interactionEvent.data.originalEvent = originalEvent; +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); +var isMobileCall = _interopDefault(require('ismobilejs')); - this.emit('pointerdown', interactionEvent); - if (event.pointerType === 'touch') - { - this.emit('touchstart', interactionEvent); - } - // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event - else if (event.pointerType === 'mouse' || event.pointerType === 'pen') - { - var isRightButton = event.button === 2; +// The ESM/CJS versions of ismobilejs only +var isMobile = isMobileCall(window.navigator); - this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); +/** + * The maximum recommended texture units to use. + * In theory the bigger the better, and for desktop we'll use as many as we can. + * But some mobile devices slow down if there is to many branches in the shader. + * So in practice there seems to be a sweet spot size that varies depending on the device. + * + * In v4, all mobile devices were limited to 4 texture units because for this. + * In v5, we allow all texture units to be used on modern Apple or Android devices. + * + * @private + * @param {number} max + * @returns {number} + */ +function maxRecommendedTextures(max) { + var allowMax = true; + if (isMobile.tablet || isMobile.phone) { + if (isMobile.apple.device) { + var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below iOS 11, which will be older hardware + if (majorVersion < 11) { + allowMax = false; + } } } - }; - - /** - * Processes the result of the pointer down check and dispatches the event if need be - * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object - */ - InteractionManager.prototype.processPointerDown = function processPointerDown (interactionEvent, displayObject, hit) - { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - - if (hit) - { - if (!displayObject.trackedPointers[id]) - { - displayObject.trackedPointers[id] = new InteractionTrackingData(id); + if (isMobile.android.device) { + var match = (navigator.userAgent).match(/Android\s([0-9.]*)/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below Android 7 (Nougat), which will be older hardware + if (majorVersion < 7) { + allowMax = false; + } } - this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + } + } + return allowMax ? max : 4; +} - if (data.pointerType === 'touch') - { - this.dispatchEvent(displayObject, 'touchstart', interactionEvent); - } - else if (data.pointerType === 'mouse' || data.pointerType === 'pen') - { - var isRightButton = data.button === 2; - - if (isRightButton) - { - displayObject.trackedPointers[id].rightDown = true; - } - else - { - displayObject.trackedPointers[id].leftDown = true; - } - - this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); - } - } - }; +/** + * Uploading the same buffer multiple times in a single frame can cause performance issues. + * Apparent on iOS so only check for that at the moment + * This check may become more complex if this issue pops up elsewhere. + * + * @private + * @returns {boolean} + */ +function canUploadSameBuffer() { + return !isMobile.apple.device; +} +/** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float precision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio; + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ +var settings = { /** - * Is called when the pointer button is released on the renderer element + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released - * @param {boolean} cancelled - true if the pointer is cancelled - * @param {Function} func - Function passed to {@link processInteractive} + * @static + * @name MIPMAP_TEXTURES + * @memberof PIXI.settings + * @type {PIXI.MIPMAP_MODES} + * @default PIXI.MIPMAP_MODES.POW2 */ - InteractionManager.prototype.onPointerComplete = function onPointerComplete (originalEvent, cancelled, func) - { - var events = this.normalizeToPointerData(originalEvent); - - var eventLen = events.length; - - // if the event wasn't targeting our canvas, then consider it to be pointerupoutside - // in all cases (unless it was a pointercancel) - var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; - - for (var i = 0; i < eventLen; i++) - { - var event = events[i]; - - var interactionData = this.getInteractionDataForPointerId(event); - - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - - interactionEvent.data.originalEvent = originalEvent; - - // perform hit testing for events targeting our canvas or cancel events - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); - - this.emit(cancelled ? 'pointercancel' : ("pointerup" + eventAppend), interactionEvent); - - if (event.pointerType === 'mouse' || event.pointerType === 'pen') - { - var isRightButton = event.button === 2; - - this.emit(isRightButton ? ("rightup" + eventAppend) : ("mouseup" + eventAppend), interactionEvent); - } - else if (event.pointerType === 'touch') - { - this.emit(cancelled ? 'touchcancel' : ("touchend" + eventAppend), interactionEvent); - this.releaseInteractionDataForPointerId(event.pointerId, interactionData); - } - } - }; - + MIPMAP_TEXTURES: 1, /** - * Is called when the pointer button is cancelled + * Default anisotropic filtering level of textures. + * Usually from 0 to 16 * - * @private - * @param {PointerEvent} event - The DOM event of a pointer button being released + * @static + * @name ANISOTROPIC_LEVEL + * @memberof PIXI.settings + * @type {number} + * @default 0 */ - InteractionManager.prototype.onPointerCancel = function onPointerCancel (event) - { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && event.pointerType === 'touch') { return; } - - this.onPointerComplete(event, true, this.processPointerCancel); - }; - + ANISOTROPIC_LEVEL: 0, /** - * Processes the result of the pointer cancel check and dispatches the event if need be + * Default resolution / device pixel ratio of the renderer. * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested + * @static + * @name RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 */ - InteractionManager.prototype.processPointerCancel = function processPointerCancel (interactionEvent, displayObject) - { - var data = interactionEvent.data; - - var id = interactionEvent.data.identifier; - - if (displayObject.trackedPointers[id] !== undefined) - { - delete displayObject.trackedPointers[id]; - this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); - - if (data.pointerType === 'touch') - { - this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); - } - } - }; - + RESOLUTION: 1, /** - * Is called when the pointer button is released on the renderer element + * Default filter resolution. * - * @private - * @param {PointerEvent} event - The DOM event of a pointer button being released + * @static + * @name FILTER_RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 */ - InteractionManager.prototype.onPointerUp = function onPointerUp (event) - { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && event.pointerType === 'touch') { return; } - - this.onPointerComplete(event, false, this.processPointerUp); - }; - + FILTER_RESOLUTION: 1, /** - * Processes the result of the pointer up check and dispatches the event if need be + * The maximum textures that this device supports. * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object + * @static + * @name SPRITE_MAX_TEXTURES + * @memberof PIXI.settings + * @type {number} + * @default 32 */ - InteractionManager.prototype.processPointerUp = function processPointerUp (interactionEvent, displayObject, hit) - { - var data = interactionEvent.data; - - var id = interactionEvent.data.identifier; - - var trackingData = displayObject.trackedPointers[id]; - - var isTouch = data.pointerType === 'touch'; - - var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); - // need to track mouse down status in the mouse block so that we can emit - // event in a later block - var isMouseTap = false; - - // Mouse only - if (isMouse) - { - var isRightButton = data.button === 2; - - var flags = InteractionTrackingData.FLAGS; - - var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; - - var isDown = trackingData !== undefined && (trackingData.flags & test); - - if (hit) - { - this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); - - if (isDown) - { - this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); - // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap - isMouseTap = true; - } - } - else if (isDown) - { - this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); - } - // update the down state of the tracking data - if (trackingData) - { - if (isRightButton) - { - trackingData.rightDown = false; - } - else - { - trackingData.leftDown = false; - } - } - } - - // Pointers and Touches, and Mouse - if (hit) - { - this.dispatchEvent(displayObject, 'pointerup', interactionEvent); - if (isTouch) { this.dispatchEvent(displayObject, 'touchend', interactionEvent); } - - if (trackingData) - { - // emit pointertap if not a mouse, or if the mouse block decided it was a tap - if (!isMouse || isMouseTap) - { - this.dispatchEvent(displayObject, 'pointertap', interactionEvent); - } - if (isTouch) - { - this.dispatchEvent(displayObject, 'tap', interactionEvent); - // touches are no longer over (if they ever were) when we get the touchend - // so we should ensure that we don't keep pretending that they are - trackingData.over = false; - } - } - } - else if (trackingData) - { - this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); - if (isTouch) { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); } - } - // Only remove the tracking data if there is no over/down state still associated with it - if (trackingData && trackingData.none) - { - delete displayObject.trackedPointers[id]; - } - }; - + SPRITE_MAX_TEXTURES: maxRecommendedTextures(32), + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 /** - * Is called when the pointer moves across the renderer element + * The default sprite batch size. * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + * The default aims to balance desktop and mobile devices. + * + * @static + * @name SPRITE_BATCH_SIZE + * @memberof PIXI.settings + * @type {number} + * @default 4096 */ - InteractionManager.prototype.onPointerMove = function onPointerMove (originalEvent) - { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') { return; } - - var events = this.normalizeToPointerData(originalEvent); - - if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') - { - this.didMove = true; - - this.cursor = null; - } - - var eventLen = events.length; - - for (var i = 0; i < eventLen; i++) - { - var event = events[i]; - - var interactionData = this.getInteractionDataForPointerId(event); - - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - - interactionEvent.data.originalEvent = originalEvent; - - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, true); - - this.emit('pointermove', interactionEvent); - if (event.pointerType === 'touch') { this.emit('touchmove', interactionEvent); } - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { this.emit('mousemove', interactionEvent); } - } - - if (events[0].pointerType === 'mouse') - { - this.setCursorMode(this.cursor); - - // TODO BUG for parents interactive object (border order issue) - } - }; - + SPRITE_BATCH_SIZE: 4096, /** - * Processes the result of the pointer move check and dispatches the event if need be + * The default render options if none are supplied to {@link PIXI.Renderer} + * or {@link PIXI.CanvasRenderer}. * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object + * @static + * @name RENDER_OPTIONS + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} autoDensity=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {number} width=800 + * @property {number} height=600 + * @property {boolean} legacy=false */ - InteractionManager.prototype.processPointerMove = function processPointerMove (interactionEvent, displayObject, hit) - { - var data = interactionEvent.data; - - var isTouch = data.pointerType === 'touch'; - - var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); - - if (isMouse) - { - this.processPointerOverOut(interactionEvent, displayObject, hit); - } - - if (!this.moveWhenInside || hit) - { - this.dispatchEvent(displayObject, 'pointermove', interactionEvent); - if (isTouch) { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); } - if (isMouse) { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); } - } - }; - + RENDER_OPTIONS: { + view: null, + antialias: false, + autoDensity: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + width: 800, + height: 600, + legacy: false, + }, /** - * Is called when the pointer is moved out of the renderer element + * Default Garbage Collection mode. * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + * @static + * @name GC_MODE + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO */ - InteractionManager.prototype.onPointerOut = function onPointerOut (originalEvent) - { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') { return; } - - var events = this.normalizeToPointerData(originalEvent); - - // Only mouse and pointer can call onPointerOut, so events will always be length 1 - var event = events[0]; - - if (event.pointerType === 'mouse') - { - this.mouseOverRenderer = false; - this.setCursorMode(null); - } - - var interactionData = this.getInteractionDataForPointerId(event); - - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - - interactionEvent.data.originalEvent = event; - - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); - - this.emit('pointerout', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') - { - this.emit('mouseout', interactionEvent); - } - else - { - // we can get touchleave events after touchend, so we want to make sure we don't - // introduce memory leaks - this.releaseInteractionDataForPointerId(interactionData.identifier); - } - }; - + GC_MODE: 0, /** - * Processes the result of the pointer over/out check and dispatches the event if need be + * Default Garbage Collection max idle. * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object + * @static + * @name GC_MAX_IDLE + * @memberof PIXI.settings + * @type {number} + * @default 3600 */ - InteractionManager.prototype.processPointerOverOut = function processPointerOverOut (interactionEvent, displayObject, hit) - { - var data = interactionEvent.data; - - var id = interactionEvent.data.identifier; - - var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); - - var trackingData = displayObject.trackedPointers[id]; - - // if we just moused over the display object, then we need to track that state - if (hit && !trackingData) - { - trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id); - } - - if (trackingData === undefined) { return; } - - if (hit && this.mouseOverRenderer) - { - if (!trackingData.over) - { - trackingData.over = true; - this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent); - if (isMouse) - { - this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent); - } - } - - // only change the cursor if it has not already been changed (by something deeper in the - // display tree) - if (isMouse && this.cursor === null) - { - this.cursor = displayObject.cursor; - } - } - else if (trackingData.over) - { - trackingData.over = false; - this.dispatchEvent(displayObject, 'pointerout', this.eventData); - if (isMouse) - { - this.dispatchEvent(displayObject, 'mouseout', interactionEvent); - } - // if there is no mouse down information for the pointer, then it is safe to delete - if (trackingData.none) - { - delete displayObject.trackedPointers[id]; - } - } - }; - + GC_MAX_IDLE: 60 * 60, /** - * Is called when the pointer is moved into the renderer element + * Default Garbage Collection maximum check count. * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + * @static + * @name GC_MAX_CHECK_COUNT + * @memberof PIXI.settings + * @type {number} + * @default 600 */ - InteractionManager.prototype.onPointerOver = function onPointerOver (originalEvent) - { - var events = this.normalizeToPointerData(originalEvent); - - // Only mouse and pointer can call onPointerOver, so events will always be length 1 - var event = events[0]; - - var interactionData = this.getInteractionDataForPointerId(event); - - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - - interactionEvent.data.originalEvent = event; - - if (event.pointerType === 'mouse') - { - this.mouseOverRenderer = true; - } - - this.emit('pointerover', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') - { - this.emit('mouseover', interactionEvent); - } - }; - + GC_MAX_CHECK_COUNT: 60 * 10, /** - * Get InteractionData for a given pointerId. Store that data as well + * Default wrap modes that are supported by pixi. * - * @private - * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData - * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier + * @static + * @name WRAP_MODE + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP */ - InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId (event) - { - var pointerId = event.pointerId; - - var interactionData; - - if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') - { - interactionData = this.mouse; - } - else if (this.activeInteractionData[pointerId]) - { - interactionData = this.activeInteractionData[pointerId]; - } - else - { - interactionData = this.interactionDataPool.pop() || new InteractionData(); - interactionData.identifier = pointerId; - this.activeInteractionData[pointerId] = interactionData; - } - // copy properties from the event, so that we can make sure that touch/pointer specific - // data is available - interactionData.copyEvent(event); - - return interactionData; - }; - + WRAP_MODE: 33071, /** - * Return unused InteractionData to the pool, for a given pointerId + * Default scale mode for textures. * - * @private - * @param {number} pointerId - Identifier from a pointer event + * @static + * @name SCALE_MODE + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR */ - InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId (pointerId) - { - var interactionData = this.activeInteractionData[pointerId]; - - if (interactionData) - { - delete this.activeInteractionData[pointerId]; - interactionData.reset(); - this.interactionDataPool.push(interactionData); - } - }; - + SCALE_MODE: 1, /** - * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * Default specify float precision in vertex shader. * - * @private - * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured - * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent - * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired - * with the InteractionEvent - * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in - */ - InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent (interactionEvent, pointerEvent, interactionData) - { - interactionEvent.data = interactionData; - - this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); - - // Not really sure why this is happening, but it's how a previous version handled things - if (pointerEvent.pointerType === 'touch') - { - pointerEvent.globalX = interactionData.global.x; - pointerEvent.globalY = interactionData.global.y; - } - - interactionData.originalEvent = pointerEvent; - interactionEvent.reset(); - - return interactionEvent; - }; - + * @static + * @name PRECISION_VERTEX + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', /** - * Ensures that the original event object contains all data that a regular pointer event would have + * Default specify float precision in fragment shader. + * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 * - * @private - * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event - * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer - * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + * @static + * @name PRECISION_FRAGMENT + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM */ - InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData (event) - { - var normalizedEvents = []; - - if (this.supportsTouchEvents && event instanceof TouchEvent) - { - for (var i = 0, li = event.changedTouches.length; i < li; i++) - { - var touch = event.changedTouches[i]; - - if (typeof touch.button === 'undefined') { touch.button = event.touches.length ? 1 : 0; } - if (typeof touch.buttons === 'undefined') { touch.buttons = event.touches.length ? 1 : 0; } - if (typeof touch.isPrimary === 'undefined') - { - touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; - } - if (typeof touch.width === 'undefined') { touch.width = touch.radiusX || 1; } - if (typeof touch.height === 'undefined') { touch.height = touch.radiusY || 1; } - if (typeof touch.tiltX === 'undefined') { touch.tiltX = 0; } - if (typeof touch.tiltY === 'undefined') { touch.tiltY = 0; } - if (typeof touch.pointerType === 'undefined') { touch.pointerType = 'touch'; } - if (typeof touch.pointerId === 'undefined') { touch.pointerId = touch.identifier || 0; } - if (typeof touch.pressure === 'undefined') { touch.pressure = touch.force || 0.5; } - if (typeof touch.twist === 'undefined') { touch.twist = 0; } - if (typeof touch.tangentialPressure === 'undefined') { touch.tangentialPressure = 0; } - // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven - // support, and the fill ins are not quite the same - // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top - // left is not 0,0 on the page - if (typeof touch.layerX === 'undefined') { touch.layerX = touch.offsetX = touch.clientX; } - if (typeof touch.layerY === 'undefined') { touch.layerY = touch.offsetY = touch.clientY; } - - // mark the touch as normalized, just so that we know we did it - touch.isNormalized = true; - - normalizedEvents.push(touch); - } - } - // apparently PointerEvent subclasses MouseEvent, so yay - else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) - { - if (typeof event.isPrimary === 'undefined') { event.isPrimary = true; } - if (typeof event.width === 'undefined') { event.width = 1; } - if (typeof event.height === 'undefined') { event.height = 1; } - if (typeof event.tiltX === 'undefined') { event.tiltX = 0; } - if (typeof event.tiltY === 'undefined') { event.tiltY = 0; } - if (typeof event.pointerType === 'undefined') { event.pointerType = 'mouse'; } - if (typeof event.pointerId === 'undefined') { event.pointerId = MOUSE_POINTER_ID; } - if (typeof event.pressure === 'undefined') { event.pressure = 0.5; } - if (typeof event.twist === 'undefined') { event.twist = 0; } - if (typeof event.tangentialPressure === 'undefined') { event.tangentialPressure = 0; } - - // mark the mouse event as normalized, just so that we know we did it - event.isNormalized = true; - - normalizedEvents.push(event); - } - else - { - normalizedEvents.push(event); - } - - return normalizedEvents; - }; - + PRECISION_FRAGMENT: isMobile.apple.device ? 'highp' : 'mediump', /** - * Destroys the interaction manager + * Can we upload the same buffer in a single frame? * + * @static + * @name CAN_UPLOAD_SAME_BUFFER + * @memberof PIXI.settings + * @type {boolean} */ - InteractionManager.prototype.destroy = function destroy () - { - this.removeEvents(); - - this.removeAllListeners(); - - this.renderer = null; - - this.mouse = null; - - this.eventData = null; - - this.interactionDOMElement = null; - - this.onPointerDown = null; - this.processPointerDown = null; - - this.onPointerUp = null; - this.processPointerUp = null; - - this.onPointerCancel = null; - this.processPointerCancel = null; - - this.onPointerMove = null; - this.processPointerMove = null; - - this.onPointerOut = null; - this.processPointerOverOut = null; - - this.onPointerOver = null; - - this.search = null; - }; - - return InteractionManager; -}(utils.EventEmitter)); - -/** - * This namespace contains a renderer plugin for handling mouse, pointer, and touch events. - * - * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. - * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. - * @namespace PIXI.interaction - */ + CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(), + /** + * Enables bitmap creation before image load. This feature is experimental. + * + * @static + * @name CREATE_IMAGE_BITMAP + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + CREATE_IMAGE_BITMAP: false, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + ROUND_PIXELS: false, +}; -exports.InteractionData = InteractionData; -exports.InteractionEvent = InteractionEvent; -exports.InteractionManager = InteractionManager; -exports.InteractionTrackingData = InteractionTrackingData; -exports.interactiveTarget = interactiveTarget; +exports.isMobile = isMobile; +exports.settings = settings; -},{"@pixi/display":18,"@pixi/math":29,"@pixi/ticker":46,"@pixi/utils":47}],28:[function(require,module,exports){ +},{"ismobilejs":43}],31:[function(require,module,exports){ /*! - * @pixi/loaders - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * @pixi/sprite-animated - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @pixi/loaders is licensed under the MIT License. + * @pixi/sprite-animated is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); -var resourceLoader = require('resource-loader'); -var utils = require('@pixi/utils'); var core = require('@pixi/core'); +var sprite = require('@pixi/sprite'); +var ticker = require('@pixi/ticker'); -/** - * Loader plugin for handling Texture resources. - * @class - * @memberof PIXI - * @implements PIXI.ILoaderPlugin - */ -var TextureLoader = function TextureLoader () {}; - -TextureLoader.use = function use (resource, next) -{ - // create a new texture if the data is an Image object - if (resource.data && resource.type === resourceLoader.Resource.TYPE.IMAGE) - { - resource.texture = core.Texture.fromLoader( - resource.data, - resource.url, - resource.name - ); - } - next(); -}; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} /** - * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. * * ```js - * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use. - * //or - * const loader = new PIXI.Loader(); // you can also create your own if you want - * - * const sprites = {}; + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; * - * // Chainable `add` to enqueue a resource - * loader.add('bunny', 'data/bunny.png') - * .add('spaceship', 'assets/spritesheet.json'); - * loader.add('scoreFont', 'assets/score.fnt'); + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.from(alienImages[i]); + * textureArray.push(texture); + * }; * - * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. - * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). - * loader.pre(cachingMiddleware); + * let animatedSprite = new PIXI.AnimatedSprite(textureArray); + * ``` * - * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. - * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). - * loader.use(parsingMiddleware); + * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} + * containing the animation definitions: * - * // The `load` method loads the queue of resources, and calls the passed in callback called once all - * // resources have loaded. - * loader.load((loader, resources) => { - * // resources is an object where the key is the name of the resource loaded and the value is the resource object. - * // They have a couple default properties: - * // - `url`: The URL that the resource was loaded from - * // - `error`: The error that happened when trying to load (if any) - * // - `data`: The raw data that was loaded - * // also may contain other properties based on the middleware that runs. - * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); - * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); - * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); - * }); + * ```js + * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); * - * // throughout the process multiple signals can be dispatched. - * loader.onProgress.add(() => {}); // called once per loaded/errored file - * loader.onError.add(() => {}); // called once per errored file - * loader.onLoad.add(() => {}); // called once per loaded file - * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * function setup() { + * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; + * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]); + * ... + * } * ``` * - * @see https://github.com/englercj/resource-loader - * - * @class Loader + * @class + * @extends PIXI.Sprite * @memberof PIXI - * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. - * @param {number} [concurrency=10] - The number of resources to load concurrently. */ -var Loader = /*@__PURE__*/(function (ResourceLoader) { - function Loader(baseUrl, concurrency) - { - var this$1 = this; - - ResourceLoader.call(this, baseUrl, concurrency); - utils.EventEmitter.call(this); - - for (var i = 0; i < Loader._plugins.length; ++i) - { - var plugin = Loader._plugins[i]; - var pre = plugin.pre; - var use = plugin.use; - - if (pre) - { - this.pre(pre); - } - - if (use) - { - this.use(use); - } - } - - // Compat layer, translate the new v2 signals into old v1 events. - this.onStart.add(function (l) { return this$1.emit('start', l); }); - this.onProgress.add(function (l, r) { return this$1.emit('progress', l, r); }); - this.onError.add(function (e, l, r) { return this$1.emit('error', e, l, r); }); - this.onLoad.add(function (l, r) { return this$1.emit('load', l, r); }); - this.onComplete.add(function (l, r) { return this$1.emit('complete', l, r); }); - +var AnimatedSprite = /** @class */ (function (_super) { + __extends(AnimatedSprite, _super); + /** + * @param {PIXI.Texture[]|PIXI.AnimatedSprite.FrameObject[]} textures - An array of {@link PIXI.Texture} or frame + * objects that make up the animation. + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.Ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + if (autoUpdate === void 0) { autoUpdate = true; } + var _this = _super.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture) || this; /** - * If this loader cannot be destroyed. + * @type {PIXI.Texture[]} + * @private + */ + _this._textures = null; + /** + * @type {number[]} + * @private + */ + _this._durations = null; + /** + * `true` uses PIXI.Ticker.shared to auto update animation time. + * + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate; + /** + * `true` if the instance is currently connected to PIXI.Ticker.shared to auto update animation time. + * + * @type {boolean} + * @default false + * @private + */ + _this._isConnectedToTicker = false; + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower. + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + /** + * Update anchor to [Texture's defaultAnchor]{@link PIXI.Texture#defaultAnchor} when frame changes. + * + * Useful with [sprite sheet animations]{@link PIXI.Spritesheet#animations} created with tools. + * Changing anchor for each frame allows to pin sprite origin to certain moving feature + * of the frame (e.g. left foot). + * + * Note: Enabling this will override any previously set `anchor` on each frame change. + * * @member {boolean} * @default false + */ + _this.updateAnchor = false; + /** + * User-assigned function to call when an AnimatedSprite finishes playing. + * + * @example + * animation.onComplete = function () { + * // finished! + * }; + * @member {Function} + */ + _this.onComplete = null; + /** + * User-assigned function to call when an AnimatedSprite changes which texture is being rendered. + * + * @example + * animation.onFrameChange = function () { + * // updated! + * }; + * @member {Function} + */ + _this.onFrameChange = null; + /** + * User-assigned function to call when `loop` is true, and an AnimatedSprite is played and + * loops around to start again. + * + * @example + * animation.onLoop = function () { + * // looped! + * }; + * @member {Function} + */ + _this.onLoop = null; + /** + * Elapsed time since animation has been started, used internally to display current texture. + * + * @member {number} * @private */ - this._protected = false; + _this._currentTime = 0; + _this._playing = false; + /** + * The texture index that was displayed last time + * + * @member {number} + * @private + */ + _this._previousFrame = null; + _this.textures = textures; + return _this; } - - if ( ResourceLoader ) Loader.__proto__ = ResourceLoader; - Loader.prototype = Object.create( ResourceLoader && ResourceLoader.prototype ); - Loader.prototype.constructor = Loader; - - var staticAccessors = { shared: { configurable: true } }; - /** - * Destroy the loader, removes references. + * Stops the AnimatedSprite. + * + */ + AnimatedSprite.prototype.stop = function () { + if (!this._playing) { + return; + } + this._playing = false; + if (this._autoUpdate && this._isConnectedToTicker) { + ticker.Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + }; + /** + * Plays the AnimatedSprite. + * + */ + AnimatedSprite.prototype.play = function () { + if (this._playing) { + return; + } + this._playing = true; + if (this._autoUpdate && !this._isConnectedToTicker) { + ticker.Ticker.shared.add(this.update, this, ticker.UPDATE_PRIORITY.HIGH); + this._isConnectedToTicker = true; + } + }; + /** + * Stops the AnimatedSprite and goes to a specific frame. + * + * @param {number} frameNumber - Frame index to stop at. + */ + AnimatedSprite.prototype.gotoAndStop = function (frameNumber) { + this.stop(); + var previousFrame = this.currentFrame; + this._currentTime = frameNumber; + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + /** + * Goes to a specific frame and begins playing the AnimatedSprite. + * + * @param {number} frameNumber - Frame index to start at. + */ + AnimatedSprite.prototype.gotoAndPlay = function (frameNumber) { + var previousFrame = this.currentFrame; + this._currentTime = frameNumber; + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + this.play(); + }; + /** + * Updates the object transform for rendering. + * + * @param {number} deltaTime - Time since last tick. + */ + AnimatedSprite.prototype.update = function (deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + lag += elapsed / 60 * 1000; + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + var sign = Math.sign(this.animationSpeed * deltaTime); + this._currentTime = Math.floor(this._currentTime); + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + this._currentTime += lag / this._durations[this.currentFrame]; + } + else { + this._currentTime += elapsed; + } + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + if (this.onComplete) { + this.onComplete(); + } + } + else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + if (this.onComplete) { + this.onComplete(); + } + } + else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } + else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + this.updateTexture(); + } + }; + /** + * Updates the displayed texture to match the current frame index. + * * @private */ - Loader.prototype.destroy = function destroy () - { - if (!this._protected) - { - this.removeAllListeners(); - this.reset(); + AnimatedSprite.prototype.updateTexture = function () { + var currentFrame = this.currentFrame; + if (this._previousFrame === currentFrame) { + return; + } + this._previousFrame = currentFrame; + this._texture = this._textures[currentFrame]; + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 0xFFFFFF; + this.uvs = this._texture._uvs.uvsFloat32; + if (this.updateAnchor) { + this._anchor.copyFrom(this._texture.defaultAnchor); + } + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); } }; - /** - * A premade instance of the loader that can be used to load resources. - * @name shared - * @type {PIXI.Loader} + * Stops the AnimatedSprite and destroys it. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well. + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well. + */ + AnimatedSprite.prototype.destroy = function (options) { + this.stop(); + _super.prototype.destroy.call(this, options); + this.onComplete = null; + this.onFrameChange = null; + this.onLoop = null; + }; + /** + * A short hand way of creating an AnimatedSprite from an array of frame ids. + * * @static - * @memberof PIXI.Loader + * @param {string[]} frames - The array of frames ids the AnimatedSprite will use as its texture frames. + * @return {PIXI.AnimatedSprite} The new animated sprite with the specified frames. */ - staticAccessors.shared.get = function () - { - var shared = Loader._shared; - - if (!shared) - { - shared = new Loader(); - shared._protected = true; - Loader._shared = shared; + AnimatedSprite.fromFrames = function (frames) { + var textures = []; + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.from(frames[i])); } - - return shared; + return new AnimatedSprite(textures); + }; + /** + * A short hand way of creating an AnimatedSprite from an array of image ids. + * + * @static + * @param {string[]} images - The array of image urls the AnimatedSprite will use as its texture frames. + * @return {PIXI.AnimatedSprite} The new animate sprite with the specified images as frames. + */ + AnimatedSprite.fromImages = function (images) { + var textures = []; + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.from(images[i])); + } + return new AnimatedSprite(textures); }; + Object.defineProperty(AnimatedSprite.prototype, "totalFrames", { + /** + * The total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + get: function () { + return this._textures.length; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "textures", { + /** + * The array of textures used for this AnimatedSprite. + * + * @member {PIXI.Texture[]} + */ + get: function () { + return this._textures; + }, + set: function (value) { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } + else { + this._textures = []; + this._durations = []; + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this._previousFrame = null; + this.gotoAndStop(0); + this.updateTexture(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "currentFrame", { + /** + * The AnimatedSprites current frame index. + * + * @member {number} + * @readonly + */ + get: function () { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + return currentFrame; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "playing", { + /** + * Indicates if the AnimatedSprite is currently playing. + * + * @member {boolean} + * @readonly + */ + get: function () { + return this._playing; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "autoUpdate", { + /** + * Whether to use PIXI.Ticker.shared to auto update animation time + * + * @member {boolean} + */ + get: function () { + return this._autoUpdate; + }, + set: function (value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + ticker.Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) { + ticker.Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + }, + enumerable: false, + configurable: true + }); + return AnimatedSprite; +}(sprite.Sprite)); +/** + * @memberof PIXI.AnimatedSprite + * @typedef {object} FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ - Object.defineProperties( Loader, staticAccessors ); +exports.AnimatedSprite = AnimatedSprite; - return Loader; -}(resourceLoader.Loader)); -// Copy EE3 prototype (mixin) -Object.assign(Loader.prototype, utils.EventEmitter.prototype); - -/** - * Collection of all installed `use` middleware for Loader. - * - * @static - * @member {Array} _plugins - * @memberof PIXI.Loader - * @private - */ -Loader._plugins = []; - -/** - * Adds a Loader plugin for the global shared loader and all - * new Loader instances created. - * - * @static - * @method registerPlugin - * @memberof PIXI.Loader - * @param {PIXI.ILoaderPlugin} plugin - The plugin to add - * @return {PIXI.Loader} Reference to PIXI.Loader for chaining - */ -Loader.registerPlugin = function registerPlugin(plugin) -{ - Loader._plugins.push(plugin); - - if (plugin.add) - { - plugin.add(); - } - - return Loader; -}; - -// parse any blob into more usable objects (e.g. Image) -Loader.registerPlugin({ use: resourceLoader.middleware.parsing }); - -// parse any Image objects into textures -Loader.registerPlugin(TextureLoader); - -/** - * Plugin to be installed for handling specific Loader resources. - * - * @memberof PIXI - * @typedef ILoaderPlugin - * @property {function} [add] - Function to call immediate after registering plugin. - * @property {PIXI.Loader.loaderMiddleware} [pre] - Middleware function to run before load, the - * arguments for this are `(resource, next)` - * @property {PIXI.Loader.loaderMiddleware} [use] - Middleware function to run after load, the - * arguments for this are `(resource, next)` - */ - -/** - * @memberof PIXI.Loader - * @callback loaderMiddleware - * @param {PIXI.LoaderResource} resource - * @param {function} next - */ - -/** - * @memberof PIXI.Loader# - * @member {object} onStart - */ - -/** - * @memberof PIXI.Loader# - * @member {object} onProgress - */ - -/** - * @memberof PIXI.Loader# - * @member {object} onError - */ - -/** - * @memberof PIXI.Loader# - * @member {object} onLoad - */ - -/** - * @memberof PIXI.Loader# - * @member {object} onComplete - */ - -/** - * Application plugin for supporting loader option. Installing the LoaderPlugin - * is not necessary if using **pixi.js** or **pixi.js-legacy**. - * @example - * import {AppLoaderPlugin} from '@pixi/loaders'; - * import {Application} from '@pixi/app'; - * Application.registerPlugin(AppLoaderPlugin); - * @class - * @memberof PIXI - */ -var AppLoaderPlugin = function AppLoaderPlugin () {}; - -AppLoaderPlugin.init = function init (options) -{ - options = Object.assign({ - sharedLoader: false, - }, options); - - /** - * Loader instance to help with asset loading. - * @name PIXI.Application#loader - * @type {PIXI.Loader} - * @readonly - */ - this.loader = options.sharedLoader ? Loader.shared : new Loader(); -}; - -/** - * Called when application destroyed - * @private - */ -AppLoaderPlugin.destroy = function destroy () -{ - if (this.loader) - { - this.loader.destroy(); - this.loader = null; - } -}; - -/** - * Reference to **{@link https://github.com/englercj/resource-loader - * resource-loader}**'s Resource class. - * @see http://englercj.github.io/resource-loader/Resource.html - * @class LoaderResource - * @memberof PIXI - */ -var LoaderResource = resourceLoader.Resource; - -exports.AppLoaderPlugin = AppLoaderPlugin; -exports.Loader = Loader; -exports.LoaderResource = LoaderResource; -exports.TextureLoader = TextureLoader; - - -},{"@pixi/core":17,"@pixi/utils":47,"resource-loader":58}],29:[function(require,module,exports){ +},{"@pixi/core":8,"@pixi/sprite":33,"@pixi/ticker":37}],32:[function(require,module,exports){ /*! - * @pixi/math - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * @pixi/sprite-tiling - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @pixi/math is licensed under the MIT License. + * @pixi/sprite-tiling is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); -/** - * Common interface for points. Both Point and ObservablePoint implement it - * @memberof PIXI - * @interface IPoint - */ -/** - * X coord - * @memberof PIXI.IPoint# - * @member {number} x - */ -/** - * Y coord - * @memberof PIXI.IPoint# - * @member {number} y - */ -/** - * Sets the point to a new x and y position. - * If y is omitted, both x and y will be set to x. - * - * @method set - * @memberof PIXI.IPoint# - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=x] - position of the point on the y axis - */ -/** - * Copies x and y from the given point - * @method copyFrom - * @memberof PIXI.IPoint# - * @param {PIXI.IPoint} p - The point to copy from - * @returns {this} Returns itself. - */ -/** - * Copies x and y into the given point - * @method copyTo - * @memberof PIXI.IPoint# - * @param {PIXI.IPoint} p - The point to copy. - * @returns {PIXI.IPoint} Given point with values updated - */ -/** - * Returns true if the given point is equal to this point - * - * @method equals - * @memberof PIXI.IPoint# - * @param {PIXI.IPoint} p - The point to check - * @returns {boolean} Whether the given point equal to this point - */ +var core = require('@pixi/core'); +var math = require('@pixi/math'); +var sprite = require('@pixi/sprite'); +var utils = require('@pixi/utils'); +var constants = require('@pixi/constants'); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +var tempPoint = new math.Point(); /** - * The Point object represents a location in a two-dimensional coordinate system, where x represents - * the horizontal axis and y represents the vertical axis. + * A tiling sprite is a fast way of rendering a tiling image * * @class + * @extends PIXI.Sprite * @memberof PIXI - * @implements IPoint */ -var Point = /** @class */ (function () { +var TilingSprite = /** @class */ (function (_super) { + __extends(TilingSprite, _super); /** - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite */ - function Point(x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } + function TilingSprite(texture, width, height) { + if (width === void 0) { width = 100; } + if (height === void 0) { height = 100; } + var _this = _super.call(this, texture) || this; + /** + * Tile transform + * + * @member {PIXI.Transform} + */ + _this.tileTransform = new math.Transform(); /** + * The with of the tiling sprite + * * @member {number} - * @default 0 + * @private */ - this.x = x; + _this._width = width; /** + * The height of the tiling sprite + * * @member {number} - * @default 0 + * @private */ - this.y = y; + _this._height = height; + /** + * matrix that is applied to UV to get the coords in Texture normalized space to coords in BaseTexture space + * + * @member {PIXI.TextureMatrix} + */ + _this.uvMatrix = texture.uvMatrix || new core.TextureMatrix(texture); + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_render' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; } + Object.defineProperty(TilingSprite.prototype, "clampMargin", { + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + get: function () { + return this.uvMatrix.clampMargin; + }, + set: function (value) { + this.uvMatrix.clampMargin = value; + this.uvMatrix.update(true); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "tileScale", { + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + get: function () { + return this.tileTransform.scale; + }, + set: function (value) { + this.tileTransform.scale.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "tilePosition", { + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + get: function () { + return this.tileTransform.position; + }, + set: function (value) { + this.tileTransform.position.copyFrom(value); + }, + enumerable: false, + configurable: true + }); /** - * Creates a clone of this point - * - * @return {PIXI.Point} a copy of the point - */ - Point.prototype.clone = function () { - return new Point(this.x, this.y); - }; - /** - * Copies x and y from the given point - * - * @param {PIXI.IPoint} p - The point to copy from - * @returns {this} Returns itself. - */ - Point.prototype.copyFrom = function (p) { - this.set(p.x, p.y); - return this; - }; - /** - * Copies x and y into the given point - * - * @param {PIXI.IPoint} p - The point to copy. - * @returns {PIXI.IPoint} Given point with values updated - */ - Point.prototype.copyTo = function (p) { - p.set(this.x, this.y); - return p; - }; - /** - * Returns true if the given point is equal to this point - * - * @param {PIXI.IPoint} p - The point to check - * @returns {boolean} Whether the given point equal to this point + * @protected */ - Point.prototype.equals = function (p) { - return (p.x === this.x) && (p.y === this.y); + TilingSprite.prototype._onTextureUpdate = function () { + if (this.uvMatrix) { + this.uvMatrix.texture = this._texture; + } + this._cachedTint = 0xFFFFFF; }; /** - * Sets the point to a new x and y position. - * If y is omitted, both x and y will be set to x. + * Renders the object using the WebGL renderer * - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=x] - position of the point on the y axis + * @protected + * @param {PIXI.Renderer} renderer - The renderer */ - Point.prototype.set = function (x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = x; } - this.x = x; - this.y = y; + TilingSprite.prototype._render = function (renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + if (!texture || !texture.valid) { + return; + } + this.tileTransform.updateLocalTransform(); + this.uvMatrix.update(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); }; - return Point; -}()); - -/** - * The Point object represents a location in a two-dimensional coordinate system, where x represents - * the horizontal axis and y represents the vertical axis. - * - * An ObservablePoint is a point that triggers a callback when the point's position is changed. - * - * @class - * @memberof PIXI - * @implements IPoint - */ -var ObservablePoint = /** @class */ (function () { - /** - * @param {Function} cb - callback when changed - * @param {object} scope - owner of callback - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis - */ - function ObservablePoint(cb, scope, x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - this._x = x; - this._y = y; - this.cb = cb; - this.scope = scope; - } /** - * Creates a clone of this point. - * The callback and scope params can be overidden otherwise they will default - * to the clone object's values. + * Updates the bounds of the tiling sprite. * - * @override - * @param {Function} [cb=null] - callback when changed - * @param {object} [scope=null] - owner of callback - * @return {PIXI.ObservablePoint} a copy of the point + * @protected */ - ObservablePoint.prototype.clone = function (cb, scope) { - if (cb === void 0) { cb = this.cb; } - if (scope === void 0) { scope = this.scope; } - return new ObservablePoint(cb, scope, this._x, this._y); + TilingSprite.prototype._calculateBounds = function () { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); }; /** - * Sets the point to a new x and y position. - * If y is omitted, both x and y will be set to x. + * Gets the local bounds of the sprite object. * - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=x] - position of the point on the y axis + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. */ - ObservablePoint.prototype.set = function (x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = x; } - if (this._x !== x || this._y !== y) { - this._x = x; - this._y = y; - this.cb.call(this.scope); + TilingSprite.prototype.getLocalBounds = function (rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new math.Rectangle(); + } + rect = this._localBoundsRect; + } + return this._bounds.getRectangle(rect); } + return _super.prototype.getLocalBounds.call(this, rect); }; /** - * Copies x and y from the given point + * Checks if a point is inside this tiling sprite. * - * @param {PIXI.IPoint} p - The point to copy from. - * @returns {this} Returns itself. + * @param {PIXI.IPointData} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. */ - ObservablePoint.prototype.copyFrom = function (p) { - if (this._x !== p.x || this._y !== p.y) { - this._x = p.x; - this._y = p.y; - this.cb.call(this.scope); + TilingSprite.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, tempPoint); + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } } - return this; + return false; }; /** - * Copies x and y into the given point + * Destroys this sprite and optionally its texture and children * - * @param {PIXI.IPoint} p - The point to copy. - * @returns {PIXI.IPoint} Given point with values updated + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well */ - ObservablePoint.prototype.copyTo = function (p) { - p.set(this._x, this._y); - return p; + TilingSprite.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this.tileTransform = null; + this.uvMatrix = null; }; /** - * Returns true if the given point is equal to this point + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture * - * @param {PIXI.IPoint} p - The point to check - * @returns {boolean} Whether the given point equal to this point + * @static + * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {Object} options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {number} options.width - required width of the tiling sprite + * @param {number} options.height - required height of the tiling sprite + * @return {PIXI.TilingSprite} The newly created texture */ - ObservablePoint.prototype.equals = function (p) { - return (p.x === this._x) && (p.y === this._y); + TilingSprite.from = function (source, options) { + // Deprecated + if (typeof options === 'number') { + utils.deprecation('5.3.0', 'TilingSprite.from use options instead of width and height args'); + // eslint-disable-next-line prefer-rest-params + options = { width: options, height: arguments[2] }; + } + return new TilingSprite(core.Texture.from(source, options), options.width, options.height); }; - Object.defineProperty(ObservablePoint.prototype, "x", { + Object.defineProperty(TilingSprite.prototype, "width", { /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * The width of the sprite, setting this will actually modify the scale to achieve the value set * * @member {number} */ get: function () { - return this._x; + return this._width; }, set: function (value) { - if (this._x !== value) { - this._x = value; - this.cb.call(this.scope); - } + this._width = value; }, - enumerable: true, + enumerable: false, configurable: true }); - Object.defineProperty(ObservablePoint.prototype, "y", { + Object.defineProperty(TilingSprite.prototype, "height", { /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set * * @member {number} */ get: function () { - return this._y; + return this._height; }, set: function (value) { - if (this._y !== value) { - this._y = value; - this.cb.call(this.scope); - } + this._height = value; }, - enumerable: true, + enumerable: false, configurable: true }); - return ObservablePoint; -}()); + return TilingSprite; +}(sprite.Sprite)); -/** - * Two Pi. - * - * @static - * @constant {number} PI_2 - * @memberof PIXI - */ -var PI_2 = Math.PI * 2; -/** - * Conversion factor for converting radians to degrees. - * - * @static - * @constant {number} RAD_TO_DEG - * @memberof PIXI - */ -var RAD_TO_DEG = 180 / Math.PI; -/** - * Conversion factor for converting degrees to radians. - * - * @static - * @constant {number} DEG_TO_RAD - * @memberof PIXI - */ -var DEG_TO_RAD = Math.PI / 180; -(function (SHAPES) { - SHAPES[SHAPES["POLY"] = 0] = "POLY"; - SHAPES[SHAPES["RECT"] = 1] = "RECT"; - SHAPES[SHAPES["CIRC"] = 2] = "CIRC"; - SHAPES[SHAPES["ELIP"] = 3] = "ELIP"; - SHAPES[SHAPES["RREC"] = 4] = "RREC"; -})(exports.SHAPES || (exports.SHAPES = {})); -/** - * Constants that identify shapes, mainly to prevent `instanceof` calls. - * - * @static - * @constant - * @name SHAPES - * @memberof PIXI - * @type {enum} - * @property {number} POLY Polygon - * @property {number} RECT Rectangle - * @property {number} CIRC Circle - * @property {number} ELIP Ellipse - * @property {number} RREC Rounded Rectangle - * @enum {number} - */ +var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + +var fragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord - floor(vTextureCoord - uClampOffset);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture2D(uSampler, coord);\n gl_FragColor = texSample * uColor;\n}\n"; + +var fragmentSimple = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n"; +var tempMat = new math.Matrix(); /** - * The PixiJS Matrix as a class makes it a lot faster. + * WebGL renderer plugin for tiling sprites * - * Here is a representation of it: - * ```js - * | a | c | tx| - * | b | d | ty| - * | 0 | 0 | 1 | - * ``` * @class * @memberof PIXI + * @extends PIXI.ObjectRenderer */ -var Matrix = /** @class */ (function () { +var TilingSpriteRenderer = /** @class */ (function (_super) { + __extends(TilingSpriteRenderer, _super); /** - * @param {number} [a=1] - x scale - * @param {number} [b=0] - x skew - * @param {number} [c=0] - y skew - * @param {number} [d=1] - y scale - * @param {number} [tx=0] - x translation - * @param {number} [ty=0] - y translation + * constructor for renderer + * + * @param {PIXI.Renderer} renderer - The renderer this tiling awesomeness works for. */ - function Matrix(a, b, c, d, tx, ty) { - if (a === void 0) { a = 1; } - if (b === void 0) { b = 0; } - if (c === void 0) { c = 0; } - if (d === void 0) { d = 1; } - if (tx === void 0) { tx = 0; } - if (ty === void 0) { ty = 0; } - this.array = null; - /** - * @member {number} - * @default 1 - */ - this.a = a; - /** - * @member {number} - * @default 0 - */ - this.b = b; + function TilingSpriteRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + var uniforms = { globals: _this.renderer.globalUniforms }; + _this.shader = core.Shader.from(vertex, fragment, uniforms); + _this.simpleShader = core.Shader.from(vertex, fragmentSimple, uniforms); + _this.quad = new core.QuadUv(); /** - * @member {number} - * @default 0 + * The WebGL state in which this renderer will work. + * + * @member {PIXI.State} + * @readonly */ - this.c = c; + _this.state = core.State.for2d(); + return _this; + } + /** + * + * @param {PIXI.TilingSprite} ts - tilingSprite to be rendered + */ + TilingSpriteRenderer.prototype.render = function (ts) { + var renderer = this.renderer; + var quad = this.quad; + var vertices = quad.vertices; + vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + quad.invalidate(); + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvMatrix; + var isSimple = baseTex.isPowerOfTwo + && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === constants.WRAP_MODES.CLAMP) { + baseTex.wrapMode = constants.WRAP_MODES.REPEAT; + } + } + else { + isSimple = baseTex.wrapMode !== constants.WRAP_MODES.CLAMP; + } + } + var shader = isSimple ? this.simpleShader : this.shader; + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } + else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.alphaMode); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + shader.uniforms.uSampler = tex; + renderer.shader.bind(shader); + renderer.geometry.bind(quad); + this.state.blendMode = utils.correctBlendMode(ts.blendMode, baseTex.alphaMode); + renderer.state.set(this.state); + renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + return TilingSpriteRenderer; +}(core.ObjectRenderer)); + +exports.TilingSprite = TilingSprite; +exports.TilingSpriteRenderer = TilingSpriteRenderer; + + +},{"@pixi/constants":7,"@pixi/core":8,"@pixi/math":20,"@pixi/sprite":33,"@pixi/utils":38}],33:[function(require,module,exports){ +/*! + * @pixi/sprite - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/sprite is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var constants = require('@pixi/constants'); +var core = require('@pixi/core'); +var display = require('@pixi/display'); +var math = require('@pixi/math'); +var settings = require('@pixi/settings'); +var utils = require('@pixi/utils'); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var tempPoint = new math.Point(); +var indices = new Uint16Array([0, 1, 2, 0, 2, 3]); +/** + * The Sprite object is the base for all textured objects that are rendered to the screen +* + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = PIXI.Sprite.from('assets/image.png'); + * ``` + * + * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}, + * as swapping base textures when rendering to the screen is inefficient. + * + * ```js + * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; + * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); + * ... + * } + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ +var Sprite = /** @class */ (function (_super) { + __extends(Sprite, _super); + /** + * @param {PIXI.Texture} [texture] - The texture for this sprite. + */ + function Sprite(texture) { + var _this = _super.call(this) || this; + /** + * The anchor point defines the normalized coordinates + * in the texture that map to the position of this + * sprite. + * + * By default, this is `(0,0)` (or `texture.defaultAnchor` + * if you have modified that), which means the position + * `(x,y)` of this `Sprite` will be the top-left corner. + * + * Note: Updating `texture.defaultAnchor` after + * constructing a `Sprite` does _not_ update its anchor. + * + * {@link https://docs.cocos2d-x.org/cocos2d-x/en/sprites/manipulation.html} + * + * @default `texture.defaultAnchor` + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new math.ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0)); + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; /** + * The width of the sprite (this is initially set by the texture) + * + * @protected * @member {number} - * @default 1 */ - this.d = d; + _this._width = 0; + /** + * The height of the sprite (this is initially set by the texture) + * + * @protected + * @member {number} + */ + _this._height = 0; /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private * @member {number} - * @default 0 + * @default 0xFFFFFF */ - this.tx = tx; + _this._tint = null; /** + * The tint applied to the sprite. This is a RGB value. A value of 0xFFFFFF will remove any tint effect. + * + * @private * @member {number} - * @default 0 + * @default 16777215 */ - this.ty = ty; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = constants.BLEND_MODES.NORMAL; + /** + * Cached tint value so we can tell when the tint is changed. + * Value is used for 2d CanvasRenderer. + * + * @protected + * @member {number} + * @default 0xFFFFFF + */ + _this._cachedTint = 0xFFFFFF; + /** + * this is used to store the uvs data of the sprite, assigned at the same time + * as the vertexData in calculateVertices() + * + * @private + * @member {Float32Array} + */ + _this.uvs = null; + // call texture setter + _this.texture = texture || core.Texture.EMPTY; + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + _this._transformID = -1; + _this._textureID = -1; + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + // Batchable stuff.. + // TODO could make this a mixin? + _this.indices = indices; + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_render' & '_renderCanvas' methods. + * + * @member {string} + * @default 'batch' + */ + _this.pluginName = 'batch'; + /** + * used to fast check if a sprite is.. a sprite! + * @member {boolean} + */ + _this.isSprite = true; + /** + * Internal roundPixels field + * + * @member {boolean} + * @private + */ + _this._roundPixels = settings.settings.ROUND_PIXELS; + return _this; } /** - * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: - * - * a = array[0] - * b = array[1] - * c = array[3] - * d = array[4] - * tx = array[2] - * ty = array[5] + * When the texture is updated, this event will fire to update the scale and frame * - * @param {number[]} array - The array that the matrix will be populated from. + * @protected */ - Matrix.prototype.fromArray = function (array) { - this.a = array[0]; - this.b = array[1]; - this.c = array[3]; - this.d = array[4]; - this.tx = array[2]; - this.ty = array[5]; + Sprite.prototype._onTextureUpdate = function () { + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 0xFFFFFF; + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = utils.sign(this.scale.x) * this._width / this._texture.orig.width; + } + if (this._height) { + this.scale.y = utils.sign(this.scale.y) * this._height / this._texture.orig.height; + } }; /** - * sets the matrix properties - * - * @param {number} a - Matrix component - * @param {number} b - Matrix component - * @param {number} c - Matrix component - * @param {number} d - Matrix component - * @param {number} tx - Matrix component - * @param {number} ty - Matrix component + * Called when the anchor position updates. * - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + * @private */ - Matrix.prototype.set = function (a, b, c, d, tx, ty) { - this.a = a; - this.b = b; - this.c = c; - this.d = d; - this.tx = tx; - this.ty = ty; - return this; + Sprite.prototype._onAnchorUpdate = function () { + this._transformID = -1; + this._transformTrimmedID = -1; }; /** - * Creates an array from the current Matrix object. - * - * @param {boolean} transpose - Whether we need to transpose the matrix or not - * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out - * @return {number[]} the newly created array which contains the matrix + * calculates worldTransform * vertices, store it in vertexData */ - Matrix.prototype.toArray = function (transpose, out) { - if (!this.array) { - this.array = new Float32Array(9); + Sprite.prototype.calculateVertices = function () { + var texture = this._texture; + if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) { + return; } - var array = out || this.array; - if (transpose) { - array[0] = this.a; - array[1] = this.b; - array[2] = 0; - array[3] = this.c; - array[4] = this.d; - array[5] = 0; - array[6] = this.tx; - array[7] = this.ty; - array[8] = 1; + // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` + if (this._textureID !== texture._updateID) { + this.uvs = this._texture._uvs.uvsFloat32; + } + this._transformID = this.transform._worldID; + this._textureID = texture._updateID; + // set the vertex data + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - (anchor._x * orig.width); + w0 = w1 + trim.width; + h1 = trim.y - (anchor._y * orig.height); + h0 = h1 + trim.height; } else { - array[0] = this.a; - array[1] = this.c; - array[2] = this.tx; - array[3] = this.b; - array[4] = this.d; - array[5] = this.ty; - array[6] = 0; - array[7] = 0; - array[8] = 1; + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + // xy + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + // xy + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + // xy + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + // xy + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; + if (this._roundPixels) { + var resolution = settings.settings.RESOLUTION; + for (var i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); + } } - return array; }; /** - * Get a new position with the current transformation applied. - * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) - * - * @param {PIXI.Point} pos - The origin - * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) - * @return {PIXI.Point} The new point, transformed through this matrix + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected */ - Matrix.prototype.apply = function (pos, newPos) { - newPos = newPos || new Point(); - var x = pos.x; - var y = pos.y; - newPos.x = (this.a * x) + (this.c * y) + this.tx; - newPos.y = (this.b * x) + (this.d * y) + this.ty; - return newPos; + Sprite.prototype.calculateTrimmedVertices = function () { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } + else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + // xy + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + // xy + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + // xy + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + // xy + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; }; /** - * Get a new position with the inverse of the current transformation applied. - * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) - * - * @param {PIXI.Point} pos - The origin - * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) - * @return {PIXI.Point} The new point, inverse-transformed through this matrix - */ - Matrix.prototype.applyInverse = function (pos, newPos) { - newPos = newPos || new Point(); - var id = 1 / ((this.a * this.d) + (this.c * -this.b)); - var x = pos.x; - var y = pos.y; - newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id); - newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id); - return newPos; + * + * Renders the object using the WebGL renderer + * + * @protected + * @param {PIXI.Renderer} renderer - The webgl renderer to use. + */ + Sprite.prototype._render = function (renderer) { + this.calculateVertices(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); }; /** - * Translates the matrix on the x and y. + * Updates the bounds of the sprite. * - * @param {number} x How much to translate x by - * @param {number} y How much to translate y by - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + * @protected */ - Matrix.prototype.translate = function (x, y) { - this.tx += x; - this.ty += y; - return this; + Sprite.prototype._calculateBounds = function () { + var trim = this._texture.trim; + var orig = this._texture.orig; + // First lets check to see if the current texture has a trim.. + if (!trim || (trim.width === orig.width && trim.height === orig.height)) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } + else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } }; /** - * Applies a scale transformation to the matrix. + * Gets the local bounds of the sprite object. * - * @param {number} x The amount to scale horizontally - * @param {number} y The amount to scale vertically - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + * @param {PIXI.Rectangle} [rect] - The output rectangle. + * @return {PIXI.Rectangle} The bounds. */ - Matrix.prototype.scale = function (x, y) { - this.a *= x; - this.d *= y; - this.c *= x; - this.b *= y; - this.tx *= x; - this.ty *= y; - return this; + Sprite.prototype.getLocalBounds = function (rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new math.Rectangle(); + } + rect = this._localBoundsRect; + } + return this._bounds.getRectangle(rect); + } + return _super.prototype.getLocalBounds.call(this, rect); }; /** - * Applies a rotation transformation to the matrix. + * Tests if a point is inside this sprite * - * @param {number} angle - The angle in radians. - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + * @param {PIXI.IPointData} point - the point to test + * @return {boolean} the result of the test */ - Matrix.prototype.rotate = function (angle) { - var cos = Math.cos(angle); - var sin = Math.sin(angle); - var a1 = this.a; - var c1 = this.c; - var tx1 = this.tx; - this.a = (a1 * cos) - (this.b * sin); - this.b = (a1 * sin) + (this.b * cos); - this.c = (c1 * cos) - (this.d * sin); - this.d = (c1 * sin) + (this.d * cos); - this.tx = (tx1 * cos) - (this.ty * sin); - this.ty = (tx1 * sin) + (this.ty * cos); - return this; + Sprite.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, tempPoint); + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + return false; }; /** - * Appends the given Matrix to this Matrix. + * Destroys this sprite and optionally its texture and children * - * @param {PIXI.Matrix} matrix - The matrix to append. - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well */ - Matrix.prototype.append = function (matrix) { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - this.a = (matrix.a * a1) + (matrix.b * c1); - this.b = (matrix.a * b1) + (matrix.b * d1); - this.c = (matrix.c * a1) + (matrix.d * c1); - this.d = (matrix.c * b1) + (matrix.d * d1); - this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx; - this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty; - return this; + Sprite.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this._texture.off('update', this._onTextureUpdate, this); + this._anchor = null; + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + this._texture.destroy(!!destroyBaseTexture); + } + this._texture = null; }; + // some helper functions.. /** - * Sets the matrix based on all the available properties + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture * - * @param {number} x - Position on the x axis - * @param {number} y - Position on the y axis - * @param {number} pivotX - Pivot on the x axis - * @param {number} pivotY - Pivot on the y axis - * @param {number} scaleX - Scale on the x axis - * @param {number} scaleY - Scale on the y axis - * @param {number} rotation - Rotation in radians - * @param {number} skewX - Skew on the x axis - * @param {number} skewY - Skew on the y axis - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + * @static + * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {object} [options] - See {@link PIXI.BaseTexture}'s constructor for options. + * @return {PIXI.Sprite} The newly created sprite */ - Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { - this.a = Math.cos(rotation + skewY) * scaleX; - this.b = Math.sin(rotation + skewY) * scaleX; - this.c = -Math.sin(rotation - skewX) * scaleY; - this.d = Math.cos(rotation - skewX) * scaleY; - this.tx = x - ((pivotX * this.a) + (pivotY * this.c)); - this.ty = y - ((pivotX * this.b) + (pivotY * this.d)); - return this; + Sprite.from = function (source, options) { + var texture = (source instanceof core.Texture) + ? source + : core.Texture.from(source, options); + return new Sprite(texture); }; + Object.defineProperty(Sprite.prototype, "roundPixels", { + get: function () { + return this._roundPixels; + }, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} + * + * @member {boolean} + * @default false + */ + set: function (value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "width", { + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + get: function () { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function (value) { + var s = utils.sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "height", { + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + get: function () { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) { + var s = utils.sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "anchor", { + /** + * The anchor sets the origin point of the sprite. The default value is taken from the {@link PIXI.Texture|Texture} + * and passed to the constructor. + * + * The default is `(0,0)`, this means the sprite's origin is the top left. + * + * Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered. + * + * Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner. + * + * If you pass only single parameter, it will set both x and y to the same value as shown in the example below. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5). + * + * @member {PIXI.ObservablePoint} + */ + get: function () { + return this._anchor; + }, + set: function (value) { + this._anchor.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "tint", { + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "texture", { + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + get: function () { + return this._texture; + }, + set: function (value) { + if (this._texture === value) { + return; + } + if (this._texture) { + this._texture.off('update', this._onTextureUpdate, this); + } + this._texture = value || core.Texture.EMPTY; + this._cachedTint = 0xFFFFFF; + this._textureID = -1; + this._textureTrimmedID = -1; + if (value) { + // wait for the texture to load + if (value.baseTexture.valid) { + this._onTextureUpdate(); + } + else { + value.once('update', this._onTextureUpdate, this); + } + } + }, + enumerable: false, + configurable: true + }); + return Sprite; +}(display.Container)); + +exports.Sprite = Sprite; + + +},{"@pixi/constants":7,"@pixi/core":8,"@pixi/display":9,"@pixi/math":20,"@pixi/settings":30,"@pixi/utils":38}],34:[function(require,module,exports){ +/*! + * @pixi/spritesheet - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/spritesheet is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var math = require('@pixi/math'); +var core = require('@pixi/core'); +var utils = require('@pixi/utils'); +var loaders = require('@pixi/loaders'); + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * To access a sprite sheet from your code pass its JSON data file to Pixi's loader: + * + * ```js + * PIXI.Loader.shared.add("images/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet; + * ... + * } + * ``` + * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. + * + * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, + * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. + * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only + * supported by TexturePacker. + * + * @class + * @memberof PIXI + */ +var Spritesheet = /** @class */ (function () { /** - * Prepends the given Matrix to this Matrix. + * @param {PIXI.BaseTexture|PIXI.Texture} baseTexture - Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + function Spritesheet(texture, data, resolutionFilename) { + if (resolutionFilename === void 0) { resolutionFilename = null; } + /** + * Reference to original source image from the Loader. This reference is retained so we + * can destroy the Texture later on. It is never used internally. + * @type {PIXI.Texture} + * @private + */ + this._texture = texture instanceof core.Texture ? texture : null; + /** + * Reference to ths source texture. + * @type {PIXI.BaseTexture} + */ + this.baseTexture = texture instanceof core.BaseTexture ? texture : this._texture.baseTexture; + /** + * A map containing all textures of the sprite sheet. + * Can be used to create a {@link PIXI.Sprite|Sprite}: + * ```js + * new PIXI.Sprite(sheet.textures["image.png"]); + * ``` + * @member {Object} + */ + this.textures = {}; + /** + * A map containing the textures for each animation. + * Can be used to create an {@link PIXI.AnimatedSprite|AnimatedSprite}: + * ```js + * new PIXI.AnimatedSprite(sheet.animations["anim_name"]) + * ``` + * @member {Object} + */ + this.animations = {}; + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + var resource = this.baseTexture.resource; + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null)); + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. * - * @param {PIXI.Matrix} matrix - The matrix to prepend - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. */ - Matrix.prototype.prepend = function (matrix) { - var tx1 = this.tx; - if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { - var a1 = this.a; - var c1 = this.c; - this.a = (a1 * matrix.a) + (this.b * matrix.c); - this.b = (a1 * matrix.b) + (this.b * matrix.d); - this.c = (c1 * matrix.a) + (this.d * matrix.c); - this.d = (c1 * matrix.b) + (this.d * matrix.d); + Spritesheet.prototype._updateResolution = function (resolutionFilename) { + if (resolutionFilename === void 0) { resolutionFilename = null; } + var scale = this.data.meta.scale; + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = utils.getResolutionOfUrl(resolutionFilename, null); + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; } - this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx; - this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty; - return this; + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.setResolution(resolution); + } + return resolution; }; /** - * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. * - * @param {PIXI.Transform} transform - The transform to apply the properties to. - * @return {PIXI.Transform} The transform with the newly applied properties + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. */ - Matrix.prototype.decompose = function (transform) { - // sort out rotation / skew.. - var a = this.a; - var b = this.b; - var c = this.c; - var d = this.d; - var skewX = -Math.atan2(-c, d); - var skewY = Math.atan2(b, a); - var delta = Math.abs(skewX + skewY); - if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) { - transform.rotation = skewY; - transform.skew.x = transform.skew.y = 0; + Spritesheet.prototype.parse = function (callback) { + this._batchIndex = 0; + this._callback = callback; + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._processAnimations(); + this._parseComplete(); } else { - transform.rotation = 0; - transform.skew.x = skewX; - transform.skew.y = skewY; + this._nextBatch(); } - // next set scale - transform.scale.x = Math.sqrt((a * a) + (b * b)); - transform.scale.y = Math.sqrt((c * c) + (d * d)); - // next set position - transform.position.x = this.tx; - transform.position.y = this.ty; - return transform; }; /** - * Inverts this matrix + * Process a batch of frames * - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + Spritesheet.prototype._processFrames = function (initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var data = this._frames[i]; + var rect = data.frame; + if (rect) { + var frame = null; + var trim = null; + var sourceSize = data.trimmed !== false && data.sourceSize + ? data.sourceSize : data.frame; + var orig = new math.Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution); + if (data.rotated) { + frame = new math.Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution); + } + else { + frame = new math.Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + // Check to see if the sprite is trimmed + if (data.trimmed !== false && data.spriteSourceSize) { + trim = new math.Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + this.textures[i] = new core.Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor); + // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions + core.Texture.addToCache(this.textures[i], i); + } + frameIndex++; + } + }; + /** + * Parse animations config + * + * @private */ - Matrix.prototype.invert = function () { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - var tx1 = this.tx; - var n = (a1 * d1) - (b1 * c1); - this.a = d1 / n; - this.b = -b1 / n; - this.c = -c1 / n; - this.d = a1 / n; - this.tx = ((c1 * this.ty) - (d1 * tx1)) / n; - this.ty = -((a1 * this.ty) - (b1 * tx1)) / n; - return this; + Spritesheet.prototype._processAnimations = function () { + var animations = this.data.animations || {}; + for (var animName in animations) { + this.animations[animName] = []; + for (var i = 0; i < animations[animName].length; i++) { + var frameName = animations[animName][i]; + this.animations[animName].push(this.textures[frameName]); + } + } }; /** - * Resets this Matrix to an identity (default) matrix. + * The parse has completed. * - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + * @private */ - Matrix.prototype.identity = function () { - this.a = 1; - this.b = 0; - this.c = 0; - this.d = 1; - this.tx = 0; - this.ty = 0; - return this; + Spritesheet.prototype._parseComplete = function () { + var callback = this._callback; + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); }; /** - * Creates a new Matrix object with the same values as this one. + * Begin the next batch of textures. * - * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + * @private */ - Matrix.prototype.clone = function () { - var matrix = new Matrix(); - matrix.a = this.a; - matrix.b = this.b; - matrix.c = this.c; - matrix.d = this.d; - matrix.tx = this.tx; - matrix.ty = this.ty; - return matrix; + Spritesheet.prototype._nextBatch = function () { + var _this = this; + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } + else { + _this._processAnimations(); + _this._parseComplete(); + } + }, 0); }; /** - * Changes the values of the given matrix to be the same as the ones in this matrix + * Destroy Spritesheet and don't use after this. * - * @param {PIXI.Matrix} matrix - The matrix to copy to. - * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well */ - Matrix.prototype.copyTo = function (matrix) { - matrix.a = this.a; - matrix.b = this.b; - matrix.c = this.c; - matrix.d = this.d; - matrix.tx = this.tx; - matrix.ty = this.ty; - return matrix; + Spritesheet.prototype.destroy = function (destroyBase) { + var _a; + if (destroyBase === void 0) { destroyBase = false; } + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy(); + this.baseTexture.destroy(); + } + this._texture = null; + this.baseTexture = null; }; /** - * Changes the values of the matrix to be the same as the ones in given matrix + * The maximum number of Textures to build per process. * - * @param {PIXI.Matrix} matrix - The matrix to copy from. - * @return {PIXI.Matrix} this + * @type {number} + * @default 1000 */ - Matrix.prototype.copyFrom = function (matrix) { - this.a = matrix.a; - this.b = matrix.b; - this.c = matrix.c; - this.d = matrix.d; - this.tx = matrix.tx; - this.ty = matrix.ty; - return this; + Spritesheet.BATCH_SIZE = 1000; + return Spritesheet; +}()); + +/** + * {@link PIXI.Loader Loader} middleware for loading texture atlases that have been created with + * TexturePacker or similar JSON-based spritesheet. + * + * This middleware automatically generates Texture resources. + * + * @class + * @memberof PIXI + * @implements PIXI.ILoaderPlugin + */ +var SpritesheetLoader = /** @class */ (function () { + function SpritesheetLoader() { + } + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param {PIXI.LoaderResource} resource + * @param {function} next + */ + SpritesheetLoader.use = function (resource, next) { + // because this is middleware, it execute in loader context. `this` = loader + var loader = this; + var imageResourceName = resource.name + "_image"; + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data + || resource.type !== loaders.LoaderResource.TYPE.JSON + || !resource.data.frames + || loader.resources[imageResourceName]) { + next(); + return; + } + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource, + }; + var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl); + // load the image for this sheet + loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + if (res.error) { + next(res.error); + return; + } + var spritesheet = new Spritesheet(res.texture, resource.data, resource.url); + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); }; - Object.defineProperty(Matrix, "IDENTITY", { + /** + * Get the spritesheets root path + * @param {PIXI.LoaderResource} resource - Resource to check path + * @param {string} baseUrl - Base root url + */ + SpritesheetLoader.getResourcePath = function (resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + return utils.url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); + }; + return SpritesheetLoader; +}()); + +exports.Spritesheet = Spritesheet; +exports.SpritesheetLoader = SpritesheetLoader; + + +},{"@pixi/core":8,"@pixi/loaders":19,"@pixi/math":20,"@pixi/utils":38}],35:[function(require,module,exports){ +/*! + * @pixi/text-bitmap - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * + * @pixi/text-bitmap is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var math = require('@pixi/math'); +var settings = require('@pixi/settings'); +var mesh = require('@pixi/mesh'); +var utils = require('@pixi/utils'); +var core = require('@pixi/core'); +var text = require('@pixi/text'); +var display = require('@pixi/display'); +var loaders = require('@pixi/loaders'); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +/* eslint-disable max-len */ +/** + * Normalized parsed data from .fnt files. + * + * @class + * @memberof PIXI + */ +var BitmapFontData = /** @class */ (function () { + function BitmapFontData() { /** - * A default (identity) matrix - * - * @static - * @const - * @member {PIXI.Matrix} + * @member {PIXI.IBitmapFontDataInfo[]} + * @readOnly */ - get: function () { - return new Matrix(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix, "TEMP_MATRIX", { + this.info = []; /** - * A temp matrix - * - * @static - * @const - * @member {PIXI.Matrix} + * @member {PIXI.IBitmapFontDataCommon[]} + * @readOnly */ - get: function () { - return new Matrix(); - }, - enumerable: true, - configurable: true - }); - return Matrix; + this.common = []; + /** + * @member {PIXI.IBitmapFontDataPage[]} + * @readOnly + */ + this.page = []; + /** + * @member {PIXI.IBitmapFontDataChar[]} + * @readOnly + */ + this.char = []; + /** + * @member {PIXI.IBitmapFontDataKerning[]} + * @readOnly + */ + this.kerning = []; + } + return BitmapFontData; }()); - -// Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group -/* - * Transform matrix for operation n is: - * | ux | vx | - * | uy | vy | - */ -var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; -var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; -var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; -var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; /** - * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table} - * for the composition of each rotation in the dihederal group D8. - * - * @type number[][] - * @private + * @memberof PIXI + * @typedef {object} IBitmapFontDataInfo + * @property {string} face + * @property {number} size */ -var rotationCayley = []; /** - * Matrices for each `GD8Symmetry` rotation. - * - * @type Matrix[] - * @private + * @memberof PIXI + * @typedef {object} IBitmapFontDataCommon + * @property {number} lineHeight */ -var rotationMatrices = []; -/* - * Alias for {@code Math.sign}. +/** + * @memberof PIXI + * @typedef {object} IBitmapFontDataPage + * @property {number} id + * @property {string} file */ -var signum = Math.sign; -/* - * Initializes `rotationCayley` and `rotationMatrices`. It is called - * only once below. +/** + * @memberof PIXI + * @typedef {object} IBitmapFontDataChar + * @property {string} id + * @property {number} page + * @property {number} x + * @property {number} y + * @property {number} width + * @property {number} height + * @property {number} xoffset + * @property {number} yoffset + * @property {number} xadvance */ -function init() { - for (var i = 0; i < 16; i++) { - var row = []; - rotationCayley.push(row); - for (var j = 0; j < 16; j++) { - /* Multiplies rotation matrices i and j. */ - var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j])); - var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j])); - var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j])); - var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j])); - /* Finds rotation matrix matching the product and pushes it. */ - for (var k = 0; k < 16; k++) { - if (ux[k] === _ux && uy[k] === _uy - && vx[k] === _vx && vy[k] === _vy) { - row.push(k); - break; - } - } - } - } - for (var i = 0; i < 16; i++) { - var mat = new Matrix(); - mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); - rotationMatrices.push(mat); - } -} -init(); /** * @memberof PIXI - * @typedef {number} GD8Symmetry - * @see PIXI.groupD8 + * @typedef {object} IBitmapFontDataKerning + * @property {number} first + * @property {number} second + * @property {number} amount */ + /** - * Implements the dihedral group D8, which is similar to - * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}; - * D8 is the same but with diagonals, and it is used for texture - * rotations. - * - * The directions the U- and V- axes after rotation - * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))` - * and `(vX(a), vY(a))`. These aren't necessarily unit vectors. - * - * **Origin:**
- * This is the small part of gameofbombs.com portal system. It works. + * BitmapFont format that's Text-based. * - * @see PIXI.groupD8.E - * @see PIXI.groupD8.SE - * @see PIXI.groupD8.S - * @see PIXI.groupD8.SW - * @see PIXI.groupD8.W - * @see PIXI.groupD8.NW - * @see PIXI.groupD8.N - * @see PIXI.groupD8.NE - * @author Ivan @ivanpopelyshev - * @namespace PIXI.groupD8 - * @memberof PIXI + * @class + * @private */ -var groupD8 = { +var TextFormat = /** @class */ (function () { + function TextFormat() { + } /** - * | Rotation | Direction | - * |----------|-----------| - * | 0° | East | + * Check if resource refers to txt font data. * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} + * @static + * @private + * @param {any} data + * @return {boolean} True if resource could be treated as font data, false otherwise. */ - E: 0, + TextFormat.test = function (data) { + return typeof data === 'string' && data.indexOf('info face=') === 0; + }; /** - * | Rotation | Direction | - * |----------|-----------| - * | 45°↻ | Southeast | + * Convert text font data to a javascript object. * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - SE: 1, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 90°↻ | South | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - S: 2, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 135°↻ | Southwest | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - SW: 3, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 180° | West | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - W: 4, + * @static + * @private + * @param {string} txt - Raw string data to be converted + * @return {PIXI.BitmapFontData} Parsed font data + */ + TextFormat.parse = function (txt) { + // Retrieve data item + var items = txt.match(/^[a-z]+\s+.+$/gm); + var rawData = { + info: [], + common: [], + page: [], + char: [], + chars: [], + kerning: [], + }; + for (var i in items) { + // Extract item name + var name = items[i].match(/^[a-z]+/gm)[0]; + // Extract item attribute list as string ex.: "width=10" + var attributeList = items[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm); + // Convert attribute list into an object + var itemData = {}; + for (var i_1 in attributeList) { + // Split key-value pairs + var split = attributeList[i_1].split('='); + var key = split[0]; + // Remove eventual quotes from value + var strValue = split[1].replace(/"/gm, ''); + // Try to convert value into float + var floatValue = parseFloat(strValue); + // Use string value case float value is NaN + var value = isNaN(floatValue) ? strValue : floatValue; + itemData[key] = value; + } + // Push current item to the resulting data + rawData[name].push(itemData); + } + var font = new BitmapFontData(); + rawData.info.forEach(function (info) { return font.info.push({ + face: info.face, + size: parseInt(info.size, 10), + }); }); + rawData.common.forEach(function (common) { return font.common.push({ + lineHeight: parseInt(common.lineHeight, 10), + }); }); + rawData.page.forEach(function (page) { return font.page.push({ + id: parseInt(page.id, 10), + file: page.file, + }); }); + rawData.char.forEach(function (char) { return font.char.push({ + id: parseInt(char.id, 10), + page: parseInt(char.page, 10), + x: parseInt(char.x, 10), + y: parseInt(char.y, 10), + width: parseInt(char.width, 10), + height: parseInt(char.height, 10), + xoffset: parseInt(char.xoffset, 10), + yoffset: parseInt(char.yoffset, 10), + xadvance: parseInt(char.xadvance, 10), + }); }); + rawData.kerning.forEach(function (kerning) { return font.kerning.push({ + first: parseInt(kerning.first, 10), + second: parseInt(kerning.second, 10), + amount: parseInt(kerning.amount, 10), + }); }); + return font; + }; + return TextFormat; +}()); + +/** + * BitmapFont format that's XML-based. + * + * @class + * @private + */ +var XMLFormat = /** @class */ (function () { + function XMLFormat() { + } /** - * | Rotation | Direction | - * |-------------|--------------| - * | -135°/225°↻ | Northwest | + * Check if resource refers to xml font data. * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} + * @static + * @private + * @param {any} data + * @return {boolean} True if resource could be treated as font data, false otherwise. */ - NW: 5, + XMLFormat.test = function (data) { + return data instanceof XMLDocument + && data.getElementsByTagName('page').length + && data.getElementsByTagName('info')[0].getAttribute('face') !== null; + }; /** - * | Rotation | Direction | - * |-------------|--------------| - * | -90°/270°↻ | North | + * Convert the XML into BitmapFontData that we can use. * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - N: 6, + * @static + * @private + * @param {XMLDocument} xml + * @return {BitmapFontData} Data to use for BitmapFont + */ + XMLFormat.parse = function (xml) { + var data = new BitmapFontData(); + var info = xml.getElementsByTagName('info'); + var common = xml.getElementsByTagName('common'); + var page = xml.getElementsByTagName('page'); + var char = xml.getElementsByTagName('char'); + var kerning = xml.getElementsByTagName('kerning'); + for (var i = 0; i < info.length; i++) { + data.info.push({ + face: info[i].getAttribute('face'), + size: parseInt(info[i].getAttribute('size'), 10), + }); + } + for (var i = 0; i < common.length; i++) { + data.common.push({ + lineHeight: parseInt(common[i].getAttribute('lineHeight'), 10), + }); + } + for (var i = 0; i < page.length; i++) { + data.page.push({ + id: parseInt(page[i].getAttribute('id'), 10) || 0, + file: page[i].getAttribute('file'), + }); + } + for (var i = 0; i < char.length; i++) { + var letter = char[i]; + data.char.push({ + id: parseInt(letter.getAttribute('id'), 10), + page: parseInt(letter.getAttribute('page'), 10) || 0, + x: parseInt(letter.getAttribute('x'), 10), + y: parseInt(letter.getAttribute('y'), 10), + width: parseInt(letter.getAttribute('width'), 10), + height: parseInt(letter.getAttribute('height'), 10), + xoffset: parseInt(letter.getAttribute('xoffset'), 10), + yoffset: parseInt(letter.getAttribute('yoffset'), 10), + xadvance: parseInt(letter.getAttribute('xadvance'), 10), + }); + } + for (var i = 0; i < kerning.length; i++) { + data.kerning.push({ + first: parseInt(kerning[i].getAttribute('first'), 10), + second: parseInt(kerning[i].getAttribute('second'), 10), + amount: parseInt(kerning[i].getAttribute('amount'), 10), + }); + } + return data; + }; + return XMLFormat; +}()); + +// Registered formats, maybe make this extensible in the future? +var formats = [ + TextFormat, + XMLFormat ]; +/** + * Auto-detect BitmapFont parsing format based on data. + * @private + * @param {any} data - Data to detect format + * @return {any} Format or null + */ +function autoDetectFormat(data) { + for (var i = 0; i < formats.length; i++) { + if (formats[i].test(data)) { + return formats[i]; + } + } + return null; +} + +// TODO: Prevent code duplication b/w generateFillStyle & Text#generateFillStyle +/** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ +function generateFillStyle(canvas, context, style, resolution, lines, metrics) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } + else if (fillStyle.length === 1) { + return fillStyle[0]; + } + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient; + // a dropshadow will enlarge the canvas and result in the gradient being + // generated with the incorrect dimensions + var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; + // should also take padding into account, padding can offset the gradient + var padding = style.padding || 0; + var width = Math.ceil(canvas.width / resolution) - dropShadowCorrection - (padding * 2); + var height = Math.ceil(canvas.height / resolution) - dropShadowCorrection - (padding * 2); + // make a copy of the style settings, so we can manipulate them later + var fill = fillStyle.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === text.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = context.createLinearGradient(width / 2, padding, width / 2, height + padding); + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + // There's potential for floating point precision issues at the seams between gradient repeats. + // The loop below generates the stops in order, so track the last generated one to prevent + // floating point precision from making us go the teeniest bit backwards, resulting in + // the first and last colors getting swapped. + var lastIterationStop = 0; + // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc + var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + // textHeight, but as a 0-1 size in global gradient stop space + var gradStopLineHeight = textHeight / height; + for (var i = 0; i < lines.length; i++) { + var thisLineTop = metrics.lineHeight * i; + for (var j = 0; j < fill.length; j++) { + // 0-1 stop point for the current line, multiplied to global space afterwards + var lineStop = 0; + if (typeof fillGradientStops[j] === 'number') { + lineStop = fillGradientStops[j]; + } + else { + lineStop = j / fill.length; + } + var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight); + // Prevent color stop generation going backwards from floating point imprecision + var clampedStop = Math.max(lastIterationStop, globalStop); + clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw. + gradient.addColorStop(clampedStop, fill[j]); + lastIterationStop = clampedStop; + } + } + } + else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = context.createLinearGradient(padding, height / 2, width + padding, height / 2); + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + var totalIterations = fill.length + 1; + var currentIteration = 1; + for (var i = 0; i < fill.length; i++) { + var stop = void 0; + if (typeof fillGradientStops[i] === 'number') { + stop = fillGradientStops[i]; + } + else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; +} + +// TODO: Prevent code duplication b/w drawGlyph & Text#updateText +/** + * Draws the glyph `metrics.text` on the given canvas. + * + * Ignored because not directly exposed. + * + * @ignore + * @param {HTMLCanvasElement} canvas + * @param {CanvasRenderingContext2D} context + * @param {TextMetrics} metrics + * @param {number} x + * @param {number} y + * @param {number} resolution + * @param {TextStyle} style + */ +function drawGlyph(canvas, context, metrics, x, y, resolution, style) { + var char = metrics.text; + var fontProperties = metrics.fontProperties; + context.translate(x, y); + context.scale(resolution, resolution); + var tx = style.strokeThickness / 2; + var ty = -(style.strokeThickness / 2); + context.font = style.toFontString(); + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + // set canvas text styles + context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics); + context.strokeStyle = style.stroke; + context.font = style.toFontString(); + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + // set canvas text styles + context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics); + context.strokeStyle = style.stroke; + var dropShadowColor = style.dropShadowColor; + var rgb = utils.hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : utils.string2hex(dropShadowColor)); + if (style.dropShadow) { + context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; + context.shadowBlur = style.dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + context.shadowOffsetY = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + } + else { + context.shadowColor = '0'; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + if (style.stroke && style.strokeThickness) { + context.strokeText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + if (style.fill) { + context.fillText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + context.setTransform(); + context.fillStyle = 'rgba(0, 0, 0, 0)'; +} + +/** + * Processes the passed character set data and returns a flattened array of all the characters. + * + * Ignored because not directly exposed. + * + * @ignore + * @param {string | string[] | string[][] } chars + * @returns {string[]} + */ +function resolveCharacters(chars) { + // Split the chars string into individual characters + if (typeof chars === 'string') { + chars = [chars]; + } + // Handle an array of characters+ranges + var result = []; + for (var i = 0, j = chars.length; i < j; i++) { + var item = chars[i]; + // Handle range delimited by start/end chars + if (Array.isArray(item)) { + if (item.length !== 2) { + throw new Error("[BitmapFont]: Invalid character range length, expecting 2 got " + item.length + "."); + } + var startCode = item[0].charCodeAt(0); + var endCode = item[1].charCodeAt(0); + if (endCode < startCode) { + throw new Error('[BitmapFont]: Invalid character range.'); + } + for (var i_1 = startCode, j_1 = endCode; i_1 <= j_1; i_1++) { + result.push(String.fromCharCode(i_1)); + } + } + // Handle a character set string + else { + result.push.apply(result, item.split('')); + } + } + if (result.length === 0) { + throw new Error('[BitmapFont]: Empty set when resolving characters.'); + } + return result; +} + +/** + * BitmapFont represents a typeface available for use with the BitmapText class. Use the `install` + * method for adding a font to be used. + * + * @class + * @memberof PIXI + */ +var BitmapFont = /** @class */ (function () { /** - * | Rotation | Direction | - * |-------------|--------------| - * | -45°/315°↻ | Northeast | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} + * @param {PIXI.BitmapFontData} data + * @param {PIXI.Texture[]|Object.} textures */ - NE: 7, + function BitmapFont(data, textures) { + var info = data.info[0]; + var common = data.common[0]; + var page = data.page[0]; + var res = utils.getResolutionOfUrl(page.file); + var pageTextures = {}; + /** + * The name of the font face. + * + * @member {string} + * @readonly + */ + this.font = info.face; + /** + * The size of the font face in pixels. + * + * @member {number} + * @readonly + */ + this.size = info.size; + /** + * The line-height of the font face in pixels. + * + * @member {number} + * @readonly + */ + this.lineHeight = common.lineHeight / res; + /** + * The map of characters by character code. + * + * @member {object} + * @readonly + */ + this.chars = {}; + /** + * The map of base page textures (i.e., sheets of glyphs). + * + * @member {object} + * @readonly + * @private + */ + this.pageTextures = pageTextures; + // Convert the input Texture, Textures or object + // into a page Texture lookup by "id" + for (var i = 0; i < data.page.length; i++) { + var _a = data.page[i], id = _a.id, file = _a.file; + pageTextures[id] = textures instanceof Array + ? textures[i] : textures[file]; + } + // parse letters + for (var i = 0; i < data.char.length; i++) { + var _b = data.char[i], id = _b.id, page_1 = _b.page; + var _c = data.char[i], x = _c.x, y = _c.y, width = _c.width, height = _c.height, xoffset = _c.xoffset, yoffset = _c.yoffset, xadvance = _c.xadvance; + x /= res; + y /= res; + width /= res; + height /= res; + xoffset /= res; + yoffset /= res; + xadvance /= res; + var rect = new math.Rectangle(x + (pageTextures[page_1].frame.x / res), y + (pageTextures[page_1].frame.y / res), width, height); + this.chars[id] = { + xOffset: xoffset, + yOffset: yoffset, + xAdvance: xadvance, + kerning: {}, + texture: new core.Texture(pageTextures[page_1].baseTexture, rect), + page: page_1, + }; + } + // parse kernings + for (var i = 0; i < data.kerning.length; i++) { + var _d = data.kerning[i], first = _d.first, second = _d.second, amount = _d.amount; + first /= res; + second /= res; + amount /= res; + if (this.chars[second]) { + this.chars[second].kerning[first] = amount; + } + } + } /** - * Reflection about Y-axis. - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} + * Remove references to created glyph textures. */ - MIRROR_VERTICAL: 8, + BitmapFont.prototype.destroy = function () { + for (var id in this.chars) { + this.chars[id].texture.destroy(); + this.chars[id].texture = null; + } + for (var id in this.pageTextures) { + this.pageTextures[id].destroy(true); + this.pageTextures[id] = null; + } + // Set readonly null. + this.chars = null; + this.pageTextures = null; + }; /** - * Reflection about the main diagonal. + * Register a new bitmap font. * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - MAIN_DIAGONAL: 10, + * @static + * @param {XMLDocument|string|PIXI.BitmapFontData} data - The + * characters map that could be provided as xml or raw string. + * @param {Object.|PIXI.Texture|PIXI.Texture[]} + * textures - List of textures for each page. + * @return {PIXI.BitmapFont} Result font object with font, size, lineHeight + * and char fields. + */ + BitmapFont.install = function (data, textures) { + var fontData; + if (data instanceof BitmapFontData) { + fontData = data; + } + else { + var format = autoDetectFormat(data); + if (!format) { + throw new Error('Unrecognized data format for font.'); + } + fontData = format.parse(data); + } + // Single texture, convert to list + if (textures instanceof core.Texture) { + textures = [textures]; + } + var font = new BitmapFont(fontData, textures); + BitmapFont.available[font.font] = font; + return font; + }; /** - * Reflection about X-axis. + * Remove bitmap font by name. * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - MIRROR_HORIZONTAL: 12, - /** - * Reflection about reverse diagonal. + * @static + * @param {string} name + */ + BitmapFont.uninstall = function (name) { + var font = BitmapFont.available[name]; + if (!font) { + throw new Error("No font found named '" + name + "'"); + } + font.destroy(); + delete BitmapFont.available[name]; + }; + /** + * Generates a bitmap-font for the given style and character set. This does not support + * kernings yet. With `style` properties, only the following non-layout properties are used: + * + * - {@link PIXI.TextStyle#dropShadow|dropShadow} + * - {@link PIXI.TextStyle#dropShadowDistance|dropShadowDistance} + * - {@link PIXI.TextStyle#dropShadowColor|dropShadowColor} + * - {@link PIXI.TextStyle#dropShadowBlur|dropShadowBlur} + * - {@link PIXI.TextStyle#dropShadowAngle|dropShadowAngle} + * - {@link PIXI.TextStyle#fill|fill} + * - {@link PIXI.TextStyle#fillGradientStops|fillGradientStops} + * - {@link PIXI.TextStyle#fillGradientType|fillGradientType} + * - {@link PIXI.TextStyle#fontFamily|fontFamily} + * - {@link PIXI.TextStyle#fontSize|fontSize} + * - {@link PIXI.TextStyle#fontVariant|fontVariant} + * - {@link PIXI.TextStyle#fontWeight|fontWeight} + * - {@link PIXI.TextStyle#lineJoin|lineJoin} + * - {@link PIXI.TextStyle#miterLimit|miterLimit} + * - {@link PIXI.TextStyle#stroke|stroke} + * - {@link PIXI.TextStyle#strokeThickness|strokeThickness} + * - {@link PIXI.TextStyle#textBaseline|textBaseline} + * + * @param {string} name - The name of the custom font to use with BitmapText. + * @param {object|PIXI.TextStyle} [style] - Style options to render with BitmapFont. + * @param {PIXI.IBitmapFontOptions} [options] - Setup options for font or name of the font. + * @param {string|string[]|string[][]} [options.chars=PIXI.BitmapFont.ALPHANUMERIC] - characters included + * in the font set. You can also use ranges. For example, `[['a', 'z'], ['A', 'Z'], "!@#$%^&*()~{}[] "]`. + * Don't forget to include spaces ' ' in your character set! + * @param {number} [options.resolution=1] - Render resolution for glyphs. + * @param {number} [options.textureWidth=512] - Optional width of atlas, smaller values to reduce memory. + * @param {number} [options.textureHeight=512] - Optional height of atlas, smaller values to reduce memory. + * @param {number} [options.padding=4] - Padding between glyphs on texture atlas. + * @return {PIXI.BitmapFont} Font generated by style options. + * @static + * @example + * PIXI.BitmapFont.from("TitleFont", { + * fontFamily: "Arial", + * fontSize: 12, + * strokeThickness: 2, + * fill: "purple" + * }); * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - REVERSE_DIAGONAL: 14, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @return {PIXI.GD8Symmetry} The X-component of the U-axis - * after rotating the axes. - */ - uX: function (ind) { return ux[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @return {PIXI.GD8Symmetry} The Y-component of the U-axis - * after rotating the axes. - */ - uY: function (ind) { return uy[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @return {PIXI.GD8Symmetry} The X-component of the V-axis - * after rotating the axes. - */ - vX: function (ind) { return vx[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @return {PIXI.GD8Symmetry} The Y-component of the V-axis - * after rotating the axes. - */ - vY: function (ind) { return vy[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite - * is needed. Only rotations have opposite symmetries while - * reflections don't. - * @return {PIXI.GD8Symmetry} The opposite symmetry of `rotation` + * const title = new PIXI.BitmapText("This is the title", { fontName: "TitleFont" }); */ - inv: function (rotation) { - if (rotation & 8) // true only if between 8 & 15 (reflections) - { - return rotation & 15; // or rotation % 16 + BitmapFont.from = function (name, textStyle, options) { + if (!name) { + throw new Error('[BitmapFont] Property `name` is required.'); } - return (-rotation) & 7; // or (8 - rotation) % 8 - }, + var _a = Object.assign({}, BitmapFont.defaultOptions, options), chars = _a.chars, padding = _a.padding, resolution = _a.resolution, textureWidth = _a.textureWidth, textureHeight = _a.textureHeight; + var charsList = resolveCharacters(chars); + var style = textStyle instanceof text.TextStyle ? textStyle : new text.TextStyle(textStyle); + var lineWidth = textureWidth; + var fontData = new BitmapFontData(); + fontData.info[0] = { + face: style.fontFamily, + size: style.fontSize, + }; + fontData.common[0] = { + lineHeight: style.fontSize, + }; + var positionX = 0; + var positionY = 0; + var canvas; + var context; + var baseTexture; + var maxCharHeight = 0; + var textures = []; + for (var i = 0; i < charsList.length; i++) { + if (!canvas) { + canvas = document.createElement('canvas'); + canvas.width = textureWidth; + canvas.height = textureHeight; + context = canvas.getContext('2d'); + baseTexture = new core.BaseTexture(canvas, { resolution: resolution }); + textures.push(new core.Texture(baseTexture)); + fontData.page.push({ + id: textures.length - 1, + file: '', + }); + } + // Measure glyph dimensions + var metrics = text.TextMetrics.measureText(charsList[i], style, false, canvas); + var width = metrics.width; + var height = Math.ceil(metrics.height); + // This is ugly - but italics are given more space so they don't overlap + var textureGlyphWidth = Math.ceil((style.fontStyle === 'italic' ? 2 : 1) * width); + // Can't fit char anymore: next canvas please! + if (positionY >= textureHeight - (height * resolution)) { + if (positionY === 0) { + // We don't want user debugging an infinite loop (or do we? :) + throw new Error("[BitmapFont] textureHeight " + textureHeight + "px is " + + ("too small for " + style.fontSize + "px fonts")); + } + --i; + // Create new atlas once current has filled up + canvas = null; + context = null; + baseTexture = null; + positionY = 0; + positionX = 0; + maxCharHeight = 0; + continue; + } + maxCharHeight = Math.max(height + metrics.fontProperties.descent, maxCharHeight); + // Wrap line once full row has been rendered + if ((textureGlyphWidth * resolution) + positionX >= lineWidth) { + --i; + positionY += maxCharHeight * resolution; + positionY = Math.ceil(positionY); + positionX = 0; + maxCharHeight = 0; + continue; + } + drawGlyph(canvas, context, metrics, positionX, positionY, resolution, style); + // Unique (numeric) ID mapping to this glyph + var id = metrics.text.charCodeAt(0); + // Create a texture holding just the glyph + fontData.char.push({ + id: id, + page: textures.length - 1, + x: positionX / resolution, + y: positionY / resolution, + width: textureGlyphWidth, + height: height, + xoffset: 0, + yoffset: 0, + xadvance: Math.ceil(width + - (style.dropShadow ? style.dropShadowDistance : 0) + - (style.stroke ? style.strokeThickness : 0)), + }); + positionX += (textureGlyphWidth + (2 * padding)) * resolution; + positionX = Math.ceil(positionX); + } + var font = new BitmapFont(fontData, textures); + // Make it easier to replace a font + if (BitmapFont.available[name] !== undefined) { + BitmapFont.uninstall(name); + } + BitmapFont.available[name] = font; + return font; + }; /** - * Composes the two D8 operations. - * - * Taking `^` as reflection: - * - * | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 | - * |-------|-----|-----|-----|-----|------|-------|-------|-------| - * | E=0 | E | S | W | N | E^ | S^ | W^ | N^ | - * | S=2 | S | W | N | E | S^ | W^ | N^ | E^ | - * | W=4 | W | N | E | S | W^ | N^ | E^ | S^ | - * | N=6 | N | E | S | W | N^ | E^ | S^ | W^ | - * | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S | - * | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W | - * | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N | - * | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E | - * - * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table} - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which - * is the row in the above cayley table. - * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which - * is the column in the above cayley table. - * @return {PIXI.GD8Symmetry} Composed operation + * This character set includes all the letters in the alphabet (both lower- and upper- case). + * @readonly + * @static + * @member {string[][]} + * @example + * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.ALPHA }) */ - add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); }, + BitmapFont.ALPHA = [['a', 'z'], ['A', 'Z'], ' ']; /** - * Reverse of `add`. - * - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotationSecond - Second operation - * @param {PIXI.GD8Symmetry} rotationFirst - First operation - * @return {PIXI.GD8Symmetry} Result + * This character set includes all decimal digits (from 0 to 9). + * @readonly + * @static + * @member {string[][]} + * @example + * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.NUMERIC }) */ - sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); }, + BitmapFont.NUMERIC = [['0', '9']]; /** - * Adds 180 degrees to rotation, which is a commutative - * operation. - * - * @memberof PIXI.groupD8 - * @param {number} rotation - The number to rotate. - * @returns {number} Rotated number + * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`. + * @readonly + * @static + * @member {string[][]} */ - rotate180: function (rotation) { return rotation ^ 4; }, + BitmapFont.ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' ']; /** - * Checks if the rotation angle is vertical, i.e. south - * or north. It doesn't work for reflections. - * - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotation - The number to check. - * @returns {boolean} Whether or not the direction is vertical + * This character set consists of all the ASCII table. + * @readonly + * @static + * @member {string[][]} + * @see http://www.asciitable.com/ */ - isVertical: function (rotation) { return (rotation & 3) === 2; }, + BitmapFont.ASCII = [[' ', '~']]; /** - * Approximates the vector `V(dx,dy)` into one of the - * eight directions provided by `groupD8`. + * Collection of default options when using `BitmapFont.from`. * - * @memberof PIXI.groupD8 - * @param {number} dx - X-component of the vector - * @param {number} dy - Y-component of the vector - * @return {PIXI.GD8Symmetry} Approximation of the vector into - * one of the eight symmetries. + * @readonly + * @static + * @member {PIXI.IBitmapFontOptions} + * @property {number} resolution=1 + * @property {number} textureWidth=512 + * @property {number} textureHeight=512 + * @property {number} padding=4 + * @property {string|string[]|string[][]} chars=PIXI.BitmapFont.ALPHANUMERIC */ - byDirection: function (dx, dy) { - if (Math.abs(dx) * 2 <= Math.abs(dy)) { - if (dy >= 0) { - return groupD8.S; - } - return groupD8.N; - } - else if (Math.abs(dy) * 2 <= Math.abs(dx)) { - if (dx > 0) { - return groupD8.E; - } - return groupD8.W; - } - else if (dy > 0) { - if (dx > 0) { - return groupD8.SE; - } - return groupD8.SW; - } - else if (dx > 0) { - return groupD8.NE; - } - return groupD8.NW; - }, + BitmapFont.defaultOptions = { + resolution: 1, + textureWidth: 512, + textureHeight: 512, + padding: 4, + chars: BitmapFont.ALPHANUMERIC, + }; /** - * Helps sprite to compensate texture packer rotation. + * Collection of available/installed fonts. * - * @memberof PIXI.groupD8 - * @param {PIXI.Matrix} matrix - sprite world matrix - * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use. - * @param {number} tx - sprite anchoring - * @param {number} ty - sprite anchoring + * @readonly + * @static + * @member {Object.} */ - matrixAppendRotationInv: function (matrix, rotation, tx, ty) { - if (tx === void 0) { tx = 0; } - if (ty === void 0) { ty = 0; } - // Packer used "rotation", we use "inv(rotation)" - var mat = rotationMatrices[groupD8.inv(rotation)]; - mat.tx = tx; - mat.ty = ty; - matrix.append(mat); - }, -}; + BitmapFont.available = {}; + return BitmapFont; +}()); +/** + * @memberof PIXI + * @interface IBitmapFontOptions + * @property {string | string[] | string[][]} [chars=PIXI.BitmapFont.ALPHANUMERIC] - the character set to generate + * @property {number} [resolution=1] - the resolution for rendering + * @property {number} [padding=4] - the padding between glyphs in the atlas + * @property {number} [textureWidth=512] - the width of the texture atlas + * @property {number} [textureHeight=512] - the height of the texture atlas + */ +var pageMeshDataPool = []; +var charRenderDataPool = []; /** - * Transform that takes care about its versions + * A BitmapText object will create a line or multiple lines of text using bitmap font. + * + * The primary advantage of this class over Text is that all of your textures are pre-generated and loading, + * meaning that rendering is fast, and changing text has no performance implications. + * + * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters. + * + * To split a line you can use '\n', '\r' or '\r\n' in your string. + * + * PixiJS can auto-generate fonts on-the-fly using BitmapFont or use fnt files provided by: + * http://www.angelcode.com/products/bmfont/ for Windows or + * http://www.bmglyph.com/ for Mac. + * + * A BitmapText can only be created when the font is loaded. + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` * * @class + * @extends PIXI.Container * @memberof PIXI */ -var Transform = /** @class */ (function () { - function Transform() { - /** - * The world transformation matrix. - * - * @member {PIXI.Matrix} - */ - this.worldTransform = new Matrix(); +var BitmapText = /** @class */ (function (_super) { + __extends(BitmapText, _super); + /** + * @param {string} text - A string that you would like the text to display. + * @param {object} style - The style parameters. + * @param {string} style.fontName - The installed BitmapFont name. + * @param {number} [style.fontSize] - The size of the font in pixels, e.g. 24. If undefined, + *. this will default to the BitmapFont size. + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text. + * @param {number} [style.tint=0xFFFFFF] - The tint color. + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters. + * @param {number} [style.maxWidth=0] - The max width of the text before line wrapping. + */ + function BitmapText(text, style) { + if (style === void 0) { style = {}; } + var _this = _super.call(this) || this; + _this._tint = 0xFFFFFF; + if (style.font) { + utils.deprecation('5.3.0', 'PIXI.BitmapText constructor style.font property is deprecated.'); + _this._upgradeStyle(style); + } + // Apply the defaults + var _a = Object.assign({}, BitmapText.styleDefaults, style), align = _a.align, tint = _a.tint, maxWidth = _a.maxWidth, letterSpacing = _a.letterSpacing, fontName = _a.fontName, fontSize = _a.fontSize; + if (!BitmapFont.available[fontName]) { + throw new Error("Missing BitmapFont \"" + fontName + "\""); + } /** - * The local transformation matrix. + * Collection of page mesh data. * - * @member {PIXI.Matrix} + * @member {object} + * @private */ - this.localTransform = new Matrix(); + _this._activePagesMeshData = []; /** - * The coordinate of the object relative to the local coordinates of the parent. + * Private tracker for the width of the overall text * - * @member {PIXI.ObservablePoint} + * @member {number} + * @private */ - this.position = new ObservablePoint(this.onChange, this, 0, 0); + _this._textWidth = 0; /** - * The scale factor of the object. + * Private tracker for the height of the overall text * - * @member {PIXI.ObservablePoint} + * @member {number} + * @private */ - this.scale = new ObservablePoint(this.onChange, this, 1, 1); + _this._textHeight = 0; /** - * The pivot point of the displayObject that it rotates around. + * Private tracker for the current text align. * - * @member {PIXI.ObservablePoint} + * @member {string} + * @private */ - this.pivot = new ObservablePoint(this.onChange, this, 0, 0); + _this._align = align; /** - * The skew amount, on the x and y axis. + * Private tracker for the current tint. * - * @member {PIXI.ObservablePoint} + * @member {number} + * @private */ - this.skew = new ObservablePoint(this.updateSkew, this, 0, 0); + _this._tint = tint; /** - * The rotation amount. + * Private tracker for the current font name. * - * @protected - * @member {number} + * @member {string} + * @private */ - this._rotation = 0; + _this._fontName = fontName; /** - * The X-coordinate value of the normalized local X axis, - * the first column of the local transformation matrix without a scale. + * Private tracker for the current font size. * - * @protected * @member {number} + * @private */ - this._cx = 1; + _this._fontSize = fontSize || BitmapFont.available[fontName].size; /** - * The Y-coordinate value of the normalized local X axis, - * the first column of the local transformation matrix without a scale. + * Private tracker for the current text. * - * @protected - * @member {number} + * @member {string} + * @private */ - this._sx = 0; + _this._text = text; /** - * The X-coordinate value of the normalized local Y axis, - * the second column of the local transformation matrix without a scale. + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 * - * @protected * @member {number} + * @private */ - this._cy = 0; + _this._maxWidth = maxWidth; /** - * The Y-coordinate value of the normalized local Y axis, - * the second column of the local transformation matrix without a scale. + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. (Internally used) * - * @protected * @member {number} + * @private */ - this._sy = 1; + _this._maxLineHeight = 0; /** - * The locally unique ID of the local transform. - * - * @protected + * Letter spacing. This is useful for setting the space between characters. * @member {number} + * @private */ - this._localID = 0; + _this._letterSpacing = letterSpacing; /** - * The locally unique ID of the local transform - * used to calculate the current local transformation matrix. + * Text anchor. read-only * - * @protected - * @member {number} + * @member {PIXI.ObservablePoint} + * @private */ - this._currentLocalID = 0; + _this._anchor = new math.ObservablePoint(function () { _this.dirty = true; }, _this, 0, 0); /** - * The locally unique ID of the world transform. + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} * - * @protected - * @member {number} + * @member {boolean} + * @default PIXI.settings.ROUND_PIXELS */ - this._worldID = 0; + _this.roundPixels = settings.settings.ROUND_PIXELS; /** - * The locally unique ID of the parent's world transform - * used to calculate the current world transformation matrix. + * Set to `true` if the BitmapText needs to be redrawn. * - * @protected - * @member {number} + * @member {boolean} */ - this._parentID = 0; + _this.dirty = true; + return _this; } /** - * Called when a value changes. - * - * @protected - */ - Transform.prototype.onChange = function () { - this._localID++; - }; - /** - * Called when the skew or the rotation changes. - * - * @protected + * Renders text and updates it when needed. This should only be called + * if the BitmapFont is regenerated. */ - Transform.prototype.updateSkew = function () { - this._cx = Math.cos(this._rotation + this.skew.y); - this._sx = Math.sin(this._rotation + this.skew.y); - this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2 - this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2 - this._localID++; + BitmapText.prototype.updateText = function () { + var _a; + var data = BitmapFont.available[this._fontName]; + var scale = this._fontSize / data.size; + var pos = new math.Point(); + var chars = []; + var lineWidths = []; + var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' '; + var textLength = text.length; + var maxWidth = this._maxWidth * data.size / this._fontSize; + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastBreakPos = -1; + var lastBreakWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + for (var i = 0; i < textLength; i++) { + var charCode = text.charCodeAt(i); + var char = text.charAt(i); + if ((/(?:\s)/).test(char)) { + lastBreakPos = i; + lastBreakWidth = lastLineWidth; + } + if (char === '\r' || char === '\n') { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + ++line; + ++spacesRemoved; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + var charData = data.chars[charCode]; + if (!charData) { + continue; + } + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + var charRenderData = charRenderDataPool.pop() || { + texture: core.Texture.EMPTY, + line: 0, + charCode: 0, + position: new math.Point(), + }; + charRenderData.texture = charData.texture; + charRenderData.line = line; + charRenderData.charCode = charCode; + charRenderData.position.x = pos.x + charData.xOffset + (this._letterSpacing / 2); + charRenderData.position.y = pos.y + charData.yOffset; + chars.push(charRenderData); + pos.x += charData.xAdvance + this._letterSpacing; + lastLineWidth = pos.x; + maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); + prevCharCode = charCode; + if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { + ++spacesRemoved; + utils.removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); + i = lastBreakPos; + lastBreakPos = -1; + lineWidths.push(lastBreakWidth); + maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); + line++; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + } + } + var lastChar = text.charAt(text.length - 1); + if (lastChar !== '\r' && lastChar !== '\n') { + if ((/(?:\s)/).test(lastChar)) { + lastLineWidth = lastBreakWidth; + } + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + } + var lineAlignOffsets = []; + for (var i = 0; i <= line; i++) { + var alignOffset = 0; + if (this._align === 'right') { + alignOffset = maxLineWidth - lineWidths[i]; + } + else if (this._align === 'center') { + alignOffset = (maxLineWidth - lineWidths[i]) / 2; + } + lineAlignOffsets.push(alignOffset); + } + var lenChars = chars.length; + var pagesMeshData = {}; + var newPagesMeshData = []; + var activePagesMeshData = this._activePagesMeshData; + for (var i = 0; i < activePagesMeshData.length; i++) { + pageMeshDataPool.push(activePagesMeshData[i]); + } + for (var i = 0; i < lenChars; i++) { + var texture = chars[i].texture; + var baseTextureUid = texture.baseTexture.uid; + if (!pagesMeshData[baseTextureUid]) { + var pageMeshData = pageMeshDataPool.pop(); + if (!pageMeshData) { + var geometry = new mesh.MeshGeometry(); + var material = new mesh.MeshMaterial(core.Texture.EMPTY); + var mesh$1 = new mesh.Mesh(geometry, material); + pageMeshData = { + index: 0, + indexCount: 0, + vertexCount: 0, + uvsCount: 0, + total: 0, + mesh: mesh$1, + vertices: null, + uvs: null, + indices: null, + }; + } + // reset data.. + pageMeshData.index = 0; + pageMeshData.indexCount = 0; + pageMeshData.vertexCount = 0; + pageMeshData.uvsCount = 0; + pageMeshData.total = 0; + // TODO need to get page texture here somehow.. + pageMeshData.mesh.texture = new core.Texture(texture.baseTexture); + pageMeshData.mesh.tint = this._tint; + newPagesMeshData.push(pageMeshData); + pagesMeshData[baseTextureUid] = pageMeshData; + } + pagesMeshData[baseTextureUid].total++; + } + // lets find any previously active pageMeshDatas that are no longer required for + // the updated text (if any), removed and return them to the pool. + for (var i = 0; i < activePagesMeshData.length; i++) { + if (newPagesMeshData.indexOf(activePagesMeshData[i]) === -1) { + this.removeChild(activePagesMeshData[i].mesh); + } + } + // next lets add any new meshes, that have not yet been added to this BitmapText + // we only add if its not already a child of this BitmapObject + for (var i = 0; i < newPagesMeshData.length; i++) { + if (newPagesMeshData[i].mesh.parent !== this) { + this.addChild(newPagesMeshData[i].mesh); + } + } + // active page mesh datas are set to be the new pages added. + this._activePagesMeshData = newPagesMeshData; + for (var i in pagesMeshData) { + var pageMeshData = pagesMeshData[i]; + var total = pageMeshData.total; + // lets only allocate new buffers if we can fit the new text in the current ones.. + // unless that is, we will be batching. Currently batching dose not respect the size property of mesh + if (!(((_a = pageMeshData.indices) === null || _a === void 0 ? void 0 : _a.length) > 6 * total) || pageMeshData.vertices.length < mesh.Mesh.BATCHABLE_SIZE * 2) { + pageMeshData.vertices = new Float32Array(4 * 2 * total); + pageMeshData.uvs = new Float32Array(4 * 2 * total); + pageMeshData.indices = new Uint16Array(6 * total); + } + // as a buffer maybe bigger than the current word, we set the size of the meshMaterial + // to match the number of letters needed + pageMeshData.mesh.size = 6 * total; + } + for (var i = 0; i < lenChars; i++) { + var char = chars[i]; + var xPos = (char.position.x + lineAlignOffsets[char.line]) * scale; + var yPos = char.position.y * scale; + var texture = char.texture; + var pageMesh = pagesMeshData[texture.baseTexture.uid]; + var textureFrame = texture.frame; + var textureUvs = texture._uvs; + var index = pageMesh.index++; + pageMesh.indices[(index * 6) + 0] = 0 + (index * 4); + pageMesh.indices[(index * 6) + 1] = 1 + (index * 4); + pageMesh.indices[(index * 6) + 2] = 2 + (index * 4); + pageMesh.indices[(index * 6) + 3] = 0 + (index * 4); + pageMesh.indices[(index * 6) + 4] = 2 + (index * 4); + pageMesh.indices[(index * 6) + 5] = 3 + (index * 4); + pageMesh.vertices[(index * 8) + 0] = xPos; + pageMesh.vertices[(index * 8) + 1] = yPos; + pageMesh.vertices[(index * 8) + 2] = xPos + (textureFrame.width * scale); + pageMesh.vertices[(index * 8) + 3] = yPos; + pageMesh.vertices[(index * 8) + 4] = xPos + (textureFrame.width * scale); + pageMesh.vertices[(index * 8) + 5] = yPos + (textureFrame.height * scale); + pageMesh.vertices[(index * 8) + 6] = xPos; + pageMesh.vertices[(index * 8) + 7] = yPos + (textureFrame.height * scale); + pageMesh.uvs[(index * 8) + 0] = textureUvs.x0; + pageMesh.uvs[(index * 8) + 1] = textureUvs.y0; + pageMesh.uvs[(index * 8) + 2] = textureUvs.x1; + pageMesh.uvs[(index * 8) + 3] = textureUvs.y1; + pageMesh.uvs[(index * 8) + 4] = textureUvs.x2; + pageMesh.uvs[(index * 8) + 5] = textureUvs.y2; + pageMesh.uvs[(index * 8) + 6] = textureUvs.x3; + pageMesh.uvs[(index * 8) + 7] = textureUvs.y3; + } + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + for (var i in pagesMeshData) { + var pageMeshData = pagesMeshData[i]; + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + var vertexCount = 0; + var anchorOffsetX = this._textWidth * this.anchor.x; + var anchorOffsetY = this._textHeight * this.anchor.y; + for (var i_1 = 0; i_1 < pageMeshData.total; i_1++) { + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + } + } + this._maxLineHeight = maxLineHeight * scale; + var vertexBuffer = pageMeshData.mesh.geometry.getBuffer('aVertexPosition'); + var textureBuffer = pageMeshData.mesh.geometry.getBuffer('aTextureCoord'); + var indexBuffer = pageMeshData.mesh.geometry.getIndex(); + vertexBuffer.data = pageMeshData.vertices; + textureBuffer.data = pageMeshData.uvs; + indexBuffer.data = pageMeshData.indices; + vertexBuffer.update(); + textureBuffer.update(); + indexBuffer.update(); + } + for (var i = 0; i < chars.length; i++) { + charRenderDataPool.push(chars[i]); + } }; /** - * Updates the local transformation matrix. + * Updates the transform of this object + * + * @private */ - Transform.prototype.updateLocalTransform = function () { - var lt = this.localTransform; - if (this._localID !== this._currentLocalID) { - // get the matrix values of the displayobject based on its transform properties.. - lt.a = this._cx * this.scale.x; - lt.b = this._sx * this.scale.x; - lt.c = this._cy * this.scale.y; - lt.d = this._sy * this.scale.y; - lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); - lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); - this._currentLocalID = this._localID; - // force an update.. - this._parentID = -1; - } + BitmapText.prototype.updateTransform = function () { + this.validate(); + this.containerUpdateTransform(); }; /** - * Updates the local and the world transformation matrices. + * Validates text before calling parent's getLocalBounds * - * @param {PIXI.Transform} parentTransform - The parent transform + * @return {PIXI.Rectangle} The rectangular bounding area */ - Transform.prototype.updateTransform = function (parentTransform) { - var lt = this.localTransform; - if (this._localID !== this._currentLocalID) { - // get the matrix values of the displayobject based on its transform properties.. - lt.a = this._cx * this.scale.x; - lt.b = this._sx * this.scale.x; - lt.c = this._cy * this.scale.y; - lt.d = this._sy * this.scale.y; - lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); - lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); - this._currentLocalID = this._localID; - // force an update.. - this._parentID = -1; - } - if (this._parentID !== parentTransform._worldID) { - // concat the parent matrix with the objects transform. - var pt = parentTransform.worldTransform; - var wt = this.worldTransform; - wt.a = (lt.a * pt.a) + (lt.b * pt.c); - wt.b = (lt.a * pt.b) + (lt.b * pt.d); - wt.c = (lt.c * pt.a) + (lt.d * pt.c); - wt.d = (lt.c * pt.b) + (lt.d * pt.d); - wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx; - wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty; - this._parentID = parentTransform._worldID; - // update the id of the transform.. - this._worldID++; - } + BitmapText.prototype.getLocalBounds = function () { + this.validate(); + return _super.prototype.getLocalBounds.call(this); }; /** - * Decomposes a matrix and sets the transforms properties based on it. + * Updates text when needed * - * @param {PIXI.Matrix} matrix - The matrix to decompose + * @private */ - Transform.prototype.setFromMatrix = function (matrix) { - matrix.decompose(this); - this._localID++; + BitmapText.prototype.validate = function () { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } }; - Object.defineProperty(Transform.prototype, "rotation", { + Object.defineProperty(BitmapText.prototype, "tint", { /** - * The rotation of the object in radians. + * The tint of the BitmapText object. * * @member {number} + * @default 0xffffff */ get: function () { - return this._rotation; + return this._tint; }, set: function (value) { - if (this._rotation !== value) { - this._rotation = value; - this.updateSkew(); + if (this._tint === value) + { return; } + this._tint = value; + for (var i = 0; i < this._activePagesMeshData.length; i++) { + this._activePagesMeshData[i].mesh.tint = value; } }, - enumerable: true, + enumerable: false, configurable: true }); - /** - * A default (identity) transform - * - * @static - * @constant - * @member {PIXI.Transform} - */ - Transform.IDENTITY = new Transform(); - return Transform; -}()); - -/** - * Size object, contains width and height - * - * @memberof PIXI - * @typedef {object} ISize - * @property {number} width - Width component - * @property {number} height - Height component - */ -/** - * Rectangle object is an area defined by its position, as indicated by its top-left corner - * point (x, y) and by its width and its height. - * - * @class - * @memberof PIXI - */ -var Rectangle = /** @class */ (function () { - /** - * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle - * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle - * @param {number} [width=0] - The overall width of this rectangle - * @param {number} [height=0] - The overall height of this rectangle - */ - function Rectangle(x, y, width, height) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (width === void 0) { width = 0; } - if (height === void 0) { height = 0; } + Object.defineProperty(BitmapText.prototype, "align", { /** - * @member {number} - * @default 0 + * The alignment of the BitmapText object. + * + * @member {string} + * @default 'left' */ - this.x = Number(x); + get: function () { + return this._align; + }, + set: function (value) { + if (this._align !== value) { + this._align = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "fontName", { /** - * @member {number} - * @default 0 + * The name of the BitmapFont. + * + * @member {string} */ - this.y = Number(y); + get: function () { + return this._fontName; + }, + set: function (value) { + if (!BitmapFont.available[value]) { + throw new Error("Missing BitmapFont \"" + value + "\""); + } + if (this._fontName !== value) { + this._fontName = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "fontSize", { /** + * The size of the font to display. + * * @member {number} - * @default 0 */ - this.width = Number(width); + get: function () { + return this._fontSize; + }, + set: function (value) { + if (this._fontSize !== value) { + this._fontSize = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "anchor", { /** - * @member {number} - * @default 0 + * The anchor sets the origin point of the text. + * + * The default is `(0,0)`, this means the text's origin is the top left. + * + * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. + * + * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. + * + * @member {PIXI.Point | number} */ - this.height = Number(height); + get: function () { + return this._anchor; + }, + set: function (value) { + if (typeof value === 'number') { + this._anchor.set(value); + } + else { + this._anchor.copyFrom(value); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "text", { /** - * The type of the object, mainly used to avoid `instanceof` checks + * The text of the BitmapText object. * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.RECT - * @see PIXI.SHAPES + * @member {string} */ - this.type = exports.SHAPES.RECT; - } - Object.defineProperty(Rectangle.prototype, "left", { + get: function () { + return this._text; + }, + set: function (text) { + text = String(text === null || text === undefined ? '' : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "maxWidth", { /** - * returns the left edge of the rectangle + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting the value to 0. * * @member {number} */ get: function () { - return this.x; + return this._maxWidth; }, - enumerable: true, + set: function (value) { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + }, + enumerable: false, configurable: true }); - Object.defineProperty(Rectangle.prototype, "right", { + Object.defineProperty(BitmapText.prototype, "maxLineHeight", { /** - * returns the right edge of the rectangle + * The max line height. This is useful when trying to use the total height of the Text, + * i.e. when trying to vertically align. * * @member {number} + * @readonly */ get: function () { - return this.x + this.width; + this.validate(); + return this._maxLineHeight; }, - enumerable: true, + enumerable: false, configurable: true }); - Object.defineProperty(Rectangle.prototype, "top", { + Object.defineProperty(BitmapText.prototype, "textWidth", { /** - * returns the top edge of the rectangle + * The width of the overall text, different from fontSize, + * which is defined in the style object. * * @member {number} + * @readonly */ get: function () { - return this.y; + this.validate(); + return this._textWidth; }, - enumerable: true, + enumerable: false, configurable: true }); - Object.defineProperty(Rectangle.prototype, "bottom", { + Object.defineProperty(BitmapText.prototype, "letterSpacing", { /** - * returns the bottom edge of the rectangle + * Additional space between characters. * * @member {number} */ get: function () { - return this.y + this.height; + return this._letterSpacing; }, - enumerable: true, + set: function (value) { + if (this._letterSpacing !== value) { + this._letterSpacing = value; + this.dirty = true; + } + }, + enumerable: false, configurable: true }); - Object.defineProperty(Rectangle, "EMPTY", { + Object.defineProperty(BitmapText.prototype, "textHeight", { /** - * A constant empty rectangle. + * The height of the overall text, different from fontSize, + * which is defined in the style object. * - * @static - * @constant - * @member {PIXI.Rectangle} - * @return {PIXI.Rectangle} An empty rectangle + * @member {number} + * @readonly */ get: function () { - return new Rectangle(0, 0, 0, 0); + this.validate(); + return this._textHeight; }, - enumerable: true, + enumerable: false, configurable: true }); /** - * Creates a clone of this Rectangle - * - * @return {PIXI.Rectangle} a copy of the rectangle - */ - Rectangle.prototype.clone = function () { - return new Rectangle(this.x, this.y, this.width, this.height); - }; - /** - * Copies another rectangle to this one. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to copy from. - * @return {PIXI.Rectangle} Returns itself. - */ - Rectangle.prototype.copyFrom = function (rectangle) { - this.x = rectangle.x; - this.y = rectangle.y; - this.width = rectangle.width; - this.height = rectangle.height; - return this; - }; - /** - * Copies this rectangle to another one. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to copy to. - * @return {PIXI.Rectangle} Returns given parameter. - */ - Rectangle.prototype.copyTo = function (rectangle) { - rectangle.x = this.x; - rectangle.y = this.y; - rectangle.width = this.width; - rectangle.height = this.height; - return rectangle; - }; - /** - * Checks whether the x and y coordinates given are contained within this Rectangle + * For backward compatibility, convert old style.font constructor param to fontName & fontSize properties. * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this Rectangle + * @private + * @deprecated since 5.3.0 */ - Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - if (x >= this.x && x < this.x + this.width) { - if (y >= this.y && y < this.y + this.height) { - return true; + BitmapText.prototype._upgradeStyle = function (style) { + if (typeof style.font === 'string') { + var valueSplit = style.font.split(' '); + style.fontName = valueSplit.length === 1 + ? valueSplit[0] + : valueSplit.slice(1).join(' '); + if (valueSplit.length >= 2) { + style.fontSize = parseInt(valueSplit[0], 10); } } - return false; - }; - /** - * Pads the rectangle making it grow in all directions. - * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. - * - * @param {number} [paddingX=0] - The horizontal padding amount. - * @param {number} [paddingY=0] - The vertical padding amount. - * @return {PIXI.Rectangle} Returns itself. - */ - Rectangle.prototype.pad = function (paddingX, paddingY) { - if (paddingX === void 0) { paddingX = 0; } - if (paddingY === void 0) { paddingY = paddingX; } - this.x -= paddingX; - this.y -= paddingY; - this.width += paddingX * 2; - this.height += paddingY * 2; - return this; - }; - /** - * Fits this rectangle around the passed one. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to fit. - * @return {PIXI.Rectangle} Returns itself. - */ - Rectangle.prototype.fit = function (rectangle) { - var x1 = Math.max(this.x, rectangle.x); - var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); - var y1 = Math.max(this.y, rectangle.y); - var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); - this.x = x1; - this.width = Math.max(x2 - x1, 0); - this.y = y1; - this.height = Math.max(y2 - y1, 0); - return this; + else { + style.fontName = style.font.name; + style.fontSize = typeof style.font.size === 'number' + ? style.font.size + : parseInt(style.font.size, 10); + } }; /** - * Enlarges rectangle that way its corners lie on grid + * Register a bitmap font with data and a texture. * - * @param {number} [resolution=1] resolution - * @param {number} [eps=0.001] precision - * @return {PIXI.Rectangle} Returns itself. + * @deprecated since 5.3.0 + * @see PIXI.BitmapFont.install + * @static */ - Rectangle.prototype.ceil = function (resolution, eps) { - if (resolution === void 0) { resolution = 1; } - if (eps === void 0) { eps = 0.001; } - var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; - var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; - this.x = Math.floor((this.x + eps) * resolution) / resolution; - this.y = Math.floor((this.y + eps) * resolution) / resolution; - this.width = x2 - this.x; - this.height = y2 - this.y; - return this; + BitmapText.registerFont = function (data, textures) { + utils.deprecation('5.3.0', 'PIXI.BitmapText.registerFont is deprecated, use PIXI.BitmapFont.install'); + return BitmapFont.install(data, textures); }; - /** - * Enlarges this rectangle to include the passed rectangle. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to include. - * @return {PIXI.Rectangle} Returns itself. - */ - Rectangle.prototype.enlarge = function (rectangle) { - var x1 = Math.min(this.x, rectangle.x); - var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); - var y1 = Math.min(this.y, rectangle.y); - var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); - this.x = x1; - this.width = x2 - x1; - this.y = y1; - this.height = y2 - y1; - return this; + Object.defineProperty(BitmapText, "fonts", { + /** + * Get the list of installed fonts. + * + * @see PIXI.BitmapFont.available + * @deprecated since 5.3.0 + * @static + * @readonly + * @member {Object.} + */ + get: function () { + utils.deprecation('5.3.0', 'PIXI.BitmapText.fonts is deprecated, use PIXI.BitmapFont.available'); + return BitmapFont.available; + }, + enumerable: false, + configurable: true + }); + BitmapText.styleDefaults = { + align: 'left', + tint: 0xFFFFFF, + maxWidth: 0, + letterSpacing: 0, }; - return Rectangle; -}()); + return BitmapText; +}(display.Container)); /** - * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects. - * + * {@link PIXI.Loader Loader} middleware for loading + * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}. * @class * @memberof PIXI + * @implements PIXI.ILoaderPlugin */ -var Circle = /** @class */ (function () { - /** - * @param {number} [x=0] - The X coordinate of the center of this circle - * @param {number} [y=0] - The Y coordinate of the center of this circle - * @param {number} [radius=0] - The radius of the circle - */ - function Circle(x, y, radius) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (radius === void 0) { radius = 0; } - /** - * @member {number} - * @default 0 - */ - this.x = x; - /** - * @member {number} - * @default 0 - */ - this.y = y; - /** - * @member {number} - * @default 0 - */ - this.radius = radius; - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.CIRC - * @see PIXI.SHAPES - */ - this.type = exports.SHAPES.CIRC; +var BitmapFontLoader = /** @class */ (function () { + function BitmapFontLoader() { } /** - * Creates a clone of this Circle instance + * Called when the plugin is installed. * - * @return {PIXI.Circle} a copy of the Circle + * @see PIXI.Loader.registerPlugin */ - Circle.prototype.clone = function () { - return new Circle(this.x, this.y, this.radius); + BitmapFontLoader.add = function () { + loaders.LoaderResource.setExtensionXhrType('fnt', loaders.LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT); }; /** - * Checks whether the x and y coordinates given are contained within this circle - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this Circle + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param {PIXI.LoaderResource} resource + * @param {function} next */ - Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { - return false; + BitmapFontLoader.use = function (resource, next) { + var format = autoDetectFormat(resource.data); + // Resource was not recognised as any of the expected font data format + if (!format) { + next(); + return; + } + var baseUrl = BitmapFontLoader.getBaseUrl(this, resource); + var data = format.parse(resource.data); + var textures = {}; + // Handle completed, when the number of textures + // load is the same number as references in the fnt file + var completed = function (page) { + textures[page.metadata.pageFile] = page.texture; + if (Object.keys(textures).length === data.page.length) { + resource.bitmapFont = BitmapFont.install(data, textures); + next(); + } + }; + for (var i = 0; i < data.page.length; ++i) { + var pageFile = data.page[i].file; + var url = baseUrl + pageFile; + var exists = false; + // incase the image is loaded outside + // using the same loader, resource will be available + for (var name in this.resources) { + var bitmapResource = this.resources[name]; + if (bitmapResource.url === url) { + bitmapResource.metadata.pageFile = pageFile; + if (bitmapResource.texture) { + completed(bitmapResource); + } + else { + bitmapResource.onAfterMiddleware.add(completed); + } + exists = true; + break; + } + } + // texture is not loaded, we'll attempt to add + // it to the load and add the texture to the list + if (!exists) { + // Standard loading options for images + var options = { + crossOrigin: resource.crossOrigin, + loadType: loaders.LoaderResource.LOAD_TYPE.IMAGE, + metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), + parentResource: resource, + }; + this.add(url, options, completed); + } } - var r2 = this.radius * this.radius; - var dx = (this.x - x); - var dy = (this.y - y); - dx *= dx; - dy *= dy; - return (dx + dy <= r2); }; /** - * Returns the framing rectangle of the circle as a Rectangle object - * - * @return {PIXI.Rectangle} the framing rectangle - */ - Circle.prototype.getBounds = function () { - return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + * Get folder path from a resource + * @private + * @param {PIXI.Loader} loader + * @param {PIXI.LoaderResource} resource + * @return {string} + */ + BitmapFontLoader.getBaseUrl = function (loader, resource) { + var resUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : ''; + if (resource.isDataUrl) { + if (resUrl === '.') { + resUrl = ''; + } + if (loader.baseUrl && resUrl) { + // if baseurl has a trailing slash then add one to resUrl so the replace works below + if (loader.baseUrl.charAt(loader.baseUrl.length - 1) === '/') { + resUrl += '/'; + } + } + } + // remove baseUrl from resUrl + resUrl = resUrl.replace(loader.baseUrl, ''); + // if there is an resUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (resUrl && resUrl.charAt(resUrl.length - 1) !== '/') { + resUrl += '/'; + } + return resUrl; }; - return Circle; + /** + * Replacement for NodeJS's path.dirname + * @private + * @param {string} url - Path to get directory for + */ + BitmapFontLoader.dirname = function (url) { + var dir = url + .replace(/\\/g, '/') // convert windows notation to UNIX notation, URL-safe because it's a forbidden character + .replace(/\/$/, '') // replace trailing slash + .replace(/\/[^\/]*$/, ''); // remove everything after the last + // File request is relative, use current directory + if (dir === url) { + return '.'; + } + // Started with a slash + else if (dir === '') { + return '/'; + } + return dir; + }; + return BitmapFontLoader; }()); -/** - * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects. +exports.BitmapFont = BitmapFont; +exports.BitmapFontData = BitmapFontData; +exports.BitmapFontLoader = BitmapFontLoader; +exports.BitmapText = BitmapText; + + +},{"@pixi/core":8,"@pixi/display":9,"@pixi/loaders":19,"@pixi/math":20,"@pixi/mesh":22,"@pixi/settings":30,"@pixi/text":36,"@pixi/utils":38}],36:[function(require,module,exports){ +/*! + * @pixi/text - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @class + * @pixi/text is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var sprite = require('@pixi/sprite'); +var core = require('@pixi/core'); +var settings = require('@pixi/settings'); +var math = require('@pixi/math'); +var utils = require('@pixi/utils'); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient */ -var Ellipse = /** @class */ (function () { +(function (TEXT_GRADIENT) { + TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL"; + TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL"; +})(exports.TEXT_GRADIENT || (exports.TEXT_GRADIENT = {})); + +// disabling eslint for now, going to rewrite this in v5 +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: exports.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + whiteSpace: 'pre', + wordWrap: false, + wordWrapWidth: 100, + leading: 0, +}; +var genericFontFamilies = [ + 'serif', + 'sans-serif', + 'monospace', + 'cursive', + 'fantasy', + 'system-ui' ]; +/** + * A TextStyle Object contains information to decorate a Text objects. + * + * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it. + * + * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style). + * + * @class + * @memberof PIXI + */ +var TextStyle = /** @class */ (function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', '800' or '900') + * @param {number} [style.leading=0] - The space between lines + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" + * (creates a squared corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {string} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" + * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + this.styleID = 0; + this.reset(); + deepCopyProperties(this, style, style); + } /** - * @param {number} [x=0] - The X coordinate of the center of this ellipse - * @param {number} [y=0] - The Y coordinate of the center of this ellipse - * @param {number} [halfWidth=0] - The half width of this ellipse - * @param {number} [halfHeight=0] - The half height of this ellipse + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object */ - function Ellipse(x, y, halfWidth, halfHeight) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (halfWidth === void 0) { halfWidth = 0; } - if (halfHeight === void 0) { halfHeight = 0; } + TextStyle.prototype.clone = function () { + var clonedProperties = {}; + deepCopyProperties(clonedProperties, this, defaultStyle); + return new TextStyle(clonedProperties); + }; + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + TextStyle.prototype.reset = function () { + deepCopyProperties(this, defaultStyle, defaultStyle); + }; + Object.defineProperty(TextStyle.prototype, "align", { + /** + * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * + * @member {string} + */ + get: function () { + return this._align; + }, + set: function (align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "breakWords", { + /** + * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true + * + * @member {boolean} + */ + get: function () { + return this._breakWords; + }, + set: function (breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadow", { + /** + * Set a drop shadow for the text + * + * @member {boolean} + */ + get: function () { + return this._dropShadow; + }, + set: function (dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowAlpha", { /** + * Set alpha for the drop shadow + * * @member {number} - * @default 0 */ - this.x = x; + get: function () { + return this._dropShadowAlpha; + }, + set: function (dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowAngle", { /** + * Set a angle of the drop shadow + * * @member {number} - * @default 0 */ - this.y = y; + get: function () { + return this._dropShadowAngle; + }, + set: function (dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowBlur", { /** + * Set a shadow blur radius + * * @member {number} - * @default 0 */ - this.width = halfWidth; + get: function () { + return this._dropShadowBlur; + }, + set: function (dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowColor", { + /** + * A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * + * @member {string|number} + */ + get: function () { + return this._dropShadowColor; + }, + set: function (dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowDistance", { /** + * Set a distance of the drop shadow + * * @member {number} - * @default 0 */ - this.height = halfHeight; + get: function () { + return this._dropShadowDistance; + }, + set: function (dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fill", { /** - * The type of the object, mainly used to avoid `instanceof` checks + * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. + * Can be an array to create a gradient eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * + * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} + */ + get: function () { + return this._fill; + }, + set: function (fill) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + // TODO: Not sure if getColor works properly with CanvasGradient and/or CanvasPattern, can't pass in + // without casting here. + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fillGradientType", { + /** + * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. + * See {@link PIXI.TEXT_GRADIENT} * * @member {number} - * @readOnly - * @default PIXI.SHAPES.ELIP - * @see PIXI.SHAPES */ - this.type = exports.SHAPES.ELIP; - } - /** - * Creates a clone of this Ellipse instance - * - * @return {PIXI.Ellipse} a copy of the ellipse - */ - Ellipse.prototype.clone = function () { - return new Ellipse(this.x, this.y, this.width, this.height); - }; - /** - * Checks whether the x and y coordinates given are contained within this ellipse - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coords are within this ellipse - */ - Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - // normalize the coords to an ellipse with center 0,0 - var normx = ((x - this.x) / this.width); - var normy = ((y - this.y) / this.height); - normx *= normx; - normy *= normy; - return (normx + normy <= 1); - }; - /** - * Returns the framing rectangle of the ellipse as a Rectangle object - * - * @return {PIXI.Rectangle} the framing rectangle - */ - Ellipse.prototype.getBounds = function () { - return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); - }; - return Ellipse; -}()); - -/** - * A class to define a shape via user defined co-orinates. - * - * @class - * @memberof PIXI - */ -var Polygon = /** @class */ (function () { - /** - * @param {PIXI.Point[]|number[]|number[][]} points - This can be an array of Points - * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or - * the arguments passed can be all the points of the polygon e.g. - * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat - * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. - */ - function Polygon() { - var arguments$1 = arguments; - - var points = []; - for (var _i = 0; _i < arguments.length; _i++) { - points[_i] = arguments$1[_i]; - } - if (Array.isArray(points[0])) { - points = points[0]; - } - // if this is an array of points, convert it to a flat array of numbers - if (points[0] instanceof Point) { - points = points; - var p = []; - for (var i = 0, il = points.length; i < il; i++) { - p.push(points[i].x, points[i].y); + get: function () { + return this._fillGradientType; + }, + set: function (fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; } - points = p; - } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fillGradientStops", { /** - * An array of the points of this polygon + * If fill is an array of colours to create a gradient, this array can set the stop points + * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. * * @member {number[]} */ - this.points = points; + get: function () { + return this._fillGradientStops; + }, + set: function (fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontFamily", { /** - * The type of the object, mainly used to avoid `instanceof` checks + * The font family * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.POLY - * @see PIXI.SHAPES + * @member {string|string[]} */ - this.type = exports.SHAPES.POLY; + get: function () { + return this._fontFamily; + }, + set: function (fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontSize", { /** - * `false` after moveTo, `true` after `closePath`. In all other cases it is `true`. - * @member {boolean} - * @default true + * The font size + * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + * + * @member {number|string} */ - this.closeStroke = true; - } - /** - * Creates a clone of this polygon - * - * @return {PIXI.Polygon} a copy of the polygon - */ - Polygon.prototype.clone = function () { - var points = this.points.slice(); - var polygon = new Polygon(points); - polygon.closeStroke = this.closeStroke; - return polygon; - }; - /** - * Checks whether the x and y coordinates passed to this function are contained within this polygon - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this polygon - */ - Polygon.prototype.contains = function (x, y) { - var inside = false; - // use some raycasting to test hits - // https://github.com/substack/point-in-polygon/blob/master/index.js - var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { - var xi = this.points[i * 2]; - var yi = this.points[(i * 2) + 1]; - var xj = this.points[j * 2]; - var yj = this.points[(j * 2) + 1]; - var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi); - if (intersect) { - inside = !inside; + get: function () { + return this._fontSize; + }, + set: function (fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; } - } - return inside; - }; - return Polygon; -}()); - -/** - * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its - * top-left corner point (x, y) and by its width and its height and its radius. - * - * @class - * @memberof PIXI - */ -var RoundedRectangle = /** @class */ (function () { - /** - * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle - * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle - * @param {number} [width=0] - The overall width of this rounded rectangle - * @param {number} [height=0] - The overall height of this rounded rectangle - * @param {number} [radius=20] - Controls the radius of the rounded corners - */ - function RoundedRectangle(x, y, width, height, radius) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (width === void 0) { width = 0; } - if (height === void 0) { height = 0; } - if (radius === void 0) { radius = 20; } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontStyle", { + /** + * The font style + * ('normal', 'italic' or 'oblique') + * + * @member {string} + */ + get: function () { + return this._fontStyle; + }, + set: function (fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontVariant", { + /** + * The font variant + * ('normal' or 'small-caps') + * + * @member {string} + */ + get: function () { + return this._fontVariant; + }, + set: function (fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontWeight", { + /** + * The font weight + * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * + * @member {string} + */ + get: function () { + return this._fontWeight; + }, + set: function (fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "letterSpacing", { /** + * The amount of spacing between letters, default is 0 + * * @member {number} - * @default 0 */ - this.x = x; + get: function () { + return this._letterSpacing; + }, + set: function (letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "lineHeight", { /** + * The line height, a number that represents the vertical space that a letter uses + * * @member {number} - * @default 0 */ - this.y = y; + get: function () { + return this._lineHeight; + }, + set: function (lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "leading", { /** + * The space between lines + * * @member {number} - * @default 0 */ - this.width = width; + get: function () { + return this._leading; + }, + set: function (leading) { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "lineJoin", { + /** + * The lineJoin property sets the type of corner created, it can resolve spiked text issues. + * Default is 'miter' (creates a sharp corner). + * + * @member {string} + */ + get: function () { + return this._lineJoin; + }, + set: function (lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "miterLimit", { /** + * The miter limit to use when using the 'miter' lineJoin mode + * This can reduce or increase the spikiness of rendered text. + * * @member {number} - * @default 0 */ - this.height = height; + get: function () { + return this._miterLimit; + }, + set: function (miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "padding", { /** + * Occasionally some fonts are cropped. Adding some padding will prevent this from happening + * by adding padding to all sides of the text. + * * @member {number} - * @default 20 */ - this.radius = radius; + get: function () { + return this._padding; + }, + set: function (padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "stroke", { /** - * The type of the object, mainly used to avoid `instanceof` checks + * A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * + * @member {string|number} + */ + get: function () { + return this._stroke; + }, + set: function (stroke) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "strokeThickness", { + /** + * A number that represents the thickness of the stroke. + * Default is 0 (no stroke) * * @member {number} - * @readonly - * @default PIXI.SHAPES.RREC - * @see PIXI.SHAPES */ - this.type = exports.SHAPES.RREC; - } - /** - * Creates a clone of this Rounded Rectangle - * - * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle - */ - RoundedRectangle.prototype.clone = function () { - return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); - }; + get: function () { + return this._strokeThickness; + }, + set: function (strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "textBaseline", { + /** + * The baseline of the text that is rendered. + * + * @member {string} + */ + get: function () { + return this._textBaseline; + }, + set: function (textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "trim", { + /** + * Trim transparent borders + * + * @member {boolean} + */ + get: function () { + return this._trim; + }, + set: function (trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "whiteSpace", { + /** + * How newlines and spaces should be handled. + * Default is 'pre' (preserve, preserve). + * + * value | New lines | Spaces + * --- | --- | --- + * 'normal' | Collapse | Collapse + * 'pre' | Preserve | Preserve + * 'pre-line' | Preserve | Collapse + * + * @member {string} + */ + get: function () { + return this._whiteSpace; + }, + set: function (whiteSpace) { + if (this._whiteSpace !== whiteSpace) { + this._whiteSpace = whiteSpace; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "wordWrap", { + /** + * Indicates if word wrap should be used + * + * @member {boolean} + */ + get: function () { + return this._wordWrap; + }, + set: function (wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "wordWrapWidth", { + /** + * The width at which text will wrap, it needs wordWrap to be set to true + * + * @member {number} + */ + get: function () { + return this._wordWrapWidth; + }, + set: function (wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); /** - * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * Generates a font style string to use for `TextMetrics.measureFont()`. * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + * @return {string} Font style string, for passing to `TextMetrics.measureFont()` */ - RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; + TextStyle.prototype.toFontString = function () { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = (typeof this.fontSize === 'number') ? this.fontSize + "px" : this.fontSize; + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { - if ((y >= this.y + this.radius && y <= this.y + this.height - this.radius) - || (x >= this.x + this.radius && x <= this.x + this.width - this.radius)) { - return true; - } - var dx = x - (this.x + this.radius); - var dy = y - (this.y + this.radius); - var radius2 = this.radius * this.radius; - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - dx = x - (this.x + this.width - this.radius); - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - dy = y - (this.y + this.height - this.radius); - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - dx = x - (this.x + this.radius); - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + // Check if font already contains strings + if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { + fontFamily = "\"" + fontFamily + "\""; } + fontFamilies[i] = fontFamily; } - return false; + return this.fontStyle + " " + this.fontVariant + " " + this.fontWeight + " " + fontSizeString + " " + fontFamilies.join(','); }; - return RoundedRectangle; + return TextStyle; }()); - /** - * Math classes and utilities mixed into PIXI namespace. - * - * @lends PIXI + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * @private + * @param {string|number} color + * @return {string} The color as a string. */ - -exports.Circle = Circle; -exports.DEG_TO_RAD = DEG_TO_RAD; -exports.Ellipse = Ellipse; -exports.Matrix = Matrix; -exports.ObservablePoint = ObservablePoint; -exports.PI_2 = PI_2; -exports.Point = Point; -exports.Polygon = Polygon; -exports.RAD_TO_DEG = RAD_TO_DEG; -exports.Rectangle = Rectangle; -exports.RoundedRectangle = RoundedRectangle; -exports.Transform = Transform; -exports.groupD8 = groupD8; - - -},{}],30:[function(require,module,exports){ -/*! - * @pixi/mesh-extras - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/mesh-extras is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license +function getSingleColor(color) { + if (typeof color === 'number') { + return utils.hex2string(color); + } + else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + return color; +} +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } + else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + return color; + } +} +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param {Array} array1 - First array to compare + * @param {Array} array2 - Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var mesh = require('@pixi/mesh'); -var constants = require('@pixi/constants'); -var core = require('@pixi/core'); - -var PlaneGeometry = /*@__PURE__*/(function (MeshGeometry) { - function PlaneGeometry(width, height, segWidth, segHeight) - { - if ( width === void 0 ) width = 100; - if ( height === void 0 ) height = 100; - if ( segWidth === void 0 ) segWidth = 10; - if ( segHeight === void 0 ) segHeight = 10; - - MeshGeometry.call(this); - - this.segWidth = segWidth; - this.segHeight = segHeight; - - this.width = width; - this.height = height; - - this.build(); +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; } - - if ( MeshGeometry ) PlaneGeometry.__proto__ = MeshGeometry; - PlaneGeometry.prototype = Object.create( MeshGeometry && MeshGeometry.prototype ); - PlaneGeometry.prototype.constructor = PlaneGeometry; - - /** - * Refreshes plane coordinates - * @private - */ - PlaneGeometry.prototype.build = function build () - { - var total = this.segWidth * this.segHeight; - var verts = []; - var uvs = []; - var indices = []; - - var segmentsX = this.segWidth - 1; - var segmentsY = this.segHeight - 1; - - var sizeX = (this.width) / segmentsX; - var sizeY = (this.height) / segmentsY; - - for (var i = 0; i < total; i++) - { - var x = (i % this.segWidth); - var y = ((i / this.segWidth) | 0); - - verts.push(x * sizeX, y * sizeY); - uvs.push(x / segmentsX, y / segmentsY); + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; } - - var totalSub = segmentsX * segmentsY; - - for (var i$1 = 0; i$1 < totalSub; i$1++) - { - var xpos = i$1 % segmentsX; - var ypos = (i$1 / segmentsX) | 0; - - var value = (ypos * this.segWidth) + xpos; - var value2 = (ypos * this.segWidth) + xpos + 1; - var value3 = ((ypos + 1) * this.segWidth) + xpos; - var value4 = ((ypos + 1) * this.segWidth) + xpos + 1; - - indices.push(value, value2, value3, - value2, value4, value3); + } + return true; +} +/** + * Utility function to ensure that object properties are copied by value, and not by reference + * @private + * @param {Object} target - Target object to copy properties into + * @param {Object} source - Source object for the properties to copy + * @param {string} propertyObj - Object containing properties names we want to loop over + */ +function deepCopyProperties(target, source, propertyObj) { + for (var prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); } - - this.buffers[0].data = new Float32Array(verts); - this.buffers[1].data = new Float32Array(uvs); - this.indexBuffer.data = new Uint16Array(indices); - - // ensure that the changes are uploaded - this.buffers[0].update(); - this.buffers[1].update(); - this.indexBuffer.update(); - }; - - return PlaneGeometry; -}(mesh.MeshGeometry)); + else { + target[prop] = source[prop]; + } + } +} /** - * RopeGeometry allows you to draw a geometry across several points and then manipulate these points. + * The TextMetrics object represents the measurement of a block of text with a specified style. * * ```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * const rope = new PIXI.RopeGeometry(100, points); + * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) + * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) * ``` * * @class - * @extends PIXI.MeshGeometry * @memberof PIXI - * */ -var RopeGeometry = /*@__PURE__*/(function (MeshGeometry) { - function RopeGeometry(width, points, textureScale) - { - if ( width === void 0 ) width = 200; - if ( textureScale === void 0 ) textureScale = 0; - - MeshGeometry.call(this, new Float32Array(points.length * 4), - new Float32Array(points.length * 4), - new Uint16Array((points.length - 1) * 6)); - +var TextMetrics = /** @class */ (function () { + /** + * @param {string} text - the text that was measured + * @param {PIXI.TextStyle} style - the style that was measured + * @param {number} width - the measured width of the text + * @param {number} height - the measured height of the text + * @param {string[]} lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param {number[]} lineWidths - an array of the line widths for each line matched to `lines` + * @param {number} lineHeight - the measured line height for this style + * @param {number} maxLineWidth - the maximum line width for all measured lines + * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { /** - * An array of points that determine the rope - * @member {PIXI.Point[]} + * The text that was measured + * + * @member {string} */ - this.points = points; - + this.text = text; /** - * The width (i.e., thickness) of the rope. + * The style that was measured + * + * @member {PIXI.TextStyle} + */ + this.style = style; + /** + * The measured width of the text + * * @member {number} - * @readOnly */ this.width = width; - /** - * Rope texture scale, if zero then the rope texture is stretched. + * The measured height of the text + * * @member {number} - * @readOnly */ - this.textureScale = textureScale; - - this.build(); + this.height = height; + /** + * An array of lines of the text broken by new lines and wrapping is specified in style + * + * @member {string[]} + */ + this.lines = lines; + /** + * An array of the line widths for each line matched to `lines` + * + * @member {number[]} + */ + this.lineWidths = lineWidths; + /** + * The measured line height for this style + * + * @member {number} + */ + this.lineHeight = lineHeight; + /** + * The maximum line width for all measured lines + * + * @member {number} + */ + this.maxLineWidth = maxLineWidth; + /** + * The font properties object from TextMetrics.measureFont + * + * @member {PIXI.IFontMetrics} + */ + this.fontProperties = fontProperties; } - - if ( MeshGeometry ) RopeGeometry.__proto__ = MeshGeometry; - RopeGeometry.prototype = Object.create( MeshGeometry && MeshGeometry.prototype ); - RopeGeometry.prototype.constructor = RopeGeometry; /** - * Refreshes Rope indices and uvs + * Measures the supplied string of text and returns a Rectangle. + * + * @param {string} text - the text to measure. + * @param {PIXI.TextStyle} style - the text style to use for measuring + * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {PIXI.TextMetrics} measured width and height of the text. + */ + TextMetrics.measureText = function (text, style, wordWrap, canvas) { + if (canvas === void 0) { canvas = TextMetrics._canvas; } + wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + // fallback in case UA disallow canvas data extraction + // (toDataURI, getImageData functions) + if (fontProperties.fontSize === 0) { + fontProperties.fontSize = style.fontSize; + fontProperties.ascent = style.fontSize; + } + var context = canvas.getContext('2d'); + context.font = font; + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + if (style.dropShadow) { + width += style.dropShadowDistance; + } + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + + ((lines.length - 1) * (lineHeight + style.leading)); + if (style.dropShadow) { + height += style.dropShadowDistance; + } + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + }; + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @param {PIXI.TextStyle} style - the style to use when wrapping + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {string} New string with new lines applied where required + */ + TextMetrics.wordWrap = function (text, style, canvas) { + if (canvas === void 0) { canvas = TextMetrics._canvas; } + var context = canvas.getContext('2d'); + var width = 0; + var line = ''; + var lines = ''; + var cache = {}; + var letterSpacing = style.letterSpacing, whiteSpace = style.whiteSpace; + // How to handle whitespaces + var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); + var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); + // whether or not spaces may be added to the beginning of lines + var canPrependSpaces = !collapseSpaces; + // There is letterSpacing after every char except the last one + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! + // so for convenience the above needs to be compared to width + 1 extra letterSpace + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ + // ________________________________________________ + // And then the final space is simply no appended to each line + var wordWrapWidth = style.wordWrapWidth + letterSpacing; + // break text into words, spaces and newline chars + var tokens = TextMetrics.tokenize(text); + for (var i = 0; i < tokens.length; i++) { + // get the word, space or newlineChar + var token = tokens[i]; + // if word is a new line + if (TextMetrics.isNewline(token)) { + // keep the new line + if (!collapseNewlines) { + lines += TextMetrics.addLine(line); + canPrependSpaces = !collapseSpaces; + line = ''; + width = 0; + continue; + } + // if we should collapse new lines + // we simply convert it into a space + token = ' '; + } + // if we should collapse repeated whitespaces + if (collapseSpaces) { + // check both this and the last tokens for spaces + var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); + var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); + if (currIsBreakingSpace && lastIsBreakingSpace) { + continue; + } + } + // get word width from cache if possible + var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); + // word is longer than desired bounds + if (tokenWidth > wordWrapWidth) { + // if we are not already at the beginning of a line + if (line !== '') { + // start newlines for overflow words + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + // break large word over multiple lines + if (TextMetrics.canBreakWords(token, style.breakWords)) { + // break word into characters + var characters = TextMetrics.wordWrapSplit(token); + // loop the characters + for (var j = 0; j < characters.length; j++) { + var char = characters[j]; + var k = 1; + // we are not at the end of the token + while (characters[j + k]) { + var nextChar = characters[j + k]; + var lastChar = char[char.length - 1]; + // should not split chars + if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { + // combine chars & move forward one + char += nextChar; + } + else { + break; + } + k++; + } + j += char.length - 1; + var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); + if (characterWidth + width > wordWrapWidth) { + lines += TextMetrics.addLine(line); + canPrependSpaces = false; + line = ''; + width = 0; + } + line += char; + width += characterWidth; + } + } + // run word out of the bounds + else { + // if there are words in this line already + // finish that line and start a new one + if (line.length > 0) { + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + var isLastToken = i === tokens.length - 1; + // give it its own line if it's not the end + lines += TextMetrics.addLine(token, !isLastToken); + canPrependSpaces = false; + line = ''; + width = 0; + } + } + // word could fit + else { + // word won't fit because of existing words + // start a new line + if (tokenWidth + width > wordWrapWidth) { + // if its a space we don't want it + canPrependSpaces = false; + // add a new line + lines += TextMetrics.addLine(line); + // start a new line + line = ''; + width = 0; + } + // don't add spaces to the beginning of lines + if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { + // add the word to the current line + line += token; + // update width counter + width += tokenWidth; + } + } + } + lines += TextMetrics.addLine(line, false); + return lines; + }; + /** + * Convienience function for logging each line added during the wordWrap + * method + * * @private + * @param {string} line - The line of text to add + * @param {boolean} newLine - Add new line character to end + * @return {string} A formatted line */ - RopeGeometry.prototype.build = function build () - { - var points = this.points; - - if (!points) { return; } - - var vertexBuffer = this.getBuffer('aVertexPosition'); - var uvBuffer = this.getBuffer('aTextureCoord'); - var indexBuffer = this.getIndex(); - - // if too little points, or texture hasn't got UVs set yet just move on. - if (points.length < 1) - { - return; + TextMetrics.addLine = function (line, newLine) { + if (newLine === void 0) { newLine = true; } + line = TextMetrics.trimRight(line); + line = (newLine) ? line + "\n" : line; + return line; + }; + /** + * Gets & sets the widths of calculated characters in a cache object + * + * @private + * @param {string} key - The key + * @param {number} letterSpacing - The letter spacing + * @param {object} cache - The cache + * @param {CanvasRenderingContext2D} context - The canvas context + * @return {number} The from cache. + */ + TextMetrics.getFromCache = function (key, letterSpacing, cache, context) { + var width = cache[key]; + if (width === undefined) { + var spacing = ((key.length) * letterSpacing); + width = context.measureText(key).width + spacing; + cache[key] = width; } - - // if the number of points has changed we will need to recreate the arraybuffers - if (vertexBuffer.data.length / 4 !== points.length) - { - vertexBuffer.data = new Float32Array(points.length * 4); - uvBuffer.data = new Float32Array(points.length * 4); - indexBuffer.data = new Uint16Array((points.length - 1) * 6); + return width; + }; + /** + * Determines whether we should collapse breaking spaces + * + * @private + * @param {string} whiteSpace - The TextStyle property whiteSpace + * @return {boolean} should collapse + */ + TextMetrics.collapseSpaces = function (whiteSpace) { + return (whiteSpace === 'normal' || whiteSpace === 'pre-line'); + }; + /** + * Determines whether we should collapse newLine chars + * + * @private + * @param {string} whiteSpace - The white space + * @return {boolean} should collapse + */ + TextMetrics.collapseNewlines = function (whiteSpace) { + return (whiteSpace === 'normal'); + }; + /** + * trims breaking whitespaces from string + * + * @private + * @param {string} text - The text + * @return {string} trimmed string + */ + TextMetrics.trimRight = function (text) { + if (typeof text !== 'string') { + return ''; } - - var uvs = uvBuffer.data; - var indices = indexBuffer.data; - - uvs[0] = 0; - uvs[1] = 0; - uvs[2] = 0; - uvs[3] = 1; - - var amount = 0; - var prev = points[0]; - var textureWidth = this.width * this.textureScale; - var total = points.length; // - 1; - - for (var i = 0; i < total; i++) - { - // time to do some smart drawing! - var index = i * 4; - - if (this.textureScale > 0) - { - // calculate pixel distance from previous point - var dx = prev.x - points[i].x; - var dy = prev.y - points[i].y; - var distance = Math.sqrt((dx * dx) + (dy * dy)); - - prev = points[i]; - amount += distance / textureWidth; + for (var i = text.length - 1; i >= 0; i--) { + var char = text[i]; + if (!TextMetrics.isBreakingSpace(char)) { + break; } - else - { - // stretch texture - amount = i / (total - 1); + text = text.slice(0, -1); + } + return text; + }; + /** + * Determines if char is a newline. + * + * @private + * @param {string} char - The character + * @return {boolean} True if newline, False otherwise. + */ + TextMetrics.isNewline = function (char) { + if (typeof char !== 'string') { + return false; + } + return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0); + }; + /** + * Determines if char is a breaking whitespace. + * + * @private + * @param {string} char - The character + * @return {boolean} True if whitespace, False otherwise. + */ + TextMetrics.isBreakingSpace = function (char) { + if (typeof char !== 'string') { + return false; + } + return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0); + }; + /** + * Splits a string into words, breaking-spaces and newLine characters + * + * @private + * @param {string} text - The text + * @return {string[]} A tokenized array + */ + TextMetrics.tokenize = function (text) { + var tokens = []; + var token = ''; + if (typeof text !== 'string') { + return tokens; + } + for (var i = 0; i < text.length; i++) { + var char = text[i]; + if (TextMetrics.isBreakingSpace(char) || TextMetrics.isNewline(char)) { + if (token !== '') { + tokens.push(token); + token = ''; + } + tokens.push(char); + continue; } - - uvs[index] = amount; - uvs[index + 1] = 0; - - uvs[index + 2] = amount; - uvs[index + 3] = 1; + token += char; } - - var indexCount = 0; - - for (var i$1 = 0; i$1 < total - 1; i$1++) - { - var index$1 = i$1 * 2; - - indices[indexCount++] = index$1; - indices[indexCount++] = index$1 + 1; - indices[indexCount++] = index$1 + 2; - - indices[indexCount++] = index$1 + 2; - indices[indexCount++] = index$1 + 1; - indices[indexCount++] = index$1 + 3; + if (token !== '') { + tokens.push(token); } - - // ensure that the changes are uploaded - uvBuffer.update(); - indexBuffer.update(); - - this.updateVertices(); + return tokens; }; - /** - * refreshes vertices of Rope mesh + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It allows one to customise which words should break + * Examples are if the token is CJK or numbers. + * It must return a boolean. + * + * @param {string} token - The token + * @param {boolean} breakWords - The style attr break words + * @return {boolean} whether to break word or not */ - RopeGeometry.prototype.updateVertices = function updateVertices () - { - var points = this.points; - - if (points.length < 1) - { - return; + TextMetrics.canBreakWords = function (_token, breakWords) { + return breakWords; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It allows one to determine whether a pair of characters + * should be broken by newlines + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * + * @param {string} char - The character + * @param {string} nextChar - The next character + * @param {string} token - The token/word the characters are from + * @param {number} index - The index in the token of the char + * @param {boolean} breakWords - The style attr break words + * @return {boolean} whether to break word or not + */ + TextMetrics.canBreakChars = function (_char, _nextChar, _token, _index, _breakWords) { + return true; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It is called when a token (usually a word) has to be split into separate pieces + * in order to determine the point to break a word. + * It must return an array of characters. + * + * @example + * // Correctly splits emojis, eg "🤪🤪" will result in two element array, each with one emoji. + * TextMetrics.wordWrapSplit = (token) => [...token]; + * + * @param {string} token - The token to split + * @return {string[]} The characters of the token + */ + TextMetrics.wordWrapSplit = function (token) { + return token.split(''); + }; + /** + * Calculates the ascent, descent and fontSize of a given font-style + * + * @static + * @param {string} font - String representing the style of the font + * @return {PIXI.IFontMetrics} Font properties object + */ + TextMetrics.measureFont = function (font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + var properties = { + ascent: 0, + descent: 0, + fontSize: 0, + }; + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + context.font = font; + var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; + var width = Math.ceil(context.measureText(metricsString).width); + var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); + var height = 2 * baseline; + baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; + canvas.width = width; + canvas.height = height; + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + context.font = font; + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(metricsString, 0, baseline); + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + var i = 0; + var idx = 0; + var stop = false; + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } + else { + break; + } } - - var lastPoint = points[0]; - var nextPoint; - var perpX = 0; - var perpY = 0; - - var vertices = this.buffers[0].data; - var total = points.length; - - for (var i = 0; i < total; i++) - { - var point = points[i]; - var index = i * 4; - - if (i < points.length - 1) - { - nextPoint = points[i + 1]; + properties.ascent = baseline - i; + idx = pixels - line; + stop = false; + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } } - else - { - nextPoint = point; + if (!stop) { + idx -= line; + } + else { + break; } - - perpY = -(nextPoint.x - lastPoint.x); - perpX = nextPoint.y - lastPoint.y; - - var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY)); - var num = this.textureScale > 0 ? this.textureScale * this.width / 2 : this.width / 2; - - perpX /= perpLength; - perpY /= perpLength; - - perpX *= num; - perpY *= num; - - vertices[index] = point.x + perpX; - vertices[index + 1] = point.y + perpY; - vertices[index + 2] = point.x - perpX; - vertices[index + 3] = point.y - perpY; - - lastPoint = point; } - - this.buffers[0].update(); + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + TextMetrics._fonts[font] = properties; + return properties; }; - - RopeGeometry.prototype.update = function update () - { - if (this.textureScale > 0) - { - this.build(); // we need to update UVs + /** + * Clear font metrics in metrics cache. + * + * @static + * @param {string} [font] - font name. If font name not set then clear cache for all fonts. + */ + TextMetrics.clearMetrics = function (font) { + if (font === void 0) { font = ''; } + if (font) { + delete TextMetrics._fonts[font]; } - else - { - this.updateVertices(); + else { + TextMetrics._fonts = {}; } }; - - return RopeGeometry; -}(mesh.MeshGeometry)); - + return TextMetrics; +}()); /** - * The rope allows you to draw a texture across several points and then manipulate these points - * - *```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points); - * ``` - * - * @class - * @extends PIXI.Mesh - * @memberof PIXI + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. * + * @typedef {object} FontMetrics + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + * @memberof PIXI.TextMetrics + * @private */ -var SimpleRope = /*@__PURE__*/(function (Mesh) { - function SimpleRope(texture, points, textureScale) - { - if ( textureScale === void 0 ) textureScale = 0; - - var ropeGeometry = new RopeGeometry(texture.height, points, textureScale); - var meshMaterial = new mesh.MeshMaterial(texture); - - if (textureScale > 0) - { - // attempt to set UV wrapping, will fail on non-power of two textures - texture.baseTexture.wrapMode = constants.WRAP_MODES.REPEAT; +var canvas = (function () { + try { + // OffscreenCanvas2D measureText can be up to 40% faster. + var c = new OffscreenCanvas(0, 0); + var context = c.getContext('2d'); + if (context && context.measureText) { + return c; } - Mesh.call(this, ropeGeometry, meshMaterial); - - /** - * re-calculate vertices by rope points each frame - * - * @member {boolean} - */ - this.autoUpdate = true; + return document.createElement('canvas'); } - - if ( Mesh ) SimpleRope.__proto__ = Mesh; - SimpleRope.prototype = Object.create( Mesh && Mesh.prototype ); - SimpleRope.prototype.constructor = SimpleRope; - - SimpleRope.prototype._render = function _render (renderer) - { - if (this.autoUpdate - || this.geometry.width !== this.shader.texture.height) - { - this.geometry.width = this.shader.texture.height; - this.geometry.update(); - } - - Mesh.prototype._render.call(this, renderer); - }; - - return SimpleRope; -}(mesh.Mesh)); - + catch (ex) { + return document.createElement('canvas'); + } +})(); +canvas.width = canvas.height = 10; /** - * The SimplePlane allows you to draw a texture across several points and then manipulate these points + * Cached canvas element for measuring text * - *```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points); - * ``` + * @memberof PIXI.TextMetrics + * @type {HTMLCanvasElement} + * @private + */ +TextMetrics._canvas = canvas; +/** + * Cache for context to use. * - * @class - * @extends PIXI.Mesh - * @memberof PIXI + * @memberof PIXI.TextMetrics + * @type {CanvasRenderingContext2D} + * @private + */ +TextMetrics._context = canvas.getContext('2d'); +/** + * Cache of {@see PIXI.TextMetrics.FontMetrics} objects. * + * @memberof PIXI.TextMetrics + * @type {Object} + * @private */ -var SimplePlane = /*@__PURE__*/(function (Mesh) { - function SimplePlane(texture, verticesX, verticesY) - { - var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY); - var meshMaterial = new mesh.MeshMaterial(core.Texture.WHITE); - - Mesh.call(this, planeGeometry, meshMaterial); - - // lets call the setter to ensure all necessary updates are performed - this.texture = texture; - } - - if ( Mesh ) SimplePlane.__proto__ = Mesh; - SimplePlane.prototype = Object.create( Mesh && Mesh.prototype ); - SimplePlane.prototype.constructor = SimplePlane; - - var prototypeAccessors = { texture: { configurable: true } }; - - /** - * Method used for overrides, to do something in case texture frame was changed. - * Meshes based on plane can override it and change more details based on texture. - */ - SimplePlane.prototype.textureUpdated = function textureUpdated () - { - this._textureID = this.shader.texture._updateID; - - this.geometry.width = this.shader.texture.width; - this.geometry.height = this.shader.texture.height; - - this.geometry.build(); - }; - - prototypeAccessors.texture.set = function (value) - { - // Track texture same way sprite does. - // For generated meshes like NineSlicePlane it can change the geometry. - // Unfortunately, this method might not work if you directly change texture in material. - - if (this.shader.texture === value) - { - return; - } - - this.shader.texture = value; - this._textureID = -1; - - if (value.baseTexture.valid) - { - this.textureUpdated(); - } - else - { - value.once('update', this.textureUpdated, this); - } - }; - - prototypeAccessors.texture.get = function () - { - return this.shader.texture; - }; - - SimplePlane.prototype._render = function _render (renderer) - { - if (this._textureID !== this.shader.texture._updateID) - { - this.textureUpdated(); - } - - Mesh.prototype._render.call(this, renderer); - }; - - Object.defineProperties( SimplePlane.prototype, prototypeAccessors ); - - return SimplePlane; -}(mesh.Mesh)); - +TextMetrics._fonts = {}; /** - * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments. - * For more robust customization, use {@link PIXI.Mesh}. + * String used for calculate font metrics. + * These characters are all tall to help calculate the height required for text. + * + * @static + * @memberof PIXI.TextMetrics + * @name METRICS_STRING + * @type {string} + * @default |ÉqÅ + */ +TextMetrics.METRICS_STRING = '|ÉqÅ'; +/** + * Baseline symbol for calculate font metrics. + * + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_SYMBOL + * @type {string} + * @default M + */ +TextMetrics.BASELINE_SYMBOL = 'M'; +/** + * Baseline multiplier for calculate font metrics. + * + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_MULTIPLIER + * @type {number} + * @default 1.4 + */ +TextMetrics.BASELINE_MULTIPLIER = 1.4; +/** + * Cache of new line chars. + * + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._newlines = [ + 0x000A, + 0x000D ]; +/** + * Cache of breaking spaces. + * + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._breakingSpaces = [ + 0x0009, + 0x0020, + 0x2000, + 0x2001, + 0x2002, + 0x2003, + 0x2004, + 0x2005, + 0x2006, + 0x2008, + 0x2009, + 0x200A, + 0x205F, + 0x3000 ]; +/** + * A number, or a string containing a number. * - * @class - * @extends PIXI.Mesh * @memberof PIXI + * @typedef IFontMetrics + * @property {number} ascent - Font ascent + * @property {number} descent - Font descent + * @property {number} fontSize - Font size */ -var SimpleMesh = /*@__PURE__*/(function (Mesh) { - function SimpleMesh(texture, vertices, uvs, indices, drawMode) - { - if ( texture === void 0 ) texture = core.Texture.EMPTY; - - var geometry = new mesh.MeshGeometry(vertices, uvs, indices); - - geometry.getBuffer('aVertexPosition').static = false; - - var meshMaterial = new mesh.MeshMaterial(texture); - - Mesh.call(this, geometry, meshMaterial, null, drawMode); - - /** - * upload vertices buffer each frame - * @member {boolean} - */ - this.autoUpdate = true; - } - - if ( Mesh ) SimpleMesh.__proto__ = Mesh; - SimpleMesh.prototype = Object.create( Mesh && Mesh.prototype ); - SimpleMesh.prototype.constructor = SimpleMesh; - - var prototypeAccessors = { vertices: { configurable: true } }; - - /** - * Collection of vertices data. - * @member {Float32Array} - */ - prototypeAccessors.vertices.get = function () - { - return this.geometry.getBuffer('aVertexPosition').data; - }; - prototypeAccessors.vertices.set = function (value) - { - this.geometry.getBuffer('aVertexPosition').data = value; - }; - - SimpleMesh.prototype._render = function _render (renderer) - { - if (this.autoUpdate) - { - this.geometry.getBuffer('aVertexPosition').update(); - } - - Mesh.prototype._render.call(this, renderer); - }; - - Object.defineProperties( SimpleMesh.prototype, prototypeAccessors ); - - return SimpleMesh; -}(mesh.Mesh)); - -var DEFAULT_BORDER_SIZE = 10; +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true, +}; /** - * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful - * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * A Text Object will create a line or multiple lines of text. * - *```js - * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15); - * ``` - *
- *      A                          B
- *    +---+----------------------+---+
- *  C | 1 |          2           | 3 |
- *    +---+----------------------+---+
- *    |   |                      |   |
- *    | 4 |          5           | 6 |
- *    |   |                      |   |
- *    +---+----------------------+---+
- *  D | 7 |          8           | 9 |
- *    +---+----------------------+---+
-
- *  When changing this objects width and/or height:
- *     areas 1 3 7 and 9 will remain unscaled.
- *     areas 2 and 8 will be stretched horizontally
- *     areas 4 and 6 will be stretched vertically
- *     area 5 will be stretched both horizontally and vertically
- * 
+ * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). + * + * The primary advantage of this class over BitmapText is that you have great control over the style of the next, + * which you can change at runtime. + * + * The primary disadvantages is that each piece of text has it's own texture, which can use more memory. + * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time. + * + * To split a line you can use '\n' in your text string, or, on the `style` object, + * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value. + * + * A Text can be created directly from a string and a style object, + * which can be generated [here](https://pixijs.io/pixi-text-style). + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` * * @class - * @extends PIXI.SimplePlane + * @extends PIXI.Sprite * @memberof PIXI - * */ -var NineSlicePlane = /*@__PURE__*/(function (SimplePlane) { - function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) - { - SimplePlane.call(this, core.Texture.WHITE, 4, 4); - - this._origWidth = texture.orig.width; - this._origHeight = texture.orig.height; - +var Text = /** @class */ (function (_super) { + __extends(Text, _super); + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + var _this = this; + var ownCanvas = false; + if (!canvas) { + canvas = document.createElement('canvas'); + ownCanvas = true; + } + canvas.width = 3; + canvas.height = 3; + var texture = core.Texture.from(canvas); + texture.orig = new math.Rectangle(); + texture.trim = new math.Rectangle(); + _this = _super.call(this, texture) || this; /** - * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * Keep track if this Text object created it's own canvas + * element (`true`) or uses the constructor argument (`false`). + * Used to workaround a GC issues with Safari < 13 when + * destroying Text. See `destroy` for more info. * - * @member {number} - * @override + * @member {boolean} + * @private */ - this._width = this._origWidth; - + _this._ownCanvas = ownCanvas; /** - * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * The canvas element that everything is drawn to * + * @member {HTMLCanvasElement} + */ + _this.canvas = canvas; + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + /** + * The resolution / device pixel ratio of the canvas. + * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. * @member {number} - * @override + * @default 1 */ - this._height = this._origHeight; - + _this._resolution = settings.settings.RESOLUTION; + _this._autoResolution = true; /** - * The width of the left column (a) + * Private tracker for the current text. * - * @member {number} + * @member {string} * @private */ - this._leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; - + _this._text = null; /** - * The width of the right column (b) + * Private tracker for the current style. * - * @member {number} + * @member {object} * @private */ - this._rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; - + _this._style = null; /** - * The height of the top row (c) + * Private listener to track style changes. * - * @member {number} + * @member {Function} * @private */ - this._topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; - + _this._styleListener = null; /** - * The height of the bottom row (d) + * Private tracker for the current font. * - * @member {number} + * @member {string} * @private */ - this._bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; - - // lets call the setter to ensure all necessary updates are performed - this.texture = texture; + _this._font = ''; + _this.text = text; + _this.style = style; + _this.localStyleID = -1; + return _this; } - - if ( SimplePlane ) NineSlicePlane.__proto__ = SimplePlane; - NineSlicePlane.prototype = Object.create( SimplePlane && SimplePlane.prototype ); - NineSlicePlane.prototype.constructor = NineSlicePlane; - - var prototypeAccessors = { vertices: { configurable: true },width: { configurable: true },height: { configurable: true },leftWidth: { configurable: true },rightWidth: { configurable: true },topHeight: { configurable: true },bottomHeight: { configurable: true } }; - - NineSlicePlane.prototype.textureUpdated = function textureUpdated () - { - this._textureID = this.shader.texture._updateID; - this._refresh(); - }; - - prototypeAccessors.vertices.get = function () - { - return this.geometry.getBuffer('aVertexPosition').data; - }; - - prototypeAccessors.vertices.set = function (value) - { - this.geometry.getBuffer('aVertexPosition').data = value; - }; - - /** - * Updates the horizontal vertices. - * - */ - NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices () - { - var vertices = this.vertices; - - var h = this._topHeight + this._bottomHeight; - var scale = this._height > h ? 1.0 : this._height / h; - - vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; - vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale); - vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; - }; - /** - * Updates the vertical vertices. + * Renders text to its canvas, and updates its texture. + * By default this is used internally to ensure the texture is correct before rendering, + * but it can be used called externally, for example from this class to 'pre-generate' the texture from a piece of text, + * and then shared across multiple Sprites. * + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. */ - NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices () - { - var vertices = this.vertices; - - var w = this._leftWidth + this._rightWidth; - var scale = this._width > w ? 1.0 : this._width / w; - - vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; - vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale); - vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + Text.prototype.updateText = function (respectDirty) { + var style = this._style; + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + if (!this.dirty && respectDirty) { + return; + } + this._font = this._style.toFontString(); + var context = this.context; + var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + this.canvas.width = Math.ceil((Math.max(1, width) + (style.padding * 2)) * this._resolution); + this.canvas.height = Math.ceil((Math.max(1, height) + (style.padding * 2)) * this._resolution); + context.scale(this._resolution, this._resolution); + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + context.font = this._font; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + var linePositionX; + var linePositionY; + // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text + var passesCount = style.dropShadow ? 2 : 1; + // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex, + // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow. + // + // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more + // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill + // and the stroke; and fill drop shadows would appear over the top of the stroke. + // + // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal + // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the + // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow + // beneath the text, whilst also having the proper text shadow styling. + for (var i = 0; i < passesCount; ++i) { + var isShadowPass = style.dropShadow && i === 0; + var dsOffsetText = isShadowPass ? height * 2 : 0; // we only want the drop shadow, so put text way off-screen + var dsOffsetShadow = dsOffsetText * this.resolution; + if (isShadowPass) { + // On Safari, text with gradient and drop shadows together do not position correctly + // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689 + // Therefore we'll set the styles to be a plain black whilst generating this drop shadow + context.fillStyle = 'black'; + context.strokeStyle = 'black'; + var dropShadowColor = style.dropShadowColor; + var rgb = utils.hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : utils.string2hex(dropShadowColor)); + context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; + context.shadowBlur = style.dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * style.dropShadowDistance) + dsOffsetShadow; + } + else { + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines, measured); + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + context.strokeStyle = style.stroke; + context.shadowColor = '0'; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + // draw lines line by line + for (var i_1 = 0; i_1 < lines.length; i_1++) { + linePositionX = style.strokeThickness / 2; + linePositionY = ((style.strokeThickness / 2) + (i_1 * lineHeight)) + fontProperties.ascent; + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i_1]; + } + else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i_1]) / 2; + } + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true); + } + if (style.fill) { + this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText); + } + } + } + this.updateTexture(); }; - /** - * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private */ - prototypeAccessors.width.get = function () - { - return this._width; - }; - - prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc - { - this._width = value; - this._refresh(); + Text.prototype.drawLetterSpacing = function (text, x, y, isStroke) { + if (isStroke === void 0) { isStroke = false; } + var style = this._style; + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } + else { + this.context.fillText(text, x, y); + } + return; + } + var currentPosition = x; + // Using Array.from correctly splits characters whilst keeping emoji together. + // This is not supported on IE as it requires ES6, so regular text splitting occurs. + // This also doesn't account for emoji that are multiple emoji put together to make something else. + // Handling all of this would require a big library itself. + // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516 + // https://github.com/orling/grapheme-splitter + var stringArray = Array.from ? Array.from(text) : text.split(''); + var previousWidth = this.context.measureText(text).width; + var currentWidth = 0; + for (var i = 0; i < stringArray.length; ++i) { + var currentChar = stringArray[i]; + if (isStroke) { + this.context.strokeText(currentChar, currentPosition, y); + } + else { + this.context.fillText(currentChar, currentPosition, y); + } + currentWidth = this.context.measureText(text.substring(i + 1)).width; + currentPosition += previousWidth - currentWidth + letterSpacing; + previousWidth = currentWidth; + } }; - /** - * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * Updates texture size based on canvas size * - * @member {number} + * @private */ - prototypeAccessors.height.get = function () - { - return this._height; - }; - - prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc - { - this._height = value; - this._refresh(); + Text.prototype.updateTexture = function () { + var canvas = this.canvas; + if (this._style.trim) { + var trimmed = utils.trimCanvas(canvas); + if (trimmed.data) { + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + } + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + texture.trim.width = texture._frame.width = Math.ceil(canvas.width / this._resolution); + texture.trim.height = texture._frame.height = Math.ceil(canvas.height / this._resolution); + texture.trim.x = -padding; + texture.trim.y = -padding; + texture.orig.width = texture._frame.width - (padding * 2); + texture.orig.height = texture._frame.height - (padding * 2); + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + baseTexture.setRealSize(canvas.width, canvas.height, this._resolution); + // Recursively updates transform of all objects from the root to this one + this._recursivePostUpdateTransform(); + this.dirty = false; }; - /** - * The width of the left column + * Renders the object using the WebGL renderer * - * @member {number} + * @protected + * @param {PIXI.Renderer} renderer - The renderer */ - prototypeAccessors.leftWidth.get = function () - { - return this._leftWidth; - }; - - prototypeAccessors.leftWidth.set = function (value) // eslint-disable-line require-jsdoc - { - this._leftWidth = value; - this._refresh(); + Text.prototype._render = function (renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + this.updateText(true); + _super.prototype._render.call(this, renderer); }; - /** - * The width of the right column + * Gets the local bounds of the text object. * - * @member {number} + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. */ - prototypeAccessors.rightWidth.get = function () - { - return this._rightWidth; - }; - - prototypeAccessors.rightWidth.set = function (value) // eslint-disable-line require-jsdoc - { - this._rightWidth = value; - this._refresh(); + Text.prototype.getLocalBounds = function (rect) { + this.updateText(true); + return _super.prototype.getLocalBounds.call(this, rect); }; - /** - * The height of the top row - * - * @member {number} + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + * @protected */ - prototypeAccessors.topHeight.get = function () - { - return this._topHeight; - }; - - prototypeAccessors.topHeight.set = function (value) // eslint-disable-line require-jsdoc - { - this._topHeight = value; - this._refresh(); + Text.prototype._calculateBounds = function () { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); }; - /** - * The height of the bottom row + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array * - * @member {number} + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style */ - prototypeAccessors.bottomHeight.get = function () - { - return this._bottomHeight; - }; - - prototypeAccessors.bottomHeight.set = function (value) // eslint-disable-line require-jsdoc - { - this._bottomHeight = value; - this._refresh(); + Text.prototype._generateFillStyle = function (style, lines, metrics) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } + else if (fillStyle.length === 1) { + return fillStyle[0]; + } + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient; + // a dropshadow will enlarge the canvas and result in the gradient being + // generated with the incorrect dimensions + var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; + // should also take padding into account, padding can offset the gradient + var padding = style.padding || 0; + var width = Math.ceil(this.canvas.width / this._resolution) - dropShadowCorrection - (padding * 2); + var height = Math.ceil(this.canvas.height / this._resolution) - dropShadowCorrection - (padding * 2); + // make a copy of the style settings, so we can manipulate them later + var fill = fillStyle.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, padding, width / 2, height + padding); + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + // There's potential for floating point precision issues at the seams between gradient repeats. + // The loop below generates the stops in order, so track the last generated one to prevent + // floating point precision from making us go the teeniest bit backwards, resulting in + // the first and last colors getting swapped. + var lastIterationStop = 0; + // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc + var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + // textHeight, but as a 0-1 size in global gradient stop space + var gradStopLineHeight = textHeight / height; + for (var i = 0; i < lines.length; i++) { + var thisLineTop = metrics.lineHeight * i; + for (var j = 0; j < fill.length; j++) { + // 0-1 stop point for the current line, multiplied to global space afterwards + var lineStop = 0; + if (typeof fillGradientStops[j] === 'number') { + lineStop = fillGradientStops[j]; + } + else { + lineStop = j / fill.length; + } + var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight); + // Prevent color stop generation going backwards from floating point imprecision + var clampedStop = Math.max(lastIterationStop, globalStop); + clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw. + gradient.addColorStop(clampedStop, fill[j]); + lastIterationStop = clampedStop; + } + } + } + else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(padding, height / 2, width + padding, height / 2); + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + var totalIterations = fill.length + 1; + var currentIteration = 1; + for (var i = 0; i < fill.length; i++) { + var stop = void 0; + if (typeof fillGradientStops[i] === 'number') { + stop = fillGradientStops[i]; + } + else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; }; - /** - * Refreshes NineSlicePlane coords. All of them. + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well */ - NineSlicePlane.prototype._refresh = function _refresh () - { - var texture = this.texture; - - var uvs = this.geometry.buffers[1].data; - - this._origWidth = texture.orig.width; - this._origHeight = texture.orig.height; - - var _uvw = 1.0 / this._origWidth; - var _uvh = 1.0 / this._origHeight; - - uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; - uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; - uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; - uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; - - uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; - uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth); - uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; - uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight); - - this.updateHorizontalVertices(); - this.updateVerticalVertices(); - - this.geometry.buffers[0].update(); - this.geometry.buffers[1].update(); + Text.prototype.destroy = function (options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + options = Object.assign({}, defaultDestroyOptions, options); + _super.prototype.destroy.call(this, options); + // set canvas width and height to 0 to workaround memory leak in Safari < 13 + // https://stackoverflow.com/questions/52532614/total-canvas-memory-use-exceeds-the-maximum-limit-safari-12 + if (this._ownCanvas) { + this.canvas.height = this.canvas.width = 0; + } + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + this._style = null; }; + Object.defineProperty(Text.prototype, "width", { + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + get: function () { + this.updateText(true); + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function (value) { + this.updateText(true); + var s = utils.sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "height", { + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + get: function () { + this.updateText(true); + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) { + this.updateText(true); + var s = utils.sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "style", { + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + get: function () { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the ITextStyle + // since the setter creates the TextStyle. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + return this._style; + }, + set: function (style) { + style = style || {}; + if (style instanceof TextStyle) { + this._style = style; + } + else { + this._style = new TextStyle(style); + } + this.localStyleID = -1; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "text", { + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + get: function () { + return this._text; + }, + set: function (text) { + text = String(text === null || text === undefined ? '' : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "resolution", { + /** + * The resolution / device pixel ratio of the canvas. + * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. + * @member {number} + * @default 1 + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + return Text; +}(sprite.Sprite)); - Object.defineProperties( NineSlicePlane.prototype, prototypeAccessors ); - - return NineSlicePlane; -}(SimplePlane)); - -exports.NineSlicePlane = NineSlicePlane; -exports.PlaneGeometry = PlaneGeometry; -exports.RopeGeometry = RopeGeometry; -exports.SimpleMesh = SimpleMesh; -exports.SimplePlane = SimplePlane; -exports.SimpleRope = SimpleRope; +exports.Text = Text; +exports.TextMetrics = TextMetrics; +exports.TextStyle = TextStyle; -},{"@pixi/constants":16,"@pixi/core":17,"@pixi/mesh":31}],31:[function(require,module,exports){ +},{"@pixi/core":8,"@pixi/math":20,"@pixi/settings":30,"@pixi/sprite":33,"@pixi/utils":38}],37:[function(require,module,exports){ /*! - * @pixi/mesh - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * @pixi/ticker - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @pixi/mesh is licensed under the MIT License. + * @pixi/ticker is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); -var core = require('@pixi/core'); -var math = require('@pixi/math'); -var constants = require('@pixi/constants'); -var display = require('@pixi/display'); var settings = require('@pixi/settings'); -var utils = require('@pixi/utils'); /** - * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space. + * Target frames per millisecond. * - * @class - * @memberof PIXI + * @static + * @name TARGET_FPMS + * @memberof PIXI.settings + * @type {number} + * @default 0.06 */ -var MeshBatchUvs = function MeshBatchUvs(uvBuffer, uvMatrix) -{ - /** - * Buffer with normalized UV's - * @member {PIXI.Buffer} - */ - this.uvBuffer = uvBuffer; - - /** - * Material UV matrix - * @member {PIXI.TextureMatrix} - */ - this.uvMatrix = uvMatrix; - - /** - * UV Buffer data - * @member {Float32Array} - * @readonly - */ - this.data = null; - - this._bufferUpdateId = -1; - - this._textureUpdateId = -1; - - this._updateID = 0; -}; +settings.settings.TARGET_FPMS = 0.06; /** - * updates + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. * - * @param {boolean} forceUpdate - force the update + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @enum {number} + * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.InteractionManager} + * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite} + * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.Ticker#add}. + * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. + * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.BasePrepare} utility. */ -MeshBatchUvs.prototype.update = function update (forceUpdate) -{ - if (!forceUpdate - && this._bufferUpdateId === this.uvBuffer._updateID - && this._textureUpdateId === this.uvMatrix._updateID) - { - return; - } - - this._bufferUpdateId = this.uvBuffer._updateID; - this._textureUpdateId = this.uvMatrix._updateID; - - var data = this.uvBuffer.data; - - if (!this.data || this.data.length !== data.length) - { - this.data = new Float32Array(data.length); - } - - this.uvMatrix.multiplyUvs(data, this.data); - - this._updateID++; -}; - -var tempPoint = new math.Point(); -var tempPolygon = new math.Polygon(); +(function (UPDATE_PRIORITY) { + UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION"; + UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH"; + UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL"; + UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW"; + UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY"; +})(exports.UPDATE_PRIORITY || (exports.UPDATE_PRIORITY = {})); /** - * Base mesh class. - * - * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of. - * This class assumes a certain level of WebGL knowledge. - * If you know a bit this should abstract enough away to make you life easier! - * - * Pretty much ALL WebGL can be broken down into the following: - * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc.. - * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry) - * - State - This is the state of WebGL required to render the mesh. - * - * Through a combination of the above elements you can render anything you want, 2D or 3D! + * Internal class for handling the priority sorting of ticker handlers. * + * @private * @class - * @extends PIXI.Container * @memberof PIXI */ -var Mesh = /*@__PURE__*/(function (Container) { - function Mesh(geometry, shader, state, drawMode)// vertices, uvs, indices, drawMode) - { - if ( drawMode === void 0 ) drawMode = constants.DRAW_MODES.TRIANGLES; - - Container.call(this); - - /** - * Includes vertex positions, face indices, normals, colors, UVs, and - * custom attributes within buffers, reducing the cost of passing all - * this data to the GPU. Can be shared between multiple Mesh objects. - * @member {PIXI.Geometry} - * @readonly - */ - this.geometry = geometry; - - geometry.refCount++; - - /** - * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. - * Can be shared between multiple Mesh objects. - * @member {PIXI.Shader|PIXI.MeshMaterial} - */ - this.shader = shader; - - /** - * Represents the WebGL state the Mesh required to render, excludes shader and geometry. E.g., - * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. - * @member {PIXI.State} - */ - this.state = state || core.State.for2d(); - - /** - * The way the Mesh should be drawn, can be any of the {@link PIXI.DRAW_MODES} constants. - * - * @member {number} - * @see PIXI.DRAW_MODES - */ - this.drawMode = drawMode; - - /** - * Typically the index of the IndexBuffer where to start drawing. - * @member {number} - * @default 0 - */ - this.start = 0; - +var TickerListener = /** @class */ (function () { + /** + * Constructor + * @private + * @param {Function} fn - The listener function to be added for one update + * @param {*} [context=null] - The listener context + * @param {number} [priority=0] - The priority for emitting + * @param {boolean} [once=false] - If the handler should fire once + */ + function TickerListener(fn, context, priority, once) { + if (context === void 0) { context = null; } + if (priority === void 0) { priority = 0; } + if (once === void 0) { once = false; } /** - * How much of the geometry to draw, by default `0` renders everything. - * @member {number} - * @default 0 + * The handler function to execute. + * @private + * @member {Function} */ - this.size = 0; - + this.fn = fn; /** - * thease are used as easy access for batching - * @member {Float32Array} + * The calling to execute. * @private + * @member {*} */ - this.uvs = null; - + this.context = context; /** - * thease are used as easy access for batching - * @member {Uint16Array} + * The current priority. * @private + * @member {number} */ - this.indices = null; - + this.priority = priority; /** - * this is the caching layer used by the batcher - * @member {Float32Array} + * If this should only execute once. * @private + * @member {boolean} */ - this.vertexData = new Float32Array(1); - + this.once = once; /** - * If geometry is changed used to decide to re-transform - * the vertexData. - * @member {number} + * The next item in chain. * @private + * @member {TickerListener} */ - this.vertexDirty = 0; - - this._transformID = -1; - - // Inherited from DisplayMode, set defaults - this.tint = 0xFFFFFF; - this.blendMode = constants.BLEND_MODES.NORMAL; - + this.next = null; /** - * Internal roundPixels field - * - * @member {boolean} + * The previous item in chain. * @private + * @member {TickerListener} */ - this._roundPixels = settings.settings.ROUND_PIXELS; - + this.previous = null; /** - * Batched UV's are cached for atlas textures - * @member {PIXI.MeshBatchUvs} + * `true` if this listener has been destroyed already. + * @member {boolean} * @private */ - this.batchUvs = null; + this._destroyed = false; } - - if ( Container ) Mesh.__proto__ = Container; - Mesh.prototype = Object.create( Container && Container.prototype ); - Mesh.prototype.constructor = Mesh; - - var prototypeAccessors = { uvBuffer: { configurable: true },verticesBuffer: { configurable: true },material: { configurable: true },blendMode: { configurable: true },roundPixels: { configurable: true },tint: { configurable: true },texture: { configurable: true } }; - - /** - * To change mesh uv's, change its uvBuffer data and increment its _updateID. - * @member {PIXI.Buffer} - * @readonly - */ - prototypeAccessors.uvBuffer.get = function () - { - return this.geometry.buffers[1]; - }; - - /** - * To change mesh vertices, change its uvBuffer data and increment its _updateID. - * Incrementing _updateID is optional because most of Mesh objects do it anyway. - * @member {PIXI.Buffer} - * @readonly - */ - prototypeAccessors.verticesBuffer.get = function () - { - return this.geometry.buffers[0]; - }; - - /** - * Alias for {@link PIXI.Mesh#shader}. - * @member {PIXI.Shader|PIXI.MeshMaterial} - */ - prototypeAccessors.material.set = function (value) - { - this.shader = value; - }; - - prototypeAccessors.material.get = function () - { - return this.shader; - }; - /** - * The blend mode to be applied to the Mesh. Apply a value of - * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL; - * @see PIXI.BLEND_MODES + * Simple compare function to figure out if a function and context match. + * @private + * @param {Function} fn - The listener function to be added for one update + * @param {any} [context] - The listener context + * @return {boolean} `true` if the listener match the arguments */ - prototypeAccessors.blendMode.set = function (value) - { - this.state.blendMode = value; - }; - - prototypeAccessors.blendMode.get = function () - { - return this.state.blendMode; + TickerListener.prototype.match = function (fn, context) { + if (context === void 0) { context = null; } + return this.fn === fn && this.context === context; }; - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} - * - * @member {boolean} - * @default false + * Emit by calling the current function. + * @private + * @param {number} deltaTime - time since the last emit. + * @return {TickerListener} Next ticker */ - prototypeAccessors.roundPixels.set = function (value) - { - if (this._roundPixels !== value) - { - this._transformID = -1; + TickerListener.prototype.emit = function (deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } + else { + this.fn(deltaTime); + } } - this._roundPixels = value; - }; - - prototypeAccessors.roundPixels.get = function () - { - return this._roundPixels; - }; - - /** - * The multiply tint applied to the Mesh. This is a hex value. A value of - * `0xFFFFFF` will remove any tint effect. - * - * @member {number} - * @default 0xFFFFFF - */ - prototypeAccessors.tint.get = function () - { - return this.shader.tint; - }; - - prototypeAccessors.tint.set = function (value) - { - this.shader.tint = value; - }; - - /** - * The texture that the Mesh uses. - * - * @member {PIXI.Texture} - */ - prototypeAccessors.texture.get = function () - { - return this.shader.texture; - }; - - prototypeAccessors.texture.set = function (value) - { - this.shader.texture = value; + var redirect = this.next; + if (this.once) { + this.destroy(true); + } + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + return redirect; }; - /** - * Standard renderer draw. - * @protected - * @param {PIXI.Renderer} renderer - Instance to renderer. + * Connect to the list. + * @private + * @param {TickerListener} previous - Input node, previous listener */ - Mesh.prototype._render = function _render (renderer) - { - // set properties for batching.. - // TODO could use a different way to grab verts? - var vertices = this.geometry.buffers[0].data; - - // TODO benchmark check for attribute size.. - if (this.shader.batchable && this.drawMode === constants.DRAW_MODES.TRIANGLES && vertices.length < Mesh.BATCHABLE_SIZE * 2) - { - this._renderToBatch(renderer); - } - else - { - this._renderDefault(renderer); + TickerListener.prototype.connect = function (previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; } + this.next = previous.next; + previous.next = this; }; - /** - * Standard non-batching way of rendering. - * @protected - * @param {PIXI.Renderer} renderer - Instance to renderer. + * Destroy and don't use after this. + * @private + * @param {boolean} [hard = false] `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @return {TickerListener} The listener to redirect while emitting or removing. */ - Mesh.prototype._renderDefault = function _renderDefault (renderer) - { - var shader = this.shader; - - shader.alpha = this.worldAlpha; - if (shader.update) - { - shader.update(); + TickerListener.prototype.destroy = function (hard) { + if (hard === void 0) { hard = false; } + this._destroyed = true; + this.fn = null; + this.context = null; + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; } - - renderer.batch.flush(); - - if (shader.program.uniformData.translationMatrix) - { - shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true); + if (this.next) { + this.next.previous = this.previous; } - - // bind and sync uniforms.. - renderer.shader.bind(shader); - - // set state.. - renderer.state.set(this.state); - - // bind the geometry... - renderer.geometry.bind(this.geometry, shader); - - // then render it - renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); + // Redirect to the next item + var redirect = this.next; + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + return redirect; }; + return TickerListener; +}()); - /** - * Rendering by using the Batch system. - * @protected - * @param {PIXI.Renderer} renderer - Instance to renderer. - */ - Mesh.prototype._renderToBatch = function _renderToBatch (renderer) - { - var geometry = this.geometry; - - if (this.shader.uvMatrix) - { - this.shader.uvMatrix.update(); - this.calculateUvs(); +/** + * A Ticker class that runs an update loop that other objects listen to. + * + * This class is composed around listeners meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI + */ +var Ticker = /** @class */ (function () { + function Ticker() { + var _this = this; + /** + * The first listener. All new listeners added are chained on this. + * @private + * @type {TickerListener} + */ + this._head = new TickerListener(null, null, Infinity); + /** + * Internal current frame request ID + * @type {?number} + * @private + */ + this._requestId = null; + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @type {number} + * @private + */ + this._maxElapsedMS = 100; + /** + * Internal value managed by maxFPS property setter and getter. + * This is the minimum allowed milliseconds between updates. + * @type {number} + * @private + */ + this._minElapsedMS = 0; + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.Ticker#minFPS} + * and is scaled with {@link PIXI.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + /** + * Scaler time elapsed in milliseconds from last frame to this frame. + * This value is capped by setting {@link PIXI.Ticker#minFPS} + * and is scaled with {@link PIXI.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.deltaMS = 1 / settings.settings.TARGET_FPMS; + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / settings.settings.TARGET_FPMS; + /** + * The last time {@link PIXI.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default -1 + */ + this.lastTime = -1; + /** + * Factor of current {@link PIXI.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.Ticker#start} has been called. + * `false` if {@link PIXI.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + /** + * If enabled, deleting is disabled. + * @member {boolean} + * @default false + * @private + */ + this._protected = false; + /** + * The last time keyframe was executed. + * Maintains a relatively fixed interval with the previous value. + * @member {number} + * @default -1 + * @private + */ + this._lastFrame = -1; + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + Ticker.prototype._requestIfNeeded = function () { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._lastFrame = this.lastTime; + this._requestId = requestAnimationFrame(this._tick); } - - // set properties for batching.. - this.calculateVertices(); - this.indices = geometry.indexBuffer.data; - this._tintRGB = this.shader._tintRGB; - this._texture = this.shader.texture; - - var pluginName = this.material.pluginName; - - renderer.batch.setObjectRenderer(renderer.plugins[pluginName]); - renderer.plugins[pluginName].render(this); }; - /** - * Updates vertexData field based on transform and vertices + * Conditionally cancels a pending animation frame. + * + * @private */ - Mesh.prototype.calculateVertices = function calculateVertices () - { - var geometry = this.geometry; - var vertices = geometry.buffers[0].data; - - if (geometry.vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) - { - return; - } - - this._transformID = this.transform._worldID; - - if (this.vertexData.length !== vertices.length) - { - this.vertexData = new Float32Array(vertices.length); - } - - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - - var vertexData = this.vertexData; - - for (var i = 0; i < vertexData.length / 2; i++) - { - var x = vertices[(i * 2)]; - var y = vertices[(i * 2) + 1]; - - vertexData[(i * 2)] = (a * x) + (c * y) + tx; - vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty; - } - - if (this._roundPixels) - { - for (var i$1 = 0; i$1 < vertexData.length; i$1++) - { - vertexData[i$1] = Math.round(vertexData[i$1]); - } + Ticker.prototype._cancelIfNeeded = function () { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; } - - this.vertexDirty = geometry.vertexDirtyId; }; - /** - * Updates uv field based on from geometry uv's or batchUvs + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private */ - Mesh.prototype.calculateUvs = function calculateUvs () - { - var geomUvs = this.geometry.buffers[1]; - - if (!this.shader.uvMatrix.isSimple) - { - if (!this.batchUvs) - { - this.batchUvs = new MeshBatchUvs(geomUvs, this.shader.uvMatrix); - } - this.batchUvs.update(); - this.uvs = this.batchUvs.data; + Ticker.prototype._startIfPossible = function () { + if (this.started) { + this._requestIfNeeded(); } - else - { - this.uvs = geomUvs.data; + else if (this.autoStart) { + this.start(); } }; - /** - * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. - * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly. + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. * - * @protected + * @param {Function} fn - The listener function to be added for updates + * @param {*} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.Ticker} This instance of a ticker */ - Mesh.prototype._calculateBounds = function _calculateBounds () - { - this.calculateVertices(); - - this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); + Ticker.prototype.add = function (fn, context, priority) { + if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } + return this._addListener(new TickerListener(fn, context, priority)); }; - /** - * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES. + * Add a handler for the tick event which is only execute once. * - * @param {PIXI.Point} point the point to test - * @return {boolean} the result of the test + * @param {Function} fn - The listener function to be added for one update + * @param {*} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.Ticker} This instance of a ticker */ - Mesh.prototype.containsPoint = function containsPoint (point) - { - if (!this.getBounds().contains(point.x, point.y)) - { - return false; + Ticker.prototype.addOnce = function (fn, context, priority) { + if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } + return this._addListener(new TickerListener(fn, context, priority, true)); + }; + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * + * @private + * @param {TickerListener} listener - Current listener being added. + * @returns {PIXI.Ticker} This instance of a ticker + */ + Ticker.prototype._addListener = function (listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + // Add the first item + if (!current) { + listener.connect(previous); } - - this.worldTransform.applyInverse(point, tempPoint); - - var vertices = this.geometry.getBuffer('aVertexPosition').data; - - var points = tempPolygon.points; - var indices = this.geometry.getIndex().data; - var len = indices.length; - var step = this.drawMode === 4 ? 3 : 1; - - for (var i = 0; i + 2 < len; i += step) - { - var ind0 = indices[i] * 2; - var ind1 = indices[i + 1] * 2; - var ind2 = indices[i + 2] * 2; - - points[0] = vertices[ind0]; - points[1] = vertices[ind0 + 1]; - points[2] = vertices[ind1]; - points[3] = vertices[ind1 + 1]; - points[4] = vertices[ind2]; - points[5] = vertices[ind2 + 1]; - - if (tempPolygon.contains(tempPoint.x, tempPoint.y)) - { - return true; + else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + // Not yet connected + if (!listener.previous) { + listener.connect(previous); } } - - return false; + this._startIfPossible(); + return this; }; /** - * Destroys the Mesh object. + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all - * options have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have - * their destroy method called as well. 'options' will be passed on to those calls. + * @param {Function} fn - The listener function to be removed + * @param {*} [context] - The listener context to be removed + * @returns {PIXI.Ticker} This instance of a ticker */ - Mesh.prototype.destroy = function destroy (options) - { - Container.prototype.destroy.call(this, options); - - this.geometry.refCount--; - if (this.geometry.refCount === 0) - { - this.geometry.dispose(); + Ticker.prototype.remove = function (fn, context) { + var listener = this._head.next; + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } + else { + listener = listener.next; + } } - - this.geometry = null; - this.shader = null; - this.state = null; - this.uvs = null; - this.indices = null; - this.vertexData = null; - }; - - Object.defineProperties( Mesh.prototype, prototypeAccessors ); - - return Mesh; -}(display.Container)); - -/** - * The maximum number of vertices to consider batchable. Generally, the complexity - * of the geometry. - * @memberof PIXI.Mesh - * @static - * @member {number} BATCHABLE_SIZE - */ -Mesh.BATCHABLE_SIZE = 100; - -var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n"; - -var fragment = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"; - -/** - * Slightly opinionated default shader for PixiJS 2D objects. - * @class - * @memberof PIXI - * @extends PIXI.Shader - */ -var MeshMaterial = /*@__PURE__*/(function (Shader) { - function MeshMaterial(uSampler, options) - { - var uniforms = { - uSampler: uSampler, - alpha: 1, - uTextureMatrix: math.Matrix.IDENTITY, - uColor: new Float32Array([1, 1, 1, 1]), - }; - - // Set defaults - options = Object.assign({ - tint: 0xFFFFFF, - alpha: 1, - pluginName: 'batch', - }, options); - - if (options.uniforms) - { - Object.assign(uniforms, options.uniforms); + if (!this._head.next) { + this._cancelIfNeeded(); } - - Shader.call(this, options.program || core.Program.from(vertex, fragment), uniforms); - - /** - * Only do update if tint or alpha changes. - * @member {boolean} - * @private - * @default false - */ - this._colorDirty = false; - + return this; + }; + Object.defineProperty(Ticker.prototype, "count", { /** - * TextureMatrix instance for this Mesh, used to track Texture changes + * The number of listeners on this ticker, calculated by walking through linked list * - * @member {PIXI.TextureMatrix} * @readonly + * @member {number} */ - this.uvMatrix = new core.TextureMatrix(uSampler); - - /** - * `true` if shader can be batch with the renderer's batch system. - * @member {boolean} - * @default true - */ - this.batchable = options.program === undefined; - - /** - * Renderer plugin for batching - * - * @member {string} - * @default 'batch' - */ - this.pluginName = options.pluginName; - - this.tint = options.tint; - this.alpha = options.alpha; - } - - if ( Shader ) MeshMaterial.__proto__ = Shader; - MeshMaterial.prototype = Object.create( Shader && Shader.prototype ); - MeshMaterial.prototype.constructor = MeshMaterial; - - var prototypeAccessors = { texture: { configurable: true },alpha: { configurable: true },tint: { configurable: true } }; - + get: function () { + if (!this._head) { + return 0; + } + var count = 0; + var current = this._head; + while ((current = current.next)) { + count++; + } + return count; + }, + enumerable: false, + configurable: true + }); /** - * Reference to the texture being rendered. - * @member {PIXI.Texture} + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. */ - prototypeAccessors.texture.get = function () - { - return this.uniforms.uSampler; - }; - prototypeAccessors.texture.set = function (value) - { - if (this.uniforms.uSampler !== value) - { - this.uniforms.uSampler = value; - this.uvMatrix.texture = value; + Ticker.prototype.start = function () { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); } }; - /** - * This gets automatically set by the object using this. - * - * @default 1 - * @member {number} + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. */ - prototypeAccessors.alpha.set = function (value) - { - if (value === this._alpha) { return; } - - this._alpha = value; - this._colorDirty = true; - }; - prototypeAccessors.alpha.get = function () - { - return this._alpha; + Ticker.prototype.stop = function () { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } }; - /** - * Multiply tint for the material. - * @member {number} - * @default 0xFFFFFF + * Destroy the ticker and don't use after this. Calling + * this method removes all references to internal events. */ - prototypeAccessors.tint.set = function (value) - { - if (value === this._tint) { return; } - - this._tint = value; - this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); - this._colorDirty = true; - }; - prototypeAccessors.tint.get = function () - { - return this._tint; + Ticker.prototype.destroy = function () { + if (!this._protected) { + this.stop(); + var listener = this._head.next; + while (listener) { + listener = listener.destroy(true); + } + this._head.destroy(); + this._head = null; + } }; - /** - * Gets called automatically by the Mesh. Intended to be overridden for custom - * MeshMaterial objects. - */ - MeshMaterial.prototype.update = function update () - { - if (this._colorDirty) - { - this._colorDirty = false; - var baseTexture = this.texture.baseTexture; - - utils.premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode); - } - if (this.uvMatrix.update()) - { - this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord; + * Triggers an update. An update entails setting the + * current {@link PIXI.Ticker#elapsedMS}, + * the current {@link PIXI.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + Ticker.prototype.update = function (currentTime) { + if (currentTime === void 0) { currentTime = performance.now(); } + var elapsedMS; + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + elapsedMS *= this.speed; + // If not enough time has passed, exit the function. + // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS + // adjustment to ensure a relatively stable interval. + if (this._minElapsedMS) { + var delta = currentTime - this._lastFrame | 0; + if (delta < this._minElapsedMS) { + return; + } + this._lastFrame = currentTime - (delta % this._minElapsedMS); + } + this.deltaMS = elapsedMS; + this.deltaTime = this.deltaMS * settings.settings.TARGET_FPMS; + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + // Invoke listeners added to internal emitter + var listener = head.next; + while (listener) { + listener = listener.emit(this.deltaTime); + } + if (!head.next) { + this._cancelIfNeeded(); + } + } + else { + this.deltaTime = this.deltaMS = this.elapsedMS = 0; } + this.lastTime = currentTime; }; - - Object.defineProperties( MeshMaterial.prototype, prototypeAccessors ); - - return MeshMaterial; -}(core.Shader)); + Object.defineProperty(Ticker.prototype, "FPS", { + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.Ticker#speed}, which is specific + * to scaling {@link PIXI.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + get: function () { + return 1000 / this.elapsedMS; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker.prototype, "minFPS", { + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.Ticker#update}. + * This value is used to cap {@link PIXI.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + get: function () { + return 1000 / this._maxElapsedMS; + }, + set: function (fps) { + // Minimum must be below the maxFPS + var minFPS = Math.min(this.maxFPS, fps); + // Must be at least 0, but below 1 / settings.TARGET_FPMS + var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings.settings.TARGET_FPMS); + this._maxElapsedMS = 1 / minFPMS; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker.prototype, "maxFPS", { + /** + * Manages the minimum amount of milliseconds required to + * elapse between invoking {@link PIXI.Ticker#update}. + * This will effect the measured value of {@link PIXI.Ticker#FPS}. + * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can. + * Otherwise it will be at least `minFPS` + * + * @member {number} + * @default 0 + */ + get: function () { + if (this._minElapsedMS) { + return Math.round(1000 / this._minElapsedMS); + } + return 0; + }, + set: function (fps) { + if (fps === 0) { + this._minElapsedMS = 0; + } + else { + // Max must be at least the minFPS + var maxFPS = Math.max(this.minFPS, fps); + this._minElapsedMS = 1 / (maxFPS / 1000); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker, "shared", { + /** + * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by + * {@link PIXI.VideoResource} to update animation frames / video textures. + * + * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true. + * + * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. + * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.Ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.Ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(); + * let stage = new PIXI.Container(); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @member {PIXI.Ticker} + * @static + */ + get: function () { + if (!Ticker._shared) { + var shared = Ticker._shared = new Ticker(); + shared.autoStart = true; + shared._protected = true; + } + return Ticker._shared; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker, "system", { + /** + * The system ticker instance used by {@link PIXI.InteractionManager} and by + * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused, + * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused. + * + * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. + * + * @member {PIXI.Ticker} + * @static + */ + get: function () { + if (!Ticker._system) { + var system = Ticker._system = new Ticker(); + system.autoStart = true; + system._protected = true; + } + return Ticker._system; + }, + enumerable: false, + configurable: true + }); + return Ticker; +}()); /** - * Standard 2D geometry used in PixiJS. - * - * Geometry can be defined without passing in a style or data if required. - * - * ```js - * const geometry = new PIXI.Geometry(); + * Middleware for for Application Ticker. * - * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); - * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2); - * geometry.addIndex([0,1,2,1,3,2]); + * @example + * import {TickerPlugin} from '@pixi/ticker'; + * import {Application} from '@pixi/app'; + * Application.registerPlugin(TickerPlugin); * - * ``` * @class * @memberof PIXI - * @extends PIXI.Geometry */ -var MeshGeometry = /*@__PURE__*/(function (Geometry) { - function MeshGeometry(vertices, uvs, index) - { - Geometry.call(this); - - var verticesBuffer = new core.Buffer(vertices); - var uvsBuffer = new core.Buffer(uvs, true); - var indexBuffer = new core.Buffer(index, true, true); - - this.addAttribute('aVertexPosition', verticesBuffer, 2, false, constants.TYPES.FLOAT) - .addAttribute('aTextureCoord', uvsBuffer, 2, false, constants.TYPES.FLOAT) - .addIndex(indexBuffer); - +var TickerPlugin = /** @class */ (function () { + function TickerPlugin() { + } + /** + * Initialize the plugin with scope of application instance + * + * @static + * @private + * @param {object} [options] - See application options + */ + TickerPlugin.init = function (options) { + var _this = this; + // Set default + options = Object.assign({ + autoStart: true, + sharedTicker: false, + }, options); + // Create ticker setter + Object.defineProperty(this, 'ticker', { + set: function (ticker) { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, exports.UPDATE_PRIORITY.LOW); + } + }, + get: function () { + return this._ticker; + }, + }); /** - * Dirty flag to limit update calls on Mesh. For example, - * limiting updates on a single Mesh instance with a shared Geometry - * within the render loop. + * Convenience method for stopping the render. + * + * @method PIXI.Application#stop + */ + this.stop = function () { + _this._ticker.stop(); + }; + /** + * Convenience method for starting the render. + * + * @method PIXI.Application#start + */ + this.start = function () { + _this._ticker.start(); + }; + /** + * Internal reference to the ticker. + * + * @type {PIXI.Ticker} + * @name _ticker + * @memberof PIXI.Application# * @private - * @member {number} - * @default -1 */ - this._updateId = -1; - } - - if ( Geometry ) MeshGeometry.__proto__ = Geometry; - MeshGeometry.prototype = Object.create( Geometry && Geometry.prototype ); - MeshGeometry.prototype.constructor = MeshGeometry; - - var prototypeAccessors = { vertexDirtyId: { configurable: true } }; - + this._ticker = null; + /** + * Ticker for doing render updates. + * + * @type {PIXI.Ticker} + * @name ticker + * @memberof PIXI.Application# + * @default PIXI.Ticker.shared + */ + this.ticker = options.sharedTicker ? Ticker.shared : new Ticker(); + // Start the rendering + if (options.autoStart) { + this.start(); + } + }; /** - * If the vertex position is updated. - * @member {number} - * @readonly + * Clean up the ticker, scoped to application. + * + * @static * @private */ - prototypeAccessors.vertexDirtyId.get = function () - { - return this.buffers[0]._updateID; + TickerPlugin.destroy = function () { + if (this._ticker) { + var oldTicker = this._ticker; + this.ticker = null; + oldTicker.destroy(); + } }; + return TickerPlugin; +}()); - Object.defineProperties( MeshGeometry.prototype, prototypeAccessors ); - - return MeshGeometry; -}(core.Geometry)); - -exports.Mesh = Mesh; -exports.MeshBatchUvs = MeshBatchUvs; -exports.MeshGeometry = MeshGeometry; -exports.MeshMaterial = MeshMaterial; +exports.Ticker = Ticker; +exports.TickerPlugin = TickerPlugin; -},{"@pixi/constants":16,"@pixi/core":17,"@pixi/display":18,"@pixi/math":29,"@pixi/settings":39,"@pixi/utils":47}],32:[function(require,module,exports){ +},{"@pixi/settings":30}],38:[function(require,module,exports){ /*! - * @pixi/mixin-cache-as-bitmap - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * @pixi/utils - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @pixi/mixin-cache-as-bitmap is licensed under the MIT License. + * @pixi/utils is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; -var core = require('@pixi/core'); -var sprite = require('@pixi/sprite'); -var display = require('@pixi/display'); -var math = require('@pixi/math'); -var utils = require('@pixi/utils'); -var settings = require('@pixi/settings'); +Object.defineProperty(exports, '__esModule', { value: true }); -var _tempMatrix = new math.Matrix(); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -display.DisplayObject.prototype._cacheAsBitmap = false; -display.DisplayObject.prototype._cacheData = false; +var settings = require('@pixi/settings'); +var eventemitter3 = _interopDefault(require('eventemitter3')); +var earcut = _interopDefault(require('earcut')); +var _url = require('url'); +var _url__default = _interopDefault(_url); +var constants = require('@pixi/constants'); -// figured theres no point adding ALL the extra variables to prototype. -// this model can hold the information needed. This can also be generated on demand as -// most objects are not cached as bitmaps. /** - * @class - * @ignore + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @name RETINA_PREFIX + * @memberof PIXI.settings + * @type {RegExp} + * @default /@([0-9\.]+)x/ + * @example `@2x` */ -var CacheData = function CacheData() -{ - this.textureCacheId = null; - - this.originalRender = null; - this.originalRenderCanvas = null; - this.originalCalculateBounds = null; - this.originalGetLocalBounds = null; - - this.originalUpdateTransform = null; - this.originalHitTest = null; - this.originalDestroy = null; - this.originalMask = null; - this.originalFilterArea = null; - this.sprite = null; -}; - -Object.defineProperties(display.DisplayObject.prototype, { - /** - * Set this to true if you want this display object to be cached as a bitmap. - * This basically takes a snap shot of the display object as it is at that moment. It can - * provide a performance benefit for complex static displayObjects. - * To remove simply set this property to `false` - * - * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true - * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. - * - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - cacheAsBitmap: { - get: function get() - { - return this._cacheAsBitmap; - }, - set: function set(value) - { - if (this._cacheAsBitmap === value) - { - return; - } - - this._cacheAsBitmap = value; - - var data; - - if (value) - { - if (!this._cacheData) - { - this._cacheData = new CacheData(); - } - - data = this._cacheData; - - data.originalRender = this.render; - data.originalRenderCanvas = this.renderCanvas; - - data.originalUpdateTransform = this.updateTransform; - data.originalCalculateBounds = this.calculateBounds; - data.originalGetLocalBounds = this.getLocalBounds; - - data.originalDestroy = this.destroy; - - data.originalContainsPoint = this.containsPoint; - - data.originalMask = this._mask; - data.originalFilterArea = this.filterArea; - - this.render = this._renderCached; - this.renderCanvas = this._renderCachedCanvas; - - this.destroy = this._cacheAsBitmapDestroy; - } - else - { - data = this._cacheData; - - if (data.sprite) - { - this._destroyCachedDisplayObject(); - } - - this.render = data.originalRender; - this.renderCanvas = data.originalRenderCanvas; - this.calculateBounds = data.originalCalculateBounds; - this.getLocalBounds = data.originalGetLocalBounds; - - this.destroy = data.originalDestroy; - - this.updateTransform = data.originalUpdateTransform; - this.containsPoint = data.originalContainsPoint; - - this._mask = data.originalMask; - this.filterArea = data.originalFilterArea; - } - }, - }, -}); - +settings.settings.RETINA_PREFIX = /@([0-9\.]+)x/; /** - * Renders a cached version of the sprite with WebGL + * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. + * For most scenarios this should be left as true, as otherwise the user may have a poor experience. + * However, it can be useful to disable under certain scenarios, such as headless unit tests. * - * @private - * @function _renderCached - * @memberof PIXI.DisplayObject# - * @param {PIXI.Renderer} renderer - the WebGL renderer + * @static + * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT + * @memberof PIXI.settings + * @type {boolean} + * @default true */ -display.DisplayObject.prototype._renderCached = function _renderCached(renderer) -{ - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) - { - return; - } - - this._initCachedDisplayObject(renderer); - - this._cacheData.sprite.transform._worldID = this.transform._worldID; - this._cacheData.sprite.worldAlpha = this.worldAlpha; - this._cacheData.sprite._render(renderer); -}; +settings.settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = true; +var saidHello = false; +var VERSION = '5.3.3'; /** - * Prepares the WebGL renderer to cache the sprite + * Skips the hello message of renderers that are created after this is run. * - * @private - * @function _initCachedDisplayObject - * @memberof PIXI.DisplayObject# - * @param {PIXI.Renderer} renderer - the WebGL renderer + * @function skipHello + * @memberof PIXI.utils */ -display.DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) -{ - if (this._cacheData && this._cacheData.sprite) - { +function skipHello() { + saidHello = true; +} +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever make you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + var _a; + if (saidHello) { return; } + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = [ + "\n %c %c %c PixiJS " + VERSION + " - \u2730 " + type + " \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n", + 'background: #ff66a5; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff66a5; background: #030307; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'background: #ffc3dc; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;' ]; + (_a = window.console).log.apply(_a, args); + } + else if (window.console) { + window.console.log("PixiJS " + VERSION + " - " + type + " - http://www.pixijs.com/"); + } + saidHello = true; +} - // make sure alpha is set to 1 otherwise it will get rendered as invisible! - var cacheAlpha = this.alpha; - - this.alpha = 1; - - // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) - renderer.batch.flush(); - // this.filters= []; - - // next we find the dimensions of the untransformed object - // this function also calls updatetransform on all its children as part of the measuring. - // This means we don't need to update the transform again in this function - // TODO pass an object to clone too? saves having to create a new one each time! - var bounds = this.getLocalBounds().clone(); - - // add some padding! - if (this.filters) - { - var padding = this.filters[0].padding; - - bounds.pad(padding); - } - - bounds.ceil(settings.settings.RESOLUTION); - - // for now we cache the current renderTarget that the WebGL renderer is currently using. - // this could be more elegant.. - var cachedRenderTexture = renderer.renderTexture.current; - var cachedSourceFrame = renderer.renderTexture.sourceFrame; - var cachedProjectionTransform = renderer.projection.transform; - - // We also store the filter stack - I will definitely look to change how this works a little later down the line. - // const stack = renderer.filterManager.filterStack; - - // this renderTexture will be used to store the cached DisplayObject - var renderTexture = core.RenderTexture.create(bounds.width, bounds.height); - - var textureCacheId = "cacheAsBitmap_" + (utils.uid()); - - this._cacheData.textureCacheId = textureCacheId; - - core.BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); - core.Texture.addToCache(renderTexture, textureCacheId); - - // need to set // - var m = _tempMatrix; - - m.tx = -bounds.x; - m.ty = -bounds.y; - - // reset - this.transform.worldTransform.identity(); - - // set all properties to there original so we can render to a texture - this.render = this._cacheData.originalRender; - - renderer.render(this, renderTexture, true, m, true); - - // now restore the state be setting the new properties - renderer.projection.transform = cachedProjectionTransform; - renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame); - - // renderer.filterManager.filterStack = stack; - - this.render = this._renderCached; - // the rest is the same as for Canvas - this.updateTransform = this.displayObjectUpdateTransform; - this.calculateBounds = this._calculateCachedBounds; - this.getLocalBounds = this._getCachedLocalBounds; - - this._mask = null; - this.filterArea = null; - - // create our cached sprite - var cachedSprite = new sprite.Sprite(renderTexture); - - cachedSprite.transform.worldTransform = this.transform.worldTransform; - cachedSprite.anchor.x = -(bounds.x / bounds.width); - cachedSprite.anchor.y = -(bounds.y / bounds.height); - cachedSprite.alpha = cacheAlpha; - cachedSprite._bounds = this._bounds; - - this._cacheData.sprite = cachedSprite; - - this.transform._parentID = -1; - // restore the transform of the cached sprite to avoid the nasty flicker.. - if (!this.parent) - { - this.parent = renderer._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } - else - { - this.updateTransform(); - } - - // map the hit test.. - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); -}; - +var supported; /** - * Renders a cached version of the sprite with canvas + * Helper for checking for WebGL support. * - * @private - * @function _renderCachedCanvas - * @memberof PIXI.DisplayObject# - * @param {PIXI.Renderer} renderer - the WebGL renderer + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} Is WebGL supported. */ -display.DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) -{ - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) - { - return; +function isWebGLSupported() { + if (typeof supported === 'undefined') { + supported = (function supported() { + var contextOptions = { + stencil: true, + failIfMajorPerformanceCaveat: settings.settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT, + }; + try { + if (!window.WebGLRenderingContext) { + return false; + } + var canvas = document.createElement('canvas'); + var gl = (canvas.getContext('webgl', contextOptions) + || canvas.getContext('experimental-webgl', contextOptions)); + var success = !!(gl && gl.getContextAttributes().stencil); + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + if (loseContext) { + loseContext.loseContext(); + } + } + gl = null; + return success; + } + catch (e) { + return false; + } + })(); } + return supported; +} - this._initCachedDisplayObjectCanvas(renderer); - - this._cacheData.sprite.worldAlpha = this.worldAlpha; - this._cacheData.sprite._renderCanvas(renderer); -}; - -// TODO this can be the same as the WebGL version.. will need to do a little tweaking first though.. /** - * Prepares the Canvas renderer to cache the sprite + * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0). * - * @private - * @function _initCachedDisplayObjectCanvas - * @memberof PIXI.DisplayObject# - * @param {PIXI.Renderer} renderer - the WebGL renderer + * @example + * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1] + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The hexadecimal number to convert + * @param {number[]} [out=[]] - If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color where all values are floats. */ -display.DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) -{ - if (this._cacheData && this._cacheData.sprite) - { - return; - } - - // get bounds actually transforms the object for us already! - var bounds = this.getLocalBounds(); - - var cacheAlpha = this.alpha; - - this.alpha = 1; - - var cachedRenderTarget = renderer.context; - - bounds.ceil(settings.settings.RESOLUTION); - - var renderTexture = core.RenderTexture.create(bounds.width, bounds.height); - - var textureCacheId = "cacheAsBitmap_" + (utils.uid()); - - this._cacheData.textureCacheId = textureCacheId; - - core.BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); - core.Texture.addToCache(renderTexture, textureCacheId); - - // need to set // - var m = _tempMatrix; - - this.transform.localTransform.copyTo(m); - m.invert(); - - m.tx -= bounds.x; - m.ty -= bounds.y; - - // m.append(this.transform.worldTransform.) - // set all properties to there original so we can render to a texture - this.renderCanvas = this._cacheData.originalRenderCanvas; - - // renderTexture.render(this, m, true); - renderer.render(this, renderTexture, true, m, false); - - // now restore the state be setting the new properties - renderer.context = cachedRenderTarget; - - this.renderCanvas = this._renderCachedCanvas; - // the rest is the same as for WebGL - this.updateTransform = this.displayObjectUpdateTransform; - this.calculateBounds = this._calculateCachedBounds; - this.getLocalBounds = this._getCachedLocalBounds; - - this._mask = null; - this.filterArea = null; - - // create our cached sprite - var cachedSprite = new sprite.Sprite(renderTexture); - - cachedSprite.transform.worldTransform = this.transform.worldTransform; - cachedSprite.anchor.x = -(bounds.x / bounds.width); - cachedSprite.anchor.y = -(bounds.y / bounds.height); - cachedSprite.alpha = cacheAlpha; - cachedSprite._bounds = this._bounds; - - this._cacheData.sprite = cachedSprite; - - this.transform._parentID = -1; - // restore the transform of the cached sprite to avoid the nasty flicker.. - if (!this.parent) - { - this.parent = renderer._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } - else - { - this.updateTransform(); - } - - // map the hit test.. - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); -}; - +function hex2rgb(hex, out) { + if (out === void 0) { out = []; } + out[0] = ((hex >> 16) & 0xFF) / 255; + out[1] = ((hex >> 8) & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + return out; +} /** - * Calculates the bounds of the cached sprite + * Converts a hexadecimal color number to a string. * - * @private + * @example + * PIXI.utils.hex2string(0xffffff); // returns "#ffffff" + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex (e.g., `0xffffff`) + * @return {string} The string color (e.g., `"#ffffff"`). */ -display.DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() -{ - this._bounds.clear(); - this._cacheData.sprite.transform._worldID = this.transform._worldID; - this._cacheData.sprite._calculateBounds(); - this._lastBoundsID = this._boundsID; -}; - +function hex2string(hex) { + var hexString = hex.toString(16); + hexString = '000000'.substr(0, 6 - hexString.length) + hexString; + return "#" + hexString; +} /** - * Gets the bounds of the cached sprite. + * Converts a hexadecimal string to a hexadecimal color number. * - * @private - * @return {Rectangle} The local bounds. + * @example + * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff + * @memberof PIXI.utils + * @function string2hex + * @param {string} string - The string color (e.g., `"#ffffff"`) + * @return {number} Number in hexadecimal. */ -display.DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() -{ - return this._cacheData.sprite.getLocalBounds(); -}; - +function string2hex(string) { + if (typeof string === 'string' && string[0] === '#') { + string = string.substr(1); + } + return parseInt(string, 16); +} /** - * Destroys the cached sprite. + * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. * - * @private + * @example + * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. + * @return {number} Number in hexadecimal. */ -display.DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() -{ - this._cacheData.sprite._texture.destroy(true); - this._cacheData.sprite = null; - - core.BaseTexture.removeFromCache(this._cacheData.textureCacheId); - core.Texture.removeFromCache(this._cacheData.textureCacheId); - - this._cacheData.textureCacheId = null; -}; +function rgb2hex(rgb) { + return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0)); +} /** - * Destroys the cached object. + * Corrects PixiJS blend, takes premultiplied alpha into account * + * @memberof PIXI.utils + * @function mapPremultipliedBlendModes * @private - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value. - * Used when destroying containers, see the Container.destroy method. + * @return {Array} Mapped modes. */ -display.DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) -{ - this.cacheAsBitmap = false; - this.destroy(options); -}; - - -},{"@pixi/core":17,"@pixi/display":18,"@pixi/math":29,"@pixi/settings":39,"@pixi/sprite":42,"@pixi/utils":47}],33:[function(require,module,exports){ -/*! - * @pixi/mixin-get-child-by-name - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC +function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + pm[constants.BLEND_MODES.NORMAL_NPM] = constants.BLEND_MODES.NORMAL; + pm[constants.BLEND_MODES.ADD_NPM] = constants.BLEND_MODES.ADD; + pm[constants.BLEND_MODES.SCREEN_NPM] = constants.BLEND_MODES.SCREEN; + npm[constants.BLEND_MODES.NORMAL] = constants.BLEND_MODES.NORMAL_NPM; + npm[constants.BLEND_MODES.ADD] = constants.BLEND_MODES.ADD_NPM; + npm[constants.BLEND_MODES.SCREEN] = constants.BLEND_MODES.SCREEN_NPM; + var array = []; + array.push(npm); + array.push(pm); + return array; +} +/** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @const premultiplyBlendMode + * @type {Array} + */ +var premultiplyBlendMode = mapPremultipliedBlendModes(); +/** + * changes blendMode according to texture format * - * @pixi/mixin-get-child-by-name is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode - supposed blend mode + * @param {boolean} premultiplied - whether source is premultiplied + * @returns {number} true blend mode for this texture */ -'use strict'; - -var display = require('@pixi/display'); - +function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; +} /** - * The instance name of the object. + * combines rgb and alpha to out array * - * @memberof PIXI.DisplayObject# - * @member {string} name + * @memberof PIXI.utils + * @function premultiplyRgba + * @param {Float32Array|number[]} rgb - input rgb + * @param {number} alpha - alpha param + * @param {Float32Array} [out] - output + * @param {boolean} [premultiply=true] - do premultiply it + * @returns {Float32Array} vec4 rgba */ -display.DisplayObject.prototype.name = null; - +function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } + else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + return out; +} /** - * Returns the display object in the container. + * premultiplies tint * - * @method getChildByName - * @memberof PIXI.Container# - * @param {string} name - Instance name. - * @return {PIXI.DisplayObject} The child with the specified name. + * @memberof PIXI.utils + * @function premultiplyTint + * @param {number} tint - integer RGB + * @param {number} alpha - floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha */ -display.Container.prototype.getChildByName = function getChildByName(name) -{ - for (var i = 0; i < this.children.length; i++) - { - if (this.children[i].name === name) - { - return this.children[i]; - } +function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; } - - return null; -}; - - -},{"@pixi/display":18}],34:[function(require,module,exports){ -/*! - * @pixi/mixin-get-global-position - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + if (alpha === 0.0) { + return 0; + } + var R = ((tint >> 16) & 0xFF); + var G = ((tint >> 8) & 0xFF); + var B = (tint & 0xFF); + R = ((R * alpha) + 0.5) | 0; + G = ((G * alpha) + 0.5) | 0; + B = ((B * alpha) + 0.5) | 0; + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; +} +/** + * converts integer tint and float alpha to vec4 form, premultiplies by default * - * @pixi/mixin-get-global-position is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license + * @memberof PIXI.utils + * @function premultiplyTintToRgba + * @param {number} tint - input tint + * @param {number} alpha - alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] - do premultiply it + * @returns {Float32Array} vec4 rgba */ -'use strict'; - -var display = require('@pixi/display'); -var math = require('@pixi/math'); +function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = ((tint >> 16) & 0xFF) / 255.0; + out[1] = ((tint >> 8) & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + return out; +} /** - * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * Generic Mask Stack data structure * - * @method getGlobalPosition - * @memberof PIXI.DisplayObject# - * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to. - * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from - * being updated. This means the calculation returned MAY be out of date BUT will give you a - * nice performance boost. - * @return {PIXI.Point} The updated point. + * @memberof PIXI.utils + * @function createIndicesForQuads + * @param {number} size - Number of quads + * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size` + * @return {Uint16Array|Uint32Array} - Resulting index buffer */ -display.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) -{ - if ( point === void 0 ) point = new math.Point(); - if ( skipUpdate === void 0 ) skipUpdate = false; - - if (this.parent) - { - this.parent.toGlobal(this.position, point, skipUpdate); +function createIndicesForQuads(size, outBuffer) { + if (outBuffer === void 0) { outBuffer = null; } + // the total number of indices in our array, there are 6 points per quad. + var totalIndices = size * 6; + outBuffer = outBuffer || new Uint16Array(totalIndices); + if (outBuffer.length !== totalIndices) { + throw new Error("Out buffer length is incorrect, got " + outBuffer.length + " and expected " + totalIndices); } - else - { - point.x = this.position.x; - point.y = this.position.y; + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + outBuffer[i + 0] = j + 0; + outBuffer[i + 1] = j + 1; + outBuffer[i + 2] = j + 2; + outBuffer[i + 3] = j + 0; + outBuffer[i + 4] = j + 2; + outBuffer[i + 5] = j + 3; } + return outBuffer; +} - return point; -}; +function getBufferType(array) { + if (array.BYTES_PER_ELEMENT === 4) { + if (array instanceof Float32Array) { + return 'Float32Array'; + } + else if (array instanceof Uint32Array) { + return 'Uint32Array'; + } + return 'Int32Array'; + } + else if (array.BYTES_PER_ELEMENT === 2) { + if (array instanceof Uint16Array) { + return 'Uint16Array'; + } + } + else if (array.BYTES_PER_ELEMENT === 1) { + if (array instanceof Uint8Array) { + return 'Uint8Array'; + } + } + // TODO map out the rest of the array elements! + return null; +} +/* eslint-disable object-shorthand */ +var map = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array }; +function interleaveTypedArrays(arrays, sizes) { + var outSize = 0; + var stride = 0; + var views = {}; + for (var i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + var buffer = new ArrayBuffer(outSize * 4); + var out = null; + var littleOffset = 0; + for (var i = 0; i < arrays.length; i++) { + var size = sizes[i]; + var array = arrays[i]; + /* + @todo This is unsafe casting but consistent with how the code worked previously. Should it stay this way + or should and `getBufferTypeUnsafe` function be exposed that throws an Error if unsupported type is passed? + */ + var type = getBufferType(array); + if (!views[type]) { + views[type] = new map[type](buffer); + } + out = views[type]; + for (var j = 0; j < array.length; j++) { + var indexStart = ((j / size | 0) * stride) + littleOffset; + var index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); +} -},{"@pixi/display":18,"@pixi/math":29}],35:[function(require,module,exports){ -/*! - * @pixi/particles - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC +// Taken from the bit-twiddle package +/** + * Rounds to next power of two. * - * @pixi/particles is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license + * @function nextPow2 + * @memberof PIXI.utils + * @param {number} v - input value + * @return {number} */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var constants = require('@pixi/constants'); -var utils = require('@pixi/utils'); -var display = require('@pixi/display'); -var core = require('@pixi/core'); -var math = require('@pixi/math'); - +function nextPow2(v) { + v += v === 0 ? 1 : 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} /** - * The ParticleContainer class is a really fast version of the Container built solely for speed, - * so use when you need a lot of sprites or particles. - * - * The tradeoff of the ParticleContainer is that most advanced functionality will not work. - * ParticleContainer implements the basic object transform (position, scale, rotation) - * and some advanced functionality like tint (as of v4.5.6). + * Checks if a number is a power of two. * - * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. - * - * It's extremely easy to use: - * ```js - * let container = new ParticleContainer(); - * - * for (let i = 0; i < 100; ++i) - * { - * let sprite = PIXI.Sprite.from("myImage.png"); - * container.addChild(sprite); - * } - * ``` + * @function isPow2 + * @memberof PIXI.utils + * @param {number} v - input value + * @return {boolean} `true` if value is power of two + */ +function isPow2(v) { + return !(v & (v - 1)) && (!!v); +} +/** + * Computes ceil of log base 2 * - * And here you have a hundred sprites that will be rendered at the speed of light. + * @function log2 + * @memberof PIXI.utils + * @param {number} v - input value + * @return {number} logarithm base 2 + */ +function log2(v) { + var r = (v > 0xFFFF ? 1 : 0) << 4; + v >>>= r; + var shift = (v > 0xFF ? 1 : 0) << 3; + v >>>= shift; + r |= shift; + shift = (v > 0xF ? 1 : 0) << 2; + v >>>= shift; + r |= shift; + shift = (v > 0x3 ? 1 : 0) << 1; + v >>>= shift; + r |= shift; + return r | (v >> 1); +} + +/** + * Remove items from a javascript array without generating garbage * - * @class - * @extends PIXI.Container - * @memberof PIXI + * @function removeItems + * @memberof PIXI.utils + * @param {Array} arr - Array to remove elements from + * @param {number} startIdx - starting index + * @param {number} removeCount - how many to remove */ -var ParticleContainer = /*@__PURE__*/(function (Container) { - function ParticleContainer(maxSize, properties, batchSize, autoResize) - { - if ( maxSize === void 0 ) maxSize = 1500; - if ( batchSize === void 0 ) batchSize = 16384; - if ( autoResize === void 0 ) autoResize = false; +function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + var i; + if (startIdx >= length || removeCount === 0) { + return; + } + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); + var len = length - removeCount; + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + arr.length = len; +} - Container.call(this); +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) + { return 0; } + return n < 0 ? -1 : 1; +} - // Making sure the batch size is valid - // 65535 is max vertex index in the index buffer (see ParticleRenderer) - // so max number of particles is 65536 / 4 = 16384 - var maxBatchSize = 16384; +var nextUid = 0; +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ +function uid() { + return ++nextUid; +} - if (batchSize > maxBatchSize) - { - batchSize = maxBatchSize; +// A map of warning messages already fired +var warnings = {}; +/** + * Helper for warning developers about deprecated features & settings. + * A stack track for warnings is given; useful for tracking-down where + * deprecated methods/properties/classes are being used within the code. + * + * @memberof PIXI.utils + * @function deprecation + * @param {string} version - The version where the feature became deprecated + * @param {string} message - Message should include what is deprecated, where, and the new solution + * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack + * this is mostly to ignore internal deprecation calls. + */ +function deprecation(version, message, ignoreDepth) { + if (ignoreDepth === void 0) { ignoreDepth = 3; } + // Ignore duplicat + if (warnings[message]) { + return; + } + /* eslint-disable no-console */ + var stack = new Error().stack; + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + } + else { + // chop off the stack trace which includes PixiJS internal calls + stack = stack.split('\n').splice(ignoreDepth).join('\n'); + if (console.groupCollapsed) { + console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version); + console.warn(stack); + console.groupEnd(); } + else { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + console.warn(stack); + } + } + /* eslint-enable no-console */ + warnings[message] = true; +} - /** - * Set properties to be dynamic (true) / static (false) - * - * @member {boolean[]} - * @private - */ - this._properties = [false, true, false, false, false]; - - /** - * @member {number} - * @private - */ - this._maxSize = maxSize; - - /** - * @member {number} - * @private - */ - this._batchSize = batchSize; - - /** - * @member {Array} - * @private - */ - this._buffers = null; - - /** - * for every batch stores _updateID corresponding to the last change in that batch - * @member {number[]} - * @private - */ - this._bufferUpdateIDs = []; - - /** - * when child inserted, removed or changes position this number goes up - * @member {number[]} - * @private - */ - this._updateID = 0; - - /** - * @member {boolean} - * - */ - this.interactiveChildren = false; - - /** - * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` - * to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - * @see PIXI.BLEND_MODES - */ - this.blendMode = constants.BLEND_MODES.NORMAL; - - /** - * If true, container allocates more batches in case there are more than `maxSize` particles. - * @member {boolean} - * @default false - */ - this.autoResize = autoResize; - - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * Default to true here as performance is usually the priority for particles. - * - * @member {boolean} - * @default true - */ - this.roundPixels = true; +/** + * @todo Describe property usage + * + * @static + * @name ProgramCache + * @memberof PIXI.utils + * @type {Object} + */ +var ProgramCache = {}; +/** + * @todo Describe property usage + * + * @static + * @name TextureCache + * @memberof PIXI.utils + * @type {Object} + */ +var TextureCache = Object.create(null); +/** + * @todo Describe property usage + * + * @static + * @name BaseTextureCache + * @memberof PIXI.utils + * @type {Object} + */ +var BaseTextureCache = Object.create(null); +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key; + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key; + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} +/** + * Creates a Canvas element of the given size to be used as a target for rendering to. + * + * @class + * @memberof PIXI.utils + */ +var CanvasRenderTarget = /** @class */ (function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { /** - * The texture used to render the children. + * The Canvas object that belongs to this CanvasRenderTarget. * - * @readonly - * @member {PIXI.BaseTexture} + * @member {HTMLCanvasElement} */ - this.baseTexture = null; - - this.setProperties(properties); - + this.canvas = document.createElement('canvas'); /** - * The tint applied to the container. - * This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. * - * @private - * @member {number} - * @default 0xFFFFFF + * @member {CanvasRenderingContext2D} */ - this._tint = 0; - this.tintRgb = new Float32Array(4); - this.tint = 0xFFFFFF; + this.context = this.canvas.getContext('2d'); + this.resolution = resolution || settings.settings.RESOLUTION; + this.resize(width, height); } - - if ( Container ) ParticleContainer.__proto__ = Container; - ParticleContainer.prototype = Object.create( Container && Container.prototype ); - ParticleContainer.prototype.constructor = ParticleContainer; - - var prototypeAccessors = { tint: { configurable: true } }; - - /** - * Sets the private properties array to dynamic / static based on the passed properties object - * - * @param {object} properties - The properties to be uploaded - */ - ParticleContainer.prototype.setProperties = function setProperties (properties) - { - if (properties) - { - this._properties[0] = 'vertices' in properties || 'scale' in properties - ? !!properties.vertices || !!properties.scale : this._properties[0]; - this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; - this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; - this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; - this._properties[4] = 'tint' in properties || 'alpha' in properties - ? !!properties.tint || !!properties.alpha : this._properties[4]; - } - }; - /** - * Updates the object transform for rendering + * Clears the canvas that was created by the CanvasRenderTarget class. * * @private */ - ParticleContainer.prototype.updateTransform = function updateTransform () - { - // TODO don't need to! - this.displayObjectUpdateTransform(); - // PIXI.Container.prototype.updateTransform.call( this ); - }; - - /** - * The tint applied to the container. This is a hex value. - * A value of 0xFFFFFF will remove any tint effect. - ** IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. - * @member {number} - * @default 0xFFFFFF - */ - prototypeAccessors.tint.get = function () - { - return this._tint; - }; - - prototypeAccessors.tint.set = function (value) // eslint-disable-line require-jsdoc - { - this._tint = value; - utils.hex2rgb(value, this.tintRgb); + CanvasRenderTarget.prototype.clear = function () { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); }; - /** - * Renders the container using the WebGL renderer + * Resizes the canvas to the specified width and height. * - * @private - * @param {PIXI.Renderer} renderer - The webgl renderer + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas */ - ParticleContainer.prototype.render = function render (renderer) - { - var this$1 = this; - - if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) - { - return; - } - - if (!this.baseTexture) - { - this.baseTexture = this.children[0]._texture.baseTexture; - if (!this.baseTexture.valid) - { - this.baseTexture.once('update', function () { return this$1.onChildrenChange(0); }); - } - } - - renderer.batch.setObjectRenderer(renderer.plugins.particle); - renderer.plugins.particle.render(this); + CanvasRenderTarget.prototype.resize = function (width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; }; - /** - * Set the flag that static data should be updated to true + * Destroys this canvas. * - * @private - * @param {number} smallestChildIndex - The smallest child index */ - ParticleContainer.prototype.onChildrenChange = function onChildrenChange (smallestChildIndex) - { - var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); - - while (this._bufferUpdateIDs.length < bufferIndex) - { - this._bufferUpdateIDs.push(0); - } - this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + CanvasRenderTarget.prototype.destroy = function () { + this.context = null; + this.canvas = null; }; + Object.defineProperty(CanvasRenderTarget.prototype, "width", { + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + get: function () { + return this.canvas.width; + }, + set: function (val) { + this.canvas.width = val; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CanvasRenderTarget.prototype, "height", { + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + get: function () { + return this.canvas.height; + }, + set: function (val) { + this.canvas.height = val; + }, + enumerable: false, + configurable: true + }); + return CanvasRenderTarget; +}()); - ParticleContainer.prototype.dispose = function dispose () - { - if (this._buffers) - { - for (var i = 0; i < this._buffers.length; ++i) - { - this._buffers[i].destroy(); +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI.utils + * @function trimCanvas + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + var width = canvas.width; + var height = canvas.height; + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + var bound = { + top: null, + left: null, + right: null, + bottom: null, + }; + var data = null; + var i; + var x; + var y; + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = (i / 4) % width; + y = ~~((i / 4) / width); + if (bound.top === null) { + bound.top = y; + } + if (bound.left === null) { + bound.left = x; + } + else if (x < bound.left) { + bound.left = x; + } + if (bound.right === null) { + bound.right = x + 1; + } + else if (bound.right < x) { + bound.right = x + 1; + } + if (bound.bottom === null) { + bound.bottom = y; + } + else if (bound.bottom < y) { + bound.bottom = y; } - - this._buffers = null; } + } + if (bound.top !== null) { + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + data = context.getImageData(bound.left, bound.top, width, height); + } + return { + height: height, + width: width, + data: data, }; - - /** - * Destroys the container - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their - * destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - ParticleContainer.prototype.destroy = function destroy (options) - { - Container.prototype.destroy.call(this, options); - - this.dispose(); - - this._properties = null; - this._buffers = null; - this._bufferUpdateIDs = null; - }; - - Object.defineProperties( ParticleContainer.prototype, prototypeAccessors ); - - return ParticleContainer; -}(display.Container)); +} /** - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that - * they now share 4 bytes on the vertex buffer + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} * - * Heavily inspired by LibGDX's ParticleBuffer: - * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + * @static + * @constant {RegExp|string} DATA_URI + * @memberof PIXI + * @example data:image/png;base64 */ +var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; /** - * The particle buffer manages the static and dynamic buffers for a particle container. + * @memberof PIXI.utils + * @interface DecomposedDataUri + */ +/** + * type, eg. `image` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} mediaType + */ +/** + * Sub type, eg. `png` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} subType + */ +/** + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} charset + */ +/** + * Data encoding, eg. `base64` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} encoding + */ +/** + * The actual data + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} data + */ +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. * - * @class - * @private - * @memberof PIXI + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined */ -var ParticleBuffer = function ParticleBuffer(properties, dynamicPropertyFlags, size) -{ - this.geometry = new core.Geometry(); - - this.indexBuffer = null; - - /** - * The number of particles the buffer can hold - * - * @private - * @member {number} - */ - this.size = size; - - /** - * A list of the properties that are dynamic. - * - * @private - * @member {object[]} - */ - this.dynamicProperties = []; - - /** - * A list of the properties that are static. - * - * @private - * @member {object[]} - */ - this.staticProperties = []; - - for (var i = 0; i < properties.length; ++i) - { - var property = properties[i]; - - // Make copy of properties object so that when we edit the offset it doesn't - // change all other instances of the object literal - property = { - attributeName: property.attributeName, - size: property.size, - uploadFunction: property.uploadFunction, - type: property.type || constants.TYPES.FLOAT, - offset: property.offset, +function decomposeDataUri(dataUri) { + var dataUriMatch = DATA_URI.exec(dataUri); + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, + data: dataUriMatch[5], }; - - if (dynamicPropertyFlags[i]) - { - this.dynamicProperties.push(property); - } - else - { - this.staticProperties.push(property); - } } + return undefined; +} - this.staticStride = 0; - this.staticBuffer = null; - this.staticData = null; - this.staticDataUint32 = null; - - this.dynamicStride = 0; - this.dynamicBuffer = null; - this.dynamicData = null; - this.dynamicDataUint32 = null; - - this._updateID = 0; - - this.initBuffers(); -}; - +var tempAnchor; /** - * Sets up the renderer context and necessary buffers. + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! * - * @private + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). */ -ParticleBuffer.prototype.initBuffers = function initBuffers () -{ - var geometry = this.geometry; - - var dynamicOffset = 0; - - /** - * Holds the indices of the geometry (quads) to draw - * - * @member {Uint16Array} - * @private - */ - this.indexBuffer = new core.Buffer(utils.createIndicesForQuads(this.size), true, true); - geometry.addIndex(this.indexBuffer); - - this.dynamicStride = 0; - - for (var i = 0; i < this.dynamicProperties.length; ++i) - { - var property = this.dynamicProperties[i]; - - property.offset = dynamicOffset; - dynamicOffset += property.size; - this.dynamicStride += property.size; - } - - var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); - - this.dynamicData = new Float32Array(dynBuffer); - this.dynamicDataUint32 = new Uint32Array(dynBuffer); - this.dynamicBuffer = new core.Buffer(this.dynamicData, false, false); - - // static // - var staticOffset = 0; - - this.staticStride = 0; - - for (var i$1 = 0; i$1 < this.staticProperties.length; ++i$1) - { - var property$1 = this.staticProperties[i$1]; - - property$1.offset = staticOffset; - staticOffset += property$1.size; - this.staticStride += property$1.size; +function determineCrossOrigin(url, loc) { + if (loc === void 0) { loc = window.location; } + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; } - - var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); - - this.staticData = new Float32Array(statBuffer); - this.staticDataUint32 = new Uint32Array(statBuffer); - this.staticBuffer = new core.Buffer(this.staticData, true, false); - - for (var i$2 = 0; i$2 < this.dynamicProperties.length; ++i$2) - { - var property$2 = this.dynamicProperties[i$2]; - - geometry.addAttribute( - property$2.attributeName, - this.dynamicBuffer, - 0, - property$2.type === constants.TYPES.UNSIGNED_BYTE, - property$2.type, - this.dynamicStride * 4, - property$2.offset * 4 - ); + // default is window.location + loc = loc || window.location; + if (!tempAnchor) { + tempAnchor = document.createElement('a'); } - - for (var i$3 = 0; i$3 < this.staticProperties.length; ++i$3) - { - var property$3 = this.staticProperties[i$3]; - - geometry.addAttribute( - property$3.attributeName, - this.staticBuffer, - 0, - property$3.type === constants.TYPES.UNSIGNED_BYTE, - property$3.type, - this.staticStride * 4, - property$3.offset * 4 - ); + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + var parsedUrl = _url.parse(tempAnchor.href); + var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); + // if cross origin + if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) { + return 'anonymous'; } -}; + return ''; +} /** - * Uploads the dynamic properties. + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls * - * @private - * @param {PIXI.DisplayObject[]} children - The children to upload. - * @param {number} startIndex - The index to start at. - * @param {number} amount - The number to upload. + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset */ -ParticleBuffer.prototype.uploadDynamic = function uploadDynamic (children, startIndex, amount) -{ - for (var i = 0; i < this.dynamicProperties.length; i++) - { - var property = this.dynamicProperties[i]; - - property.uploadFunction(children, startIndex, amount, - property.type === constants.TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, - this.dynamicStride, property.offset); +function getResolutionOfUrl(url, defaultValue) { + var resolution = settings.settings.RETINA_PREFIX.exec(url); + if (resolution) { + return parseFloat(resolution[1]); } - - this.dynamicBuffer._updateID++; -}; + return defaultValue !== undefined ? defaultValue : 1; +} /** - * Uploads the static properties. + * Generalized convenience utilities for PIXI. + * @example + * // Extend PIXI's internal Event Emitter. + * class MyEmitter extends PIXI.utils.EventEmitter { + * constructor() { + * super(); + * console.log("Emitter created!"); + * } + * } * - * @private - * @param {PIXI.DisplayObject[]} children - The children to upload. - * @param {number} startIndex - The index to start at. - * @param {number} amount - The number to upload. + * // Get info on current device + * console.log(PIXI.utils.isMobile); + * + * // Convert hex color to string + * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" + * @namespace PIXI.utils */ -ParticleBuffer.prototype.uploadStatic = function uploadStatic (children, startIndex, amount) -{ - for (var i = 0; i < this.staticProperties.length; i++) - { - var property = this.staticProperties[i]; - property.uploadFunction(children, startIndex, amount, - property.type === constants.TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, - this.staticStride, property.offset); +Object.defineProperty(exports, 'isMobile', { + enumerable: true, + get: function () { + return settings.isMobile; } +}); +exports.EventEmitter = eventemitter3; +exports.earcut = earcut; +exports.url = _url__default; +exports.BaseTextureCache = BaseTextureCache; +exports.CanvasRenderTarget = CanvasRenderTarget; +exports.DATA_URI = DATA_URI; +exports.ProgramCache = ProgramCache; +exports.TextureCache = TextureCache; +exports.clearTextureCache = clearTextureCache; +exports.correctBlendMode = correctBlendMode; +exports.createIndicesForQuads = createIndicesForQuads; +exports.decomposeDataUri = decomposeDataUri; +exports.deprecation = deprecation; +exports.destroyTextureCache = destroyTextureCache; +exports.determineCrossOrigin = determineCrossOrigin; +exports.getBufferType = getBufferType; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.interleaveTypedArrays = interleaveTypedArrays; +exports.isPow2 = isPow2; +exports.isWebGLSupported = isWebGLSupported; +exports.log2 = log2; +exports.nextPow2 = nextPow2; +exports.premultiplyBlendMode = premultiplyBlendMode; +exports.premultiplyRgba = premultiplyRgba; +exports.premultiplyTint = premultiplyTint; +exports.premultiplyTintToRgba = premultiplyTintToRgba; +exports.removeItems = removeItems; +exports.rgb2hex = rgb2hex; +exports.sayHello = sayHello; +exports.sign = sign; +exports.skipHello = skipHello; +exports.string2hex = string2hex; +exports.trimCanvas = trimCanvas; +exports.uid = uid; - this.staticBuffer._updateID++; -}; -/** - * Destroys the ParticleBuffer. - * - * @private - */ -ParticleBuffer.prototype.destroy = function destroy () -{ - this.indexBuffer = null; - - this.dynamicProperties = null; - // this.dynamicBuffer.destroy(); - this.dynamicBuffer = null; - this.dynamicData = null; - this.dynamicDataUint32 = null; - - this.staticProperties = null; - // this.staticBuffer.destroy(); - this.staticBuffer = null; - this.staticData = null; - this.staticDataUint32 = null; - // all buffers are destroyed inside geometry - this.geometry.destroy(); -}; +},{"@pixi/constants":7,"@pixi/settings":30,"earcut":39,"eventemitter3":41,"url":70}],39:[function(require,module,exports){ +'use strict'; -var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n"; +module.exports = earcut; +module.exports.default = earcut; -var fragment = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}"; +function earcut(data, holeIndices, dim) { -/** - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now - * share 4 bytes on the vertex buffer - * - * Heavily inspired by LibGDX's ParticleRenderer: - * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java - */ + dim = dim || 2; -/** - * Renderer for Particles that is designer for speed over feature set. - * - * @class - * @memberof PIXI - */ -var ParticleRenderer = /*@__PURE__*/(function (ObjectRenderer) { - function ParticleRenderer(renderer) - { - ObjectRenderer.call(this, renderer); + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; - // 65535 is max vertex index in the index buffer (see ParticleRenderer) - // so max number of particles is 65536 / 4 = 16384 - // and max number of element in the index buffer is 16384 * 6 = 98304 - // Creating a full index buffer, overhead is 98304 * 2 = 196Ko - // let numIndices = 98304; + if (!outerNode || outerNode.next === outerNode.prev) return triangles; - /** - * The default shader that is used if a sprite doesn't have a more specific one. - * - * @member {PIXI.Shader} - */ - this.shader = null; + var minX, minY, maxX, maxY, x, y, invSize; - this.properties = null; + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); - this.tempMatrix = new math.Matrix(); + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; - this.properties = [ - // verticesData - { - attributeName: 'aVertexPosition', - size: 2, - uploadFunction: this.uploadVertices, - offset: 0, - }, - // positionData - { - attributeName: 'aPositionCoord', - size: 2, - uploadFunction: this.uploadPosition, - offset: 0, - }, - // rotationData - { - attributeName: 'aRotation', - size: 1, - uploadFunction: this.uploadRotation, - offset: 0, - }, - // uvsData - { - attributeName: 'aTextureCoord', - size: 2, - uploadFunction: this.uploadUvs, - offset: 0, - }, - // tintData - { - attributeName: 'aColor', - size: 1, - type: constants.TYPES.UNSIGNED_BYTE, - uploadFunction: this.uploadTint, - offset: 0, - } ]; + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } - this.shader = core.Shader.from(vertex, fragment, {}); + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 1 / invSize : 0; } - if ( ObjectRenderer ) ParticleRenderer.__proto__ = ObjectRenderer; - ParticleRenderer.prototype = Object.create( ObjectRenderer && ObjectRenderer.prototype ); - ParticleRenderer.prototype.constructor = ParticleRenderer; + earcutLinked(outerNode, triangles, dim, minX, minY, invSize); - /** - * Renders the particle container object. - * - * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer - */ - ParticleRenderer.prototype.render = function render (container) - { - var children = container.children; - var maxSize = container._maxSize; - var batchSize = container._batchSize; - var renderer = this.renderer; - var totalChildren = children.length; + return triangles; +} - if (totalChildren === 0) - { - return; - } - else if (totalChildren > maxSize && !container.autoResize) - { - totalChildren = maxSize; - } +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; - var buffers = container._buffers; + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } - if (!buffers) - { - buffers = container._buffers = this.generateBuffers(container); - } + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } - var baseTexture = children[0]._texture.baseTexture; + return last; +} - // if the uvs have not updated then no point rendering just yet! - this.renderer.state.setBlendMode(utils.correctBlendMode(container.blendMode, baseTexture.alphaMode)); +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; - var gl = renderer.gl; + var p = start, + again; + do { + again = false; - var m = container.worldTransform.copyTo(this.tempMatrix); + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; - m.prepend(renderer.globalUniforms.uniforms.projectionMatrix); + } else { + p = p.next; + } + } while (again || p !== end); - this.shader.uniforms.translationMatrix = m.toArray(true); + return end; +} - this.shader.uniforms.uColor = utils.premultiplyRgba(container.tintRgb, - container.worldAlpha, this.shader.uniforms.uColor, baseTexture.alphaMode); +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; - this.shader.uniforms.uSampler = baseTexture; + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); - this.renderer.shader.bind(this.shader); + var stop = ear, + prev, next; - var updateStatic = false; + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; - // now lets upload and render the buffers.. - for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) - { - var amount = (totalChildren - i); + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); - if (amount > batchSize) - { - amount = batchSize; - } + removeNode(ear); - if (j >= buffers.length) - { - buffers.push(this._generateOneMoreBuffer(container)); - } + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; - var buffer = buffers[j]; + continue; + } - // we always upload the dynamic - buffer.uploadDynamic(children, i, amount); + ear = next; - var bid = container._bufferUpdateIDs[j] || 0; + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); - updateStatic = updateStatic || (buffer._updateID < bid); - // we only upload the static content when we have to! - if (updateStatic) - { - buffer._updateID = container._updateID; - buffer.uploadStatic(children, i, amount); + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); } - // bind the buffer - renderer.geometry.bind(buffer.geometry); - gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + break; } - }; - - /** - * Creates one particle buffer for each child in the container we want to render and updates internal properties - * - * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer - * @return {PIXI.ParticleBuffer[]} The buffers - * @private - */ - ParticleRenderer.prototype.generateBuffers = function generateBuffers (container) - { - var buffers = []; - var size = container._maxSize; - var batchSize = container._batchSize; - var dynamicPropertyFlags = container._properties; + } +} - for (var i = 0; i < size; i += batchSize) - { - buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize)); - } +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; - return buffers; - }; + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear - /** - * Creates one more particle buffer, because container has autoResize feature - * - * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer - * @return {PIXI.ParticleBuffer} generated buffer - * @private - */ - ParticleRenderer.prototype._generateOneMoreBuffer = function _generateOneMoreBuffer (container) - { - var batchSize = container._batchSize; - var dynamicPropertyFlags = container._properties; + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; - return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize); - }; + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } - /** - * Uploads the vertices. - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their vertices uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadVertices = function uploadVertices (children, startIndex, amount, array, stride, offset) - { - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; + return true; +} - for (var i = 0; i < amount; ++i) - { - var sprite = children[startIndex + i]; - var texture = sprite._texture; - var sx = sprite.scale.x; - var sy = sprite.scale.y; - var trim = texture.trim; - var orig = texture.orig; +function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; - if (trim) - { - // if the sprite is trimmed and is not a tilingsprite then we need to add the - // extra space before transforming the sprite coords.. - w1 = trim.x - (sprite.anchor.x * orig.width); - w0 = w1 + trim.width; + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear - h1 = trim.y - (sprite.anchor.y * orig.height); - h0 = h1 + trim.height; - } - else - { - w0 = (orig.width) * (1 - sprite.anchor.x); - w1 = (orig.width) * -sprite.anchor.x; + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); - h0 = orig.height * (1 - sprite.anchor.y); - h1 = orig.height * -sprite.anchor.y; - } + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, invSize), + maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); - array[offset] = w1 * sx; - array[offset + 1] = h1 * sy; + var p = ear.prevZ, + n = ear.nextZ; - array[offset + stride] = w0 * sx; - array[offset + stride + 1] = h1 * sy; + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; - array[offset + (stride * 2)] = w0 * sx; - array[offset + (stride * 2) + 1] = h0 * sy; + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } - array[offset + (stride * 3)] = w1 * sx; - array[offset + (stride * 3) + 1] = h0 * sy; + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } - offset += stride * 4; - } - }; + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } - /** - * Uploads the position. - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their positions uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadPosition = function uploadPosition (children, startIndex, amount, array, stride, offset) - { - for (var i = 0; i < amount; i++) - { - var spritePosition = children[startIndex + i].position; + return true; +} - array[offset] = spritePosition.x; - array[offset + 1] = spritePosition.y; +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; - array[offset + stride] = spritePosition.x; - array[offset + stride + 1] = spritePosition.y; + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { - array[offset + (stride * 2)] = spritePosition.x; - array[offset + (stride * 2) + 1] = spritePosition.y; + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); - array[offset + (stride * 3)] = spritePosition.x; - array[offset + (stride * 3) + 1] = spritePosition.y; + // remove two nodes involved + removeNode(p); + removeNode(p.next); - offset += stride * 4; + p = start = b; } - }; - - /** - * Uploads the rotiation. - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their rotation uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadRotation = function uploadRotation (children, startIndex, amount, array, stride, offset) - { - for (var i = 0; i < amount; i++) - { - var spriteRotation = children[startIndex + i].rotation; + p = p.next; + } while (p !== start); - array[offset] = spriteRotation; - array[offset + stride] = spriteRotation; - array[offset + (stride * 2)] = spriteRotation; - array[offset + (stride * 3)] = spriteRotation; + return filterPoints(p); +} - offset += stride * 4; - } - }; +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); - /** - * Uploads the Uvs - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their rotation uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadUvs = function uploadUvs (children, startIndex, amount, array, stride, offset) - { - for (var i = 0; i < amount; ++i) - { - var textureUvs = children[startIndex + i]._texture._uvs; + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); - if (textureUvs) - { - array[offset] = textureUvs.x0; - array[offset + 1] = textureUvs.y0; + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize); + earcutLinked(c, triangles, dim, minX, minY, invSize); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} - array[offset + stride] = textureUvs.x1; - array[offset + stride + 1] = textureUvs.y1; +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; - array[offset + (stride * 2)] = textureUvs.x2; - array[offset + (stride * 2) + 1] = textureUvs.y2; + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } - array[offset + (stride * 3)] = textureUvs.x3; - array[offset + (stride * 3) + 1] = textureUvs.y3; + queue.sort(compareX); - offset += stride * 4; - } - else - { - // TODO you know this can be easier! - array[offset] = 0; - array[offset + 1] = 0; + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } - array[offset + stride] = 0; - array[offset + stride + 1] = 0; + return outerNode; +} - array[offset + (stride * 2)] = 0; - array[offset + (stride * 2) + 1] = 0; +function compareX(a, b) { + return a.x - b.x; +} - array[offset + (stride * 3)] = 0; - array[offset + (stride * 3) + 1] = 0; +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} - offset += stride * 4; +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; } } - }; + p = p.next; + } while (p !== outerNode); - /** - * Uploads the tint. - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their rotation uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadTint = function uploadTint (children, startIndex, amount, array, stride, offset) - { - for (var i = 0; i < amount; ++i) - { - var sprite = children[startIndex + i]; - var premultiplied = sprite._texture.baseTexture.alphaMode > 0; - var alpha = sprite.alpha; - // we dont call extra function if alpha is 1.0, that's faster - var argb = alpha < 1.0 && premultiplied ? utils.premultiplyTint(sprite._tintRGB, alpha) - : sprite._tintRGB + (alpha * 255 << 24); + if (!m) return null; - array[offset] = argb; - array[offset + stride] = argb; - array[offset + (stride * 2)] = argb; - array[offset + (stride * 3)] = argb; + if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint - offset += stride * 4; - } - }; + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point - /** - * Destroys the ParticleRenderer. - */ - ParticleRenderer.prototype.destroy = function destroy () - { - ObjectRenderer.prototype.destroy.call(this); + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; - if (this.shader) - { - this.shader.destroy(); - this.shader = null; - } + p = m; - this.tempMatrix = null; - }; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { - return ParticleRenderer; -}(core.ObjectRenderer)); + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential -exports.ParticleContainer = ParticleContainer; -exports.ParticleRenderer = ParticleRenderer; + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); -},{"@pixi/constants":16,"@pixi/core":17,"@pixi/display":18,"@pixi/math":29,"@pixi/utils":47}],36:[function(require,module,exports){ -(function (global){ -/*! - * @pixi/polyfill - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/polyfill is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; + return m; +} -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} -var es6PromisePolyfill = require('es6-promise-polyfill'); -var objectAssign = _interopDefault(require('object-assign')); +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); -// Support for IE 9 - 11 which does not include Promises -if (!window.Promise) -{ - window.Promise = es6PromisePolyfill.Polyfill; + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); } -// References: +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; -if (!Object.assign) -{ - Object.assign = objectAssign; -} + do { + p = list; + list = null; + tail = null; + numMerges = 0; -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; -// References: -// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ -// https://gist.github.com/1579671 -// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision -// https://gist.github.com/timhall/4078614 -// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + while (pSize > 0 || (qSize > 0 && q)) { -// Expected to be used with Browserfiy -// Browserify automatically detects the use of `global` and passes the -// correct reference of `global`, `self`, and finally `window` + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } -var ONE_FRAME_TIME = 16; + if (tail) tail.nextZ = e; + else list = e; -// Date.now -if (!(Date.now && Date.prototype.getTime)) -{ - Date.now = function now() - { - return new Date().getTime(); - }; -} + e.prevZ = tail; + tail = e; + } -// performance.now -if (!(commonjsGlobal.performance && commonjsGlobal.performance.now)) -{ - var startTime = Date.now(); + p = q; + } - if (!commonjsGlobal.performance) - { - commonjsGlobal.performance = {}; - } + tail.nextZ = null; + inSize *= 2; - commonjsGlobal.performance.now = function () { return Date.now() - startTime; }; + } while (numMerges > 1); + + return list; } -// requestAnimationFrame -var lastTime = Date.now(); -var vendors = ['ms', 'moz', 'webkit', 'o']; +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) * invSize; + y = 32767 * (y - minY) * invSize; -for (var x = 0; x < vendors.length && !commonjsGlobal.requestAnimationFrame; ++x) -{ - var p = vendors[x]; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; - commonjsGlobal.requestAnimationFrame = commonjsGlobal[(p + "RequestAnimationFrame")]; - commonjsGlobal.cancelAnimationFrame = commonjsGlobal[(p + "CancelAnimationFrame")] || commonjsGlobal[(p + "CancelRequestAnimationFrame")]; + return x | (y << 1); } -if (!commonjsGlobal.requestAnimationFrame) -{ - commonjsGlobal.requestAnimationFrame = function (callback) { - if (typeof callback !== 'function') - { - throw new TypeError((callback + "is not a function")); - } +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; + p = p.next; + } while (p !== start); - var currentTime = Date.now(); - var delay = ONE_FRAME_TIME + lastTime - currentTime; + return leftmost; +} - if (delay < 0) - { - delay = 0; - } +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} - lastTime = currentTime; +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case +} - return setTimeout(function () { - lastTime = Date.now(); - callback(performance.now()); - }, delay); - }; +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); } -if (!commonjsGlobal.cancelAnimationFrame) -{ - commonjsGlobal.cancelAnimationFrame = function (id) { return clearTimeout(id); }; +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; } -// References: -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + var o1 = sign(area(p1, q1, p2)); + var o2 = sign(area(p1, q1, q2)); + var o3 = sign(area(p2, q2, p1)); + var o4 = sign(area(p2, q2, q1)); -if (!Math.sign) -{ - Math.sign = function mathSign(x) - { - x = Number(x); + if (o1 !== o2 && o3 !== o4) return true; // general case - if (x === 0 || isNaN(x)) - { - return x; - } + if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 - return x > 0 ? 1 : -1; - }; + return false; } -// References: -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger - -if (!Number.isInteger) -{ - Number.isInteger = function numberIsInteger(value) - { - return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; - }; +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); } -if (!window.ArrayBuffer) -{ - window.ArrayBuffer = Array; +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; } -if (!window.Float32Array) -{ - window.Float32Array = Array; -} +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); -if (!window.Uint32Array) -{ - window.Uint32Array = Array; + return false; } -if (!window.Uint16Array) -{ - window.Uint16Array = Array; +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; } -if (!window.Uint8Array) -{ - window.Uint8Array = Array; -} +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); -if (!window.Int32Array) -{ - window.Int32Array = Array; + return inside; } +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"es6-promise-polyfill":49,"object-assign":54}],37:[function(require,module,exports){ -/*! - * @pixi/prepare - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/prepare is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); + a.next = b; + b.prev = a; -var settings = require('@pixi/settings'); -var core = require('@pixi/core'); -var graphics = require('@pixi/graphics'); -var ticker = require('@pixi/ticker'); -var display = require('@pixi/display'); -var text = require('@pixi/text'); + a2.next = an; + an.prev = a2; -/** - * Default number of uploads per frame using prepare plugin. - * - * @static - * @memberof PIXI.settings - * @name UPLOADS_PER_FRAME - * @type {number} - * @default 4 - */ -settings.settings.UPLOADS_PER_FRAME = 4; + b2.next = a2; + a2.prev = b2; -/** - * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified - * number of items per frame. - * - * @class - * @memberof PIXI.prepare - */ -var CountLimiter = function CountLimiter(maxItemsPerFrame) -{ - /** - * The maximum number of items that can be prepared each frame. - * @type {number} - * @private - */ - this.maxItemsPerFrame = maxItemsPerFrame; - /** - * The number of items that can be prepared in the current frame. - * @type {number} - * @private - */ - this.itemsLeft = 0; -}; + bp.next = b2; + b2.prev = bp; -/** - * Resets any counting properties to start fresh on a new frame. - */ -CountLimiter.prototype.beginFrame = function beginFrame () -{ - this.itemsLeft = this.maxItemsPerFrame; -}; + return b2; +} -/** - * Checks to see if another item can be uploaded. This should only be called once per item. - * @return {boolean} If the item is allowed to be uploaded. - */ -CountLimiter.prototype.allowedToUpload = function allowedToUpload () -{ - return this.itemsLeft-- > 0; -}; +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); -/** - * The prepare manager provides functionality to upload content to the GPU. - * - * BasePrepare handles basic queuing functionality and is extended by - * {@link PIXI.prepare.Prepare} and {@link PIXI.prepare.CanvasPrepare} - * to provide preparation capabilities specific to their respective renderers. - * - * @example - * // Create a sprite - * const sprite = PIXI.Sprite.from('something.png'); - * - * // Load object into GPU - * app.renderer.plugins.prepare.upload(sprite, () => { - * - * //Texture(s) has been uploaded to GPU - * app.stage.addChild(sprite); - * - * }) - * - * @abstract - * @class - * @memberof PIXI.prepare - */ -var BasePrepare = function BasePrepare(renderer) -{ - var this$1 = this; + if (!last) { + p.prev = p; + p.next = p; - /** - * The limiter to be used to control how quickly items are prepared. - * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} - */ - this.limiter = new CountLimiter(settings.settings.UPLOADS_PER_FRAME); - - /** - * Reference to the renderer. - * @type {PIXI.AbstractRenderer} - * @protected - */ - this.renderer = renderer; + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} - /** - * The only real difference between CanvasPrepare and Prepare is what they pass - * to upload hooks. That different parameter is stored here. - * @type {PIXI.prepare.CanvasPrepare|PIXI.Renderer} - * @protected - */ - this.uploadHookHelper = null; +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; - /** - * Collection of items to uploads at once. - * @type {Array<*>} - * @private - */ - this.queue = []; + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} - /** - * Collection of additional hooks for finding assets. - * @type {Array} - * @private - */ - this.addHooks = []; +function Node(i, x, y) { + // vertex index in coordinates array + this.i = i; - /** - * Collection of additional hooks for processing assets. - * @type {Array} - * @private - */ - this.uploadHooks = []; + // vertex coordinates + this.x = x; + this.y = y; - /** - * Callback to call after completed. - * @type {Array} - * @private - */ - this.completes = []; + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; - /** - * If prepare is ticking (running). - * @type {boolean} - * @private - */ - this.ticking = false; + // z-order curve value + this.z = null; - /** - * 'bound' call for prepareItems(). - * @type {Function} - * @private - */ - this.delayedTick = function () { - // unlikely, but in case we were destroyed between tick() and delayedTick() - if (!this$1.queue) - { - return; - } - this$1.prepareItems(); - }; + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; - // hooks to find the correct texture - this.registerFindHook(findText); - this.registerFindHook(findTextStyle); - this.registerFindHook(findMultipleBaseTextures); - this.registerFindHook(findBaseTexture); - this.registerFindHook(findTexture); + // indicates whether this is a steiner point + this.steiner = false; +} - // upload hooks - this.registerUploadHook(drawText); - this.registerUploadHook(calculateTextStyle); -}; +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; -/** - * Upload all the textures and graphics to the GPU. - * - * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - - * Either the container or display object to search for items to upload, the items to upload themselves, - * or the callback function, if items have been added using `prepare.add`. - * @param {Function} [done] - Optional callback when all queued uploads have completed - */ -BasePrepare.prototype.upload = function upload (item, done) -{ - if (typeof item === 'function') - { - done = item; - item = null; + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } } - // If a display object, search for items - // that we could upload - if (item) - { - this.add(item); + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); } - // Get the items for upload from the display - if (this.queue.length) - { - if (done) - { - this.completes.push(done); - } - - if (!this.ticking) - { - this.ticking = true; - ticker.Ticker.system.addOnce(this.tick, this, ticker.UPDATE_PRIORITY.UTILITY); - } - } - else if (done) - { - done(); - } + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); }; -/** - * Handle tick update - * - * @private - */ -BasePrepare.prototype.tick = function tick () -{ - setTimeout(this.delayedTick, 0); -}; +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} -/** - * Actually prepare items. This is handled outside of the tick because it will take a while - * and we do NOT want to block the current animation frame from rendering. - * - * @private - */ -BasePrepare.prototype.prepareItems = function prepareItems () -{ - this.limiter.beginFrame(); - // Upload the graphics - while (this.queue.length && this.limiter.allowedToUpload()) - { - var item = this.queue[0]; - var uploaded = false; +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; - if (item && !item._destroyed) - { - for (var i = 0, len = this.uploadHooks.length; i < len; i++) - { - if (this.uploadHooks[i](this.uploadHookHelper, item)) - { - this.queue.shift(); - uploaded = true; - break; - } - } + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); } - - if (!uploaded) - { - this.queue.shift(); + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); } } + return result; +}; - // We're finished - if (!this.queue.length) - { - this.ticking = false; - - var completes = this.completes.slice(0); +},{}],40:[function(require,module,exports){ +(function (global,setImmediate){ +(function(global){ - this.completes.length = 0; +// +// Check for native Promise and it has correct interface +// - for (var i$1 = 0, len$1 = completes.length; i$1 < len$1; i$1++) - { - completes[i$1](); - } - } - else - { - // if we are not finished, on the next rAF do this again - ticker.Ticker.system.addOnce(this.tick, this, ticker.UPDATE_PRIORITY.UTILITY); - } -}; +var NativePromise = global['Promise']; +var nativePromiseSupported = + NativePromise && + // Some of these methods are missing from + // Firefox/Chrome experimental implementations + 'resolve' in NativePromise && + 'reject' in NativePromise && + 'all' in NativePromise && + 'race' in NativePromise && + // Older version of the spec had a resolver object + // as the arg rather than a function + (function(){ + var resolve; + new NativePromise(function(r){ resolve = r; }); + return typeof resolve === 'function'; + })(); -/** - * Adds hooks for finding items. - * - * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` - * function must return `true` if it was able to add item to the queue. - * @return {PIXI.prepare.BasePrepare} Instance of plugin for chaining. - */ -BasePrepare.prototype.registerFindHook = function registerFindHook (addHook) -{ - if (addHook) - { - this.addHooks.push(addHook); - } - return this; -}; +// +// export if necessary +// -/** - * Adds hooks for uploading items. - * - * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and - * function must return `true` if it was able to handle upload of item. - * @return {PIXI.prepare.BasePrepare} Instance of plugin for chaining. - */ -BasePrepare.prototype.registerUploadHook = function registerUploadHook (uploadHook) +if (typeof exports !== 'undefined' && exports) { - if (uploadHook) - { - this.uploadHooks.push(uploadHook); - } - - return this; -}; - -/** - * Manually add an item to the uploading queue. - * - * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to - * add to the queue - * @return {PIXI.prepare.BasePrepare} Instance of plugin for chaining. - */ -BasePrepare.prototype.add = function add (item) + // node.js + exports.Promise = nativePromiseSupported ? NativePromise : Promise; + exports.Polyfill = Promise; +} +else { - // Add additional hooks for finding elements on special - // types of objects that - for (var i = 0, len = this.addHooks.length; i < len; i++) - { - if (this.addHooks[i](item, this.queue)) - { - break; - } - } + // AMD + if (typeof define == 'function' && define.amd) + { + define(function(){ + return nativePromiseSupported ? NativePromise : Promise; + }); + } + else + { + // in browser add to global + if (!nativePromiseSupported) + global['Promise'] = Promise; + } +} - // Get children recursively - if (item instanceof display.Container) - { - for (var i$1 = item.children.length - 1; i$1 >= 0; i$1--) - { - this.add(item.children[i$1]); - } - } - return this; -}; +// +// Polyfill +// -/** - * Destroys the plugin, don't use after this. - * - */ -BasePrepare.prototype.destroy = function destroy () -{ - if (this.ticking) - { - ticker.Ticker.system.remove(this.tick, this); - } - this.ticking = false; - this.addHooks = null; - this.uploadHooks = null; - this.renderer = null; - this.completes = null; - this.queue = null; - this.limiter = null; - this.uploadHookHelper = null; -}; +var PENDING = 'pending'; +var SEALED = 'sealed'; +var FULFILLED = 'fulfilled'; +var REJECTED = 'rejected'; +var NOOP = function(){}; -/** - * Built-in hook to find multiple textures from objects like AnimatedSprites. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Texture object was found. - */ -function findMultipleBaseTextures(item, queue) -{ - var result = false; +function isArray(value) { + return Object.prototype.toString.call(value) === '[object Array]'; +} - // Objects with multiple textures - if (item && item._textures && item._textures.length) - { - for (var i = 0; i < item._textures.length; i++) - { - if (item._textures[i] instanceof core.Texture) - { - var baseTexture = item._textures[i].baseTexture; +// async calls +var asyncSetTimer = typeof setImmediate !== 'undefined' ? setImmediate : setTimeout; +var asyncQueue = []; +var asyncTimer; - if (queue.indexOf(baseTexture) === -1) - { - queue.push(baseTexture); - result = true; - } - } - } - } +function asyncFlush(){ + // run promise callbacks + for (var i = 0; i < asyncQueue.length; i++) + asyncQueue[i][0](asyncQueue[i][1]); - return result; + // reset async asyncQueue + asyncQueue = []; + asyncTimer = false; } -/** - * Built-in hook to find BaseTextures from Texture. - * - * @private - * @param {PIXI.Texture} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Texture object was found. - */ -function findBaseTexture(item, queue) -{ - if (item.baseTexture instanceof core.BaseTexture) - { - var texture = item.baseTexture; - - if (queue.indexOf(texture) === -1) - { - queue.push(texture); - } - - return true; - } +function asyncCall(callback, arg){ + asyncQueue.push([callback, arg]); - return false; + if (!asyncTimer) + { + asyncTimer = true; + asyncSetTimer(asyncFlush, 0); + } } -/** - * Built-in hook to find textures from objects. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Texture object was found. - */ -function findTexture(item, queue) -{ - if (item._texture && item._texture instanceof core.Texture) - { - var texture = item._texture.baseTexture; - if (queue.indexOf(texture) === -1) - { - queue.push(texture); - } +function invokeResolver(resolver, promise) { + function resolvePromise(value) { + resolve(promise, value); + } - return true; - } + function rejectPromise(reason) { + reject(promise, reason); + } - return false; + try { + resolver(resolvePromise, rejectPromise); + } catch(e) { + rejectPromise(e); + } } -/** - * Built-in hook to draw PIXI.Text to its texture. - * - * @private - * @param {PIXI.Renderer|PIXI.CanvasPrepare} helper - Not used by this upload handler - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ -function drawText(helper, item) -{ - if (item instanceof text.Text) - { - // updating text will return early if it is not dirty - item.updateText(true); +function invokeCallback(subscriber){ + var owner = subscriber.owner; + var settled = owner.state_; + var value = owner.data_; + var callback = subscriber[settled]; + var promise = subscriber.then; - return true; + if (typeof callback === 'function') + { + settled = FULFILLED; + try { + value = callback(value); + } catch(e) { + reject(promise, e); } + } - return false; + if (!handleThenable(promise, value)) + { + if (settled === FULFILLED) + resolve(promise, value); + + if (settled === REJECTED) + reject(promise, value); + } } -/** - * Built-in hook to calculate a text style for a PIXI.Text object. - * - * @private - * @param {PIXI.Renderer|PIXI.CanvasPrepare} helper - Not used by this upload handler - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ -function calculateTextStyle(helper, item) -{ - if (item instanceof text.TextStyle) +function handleThenable(promise, value) { + var resolved; + + try { + if (promise === value) + throw new TypeError('A promises callback cannot return that same promise.'); + + if (value && (typeof value === 'function' || typeof value === 'object')) { - var font = item.toFontString(); + var then = value.then; // then should be retrived only once - text.TextMetrics.measureFont(font); + if (typeof then === 'function') + { + then.call(value, function(val){ + if (!resolved) + { + resolved = true; + + if (value !== val) + resolve(promise, val); + else + fulfill(promise, val); + } + }, function(reason){ + if (!resolved) + { + resolved = true; + + reject(promise, reason); + } + }); return true; + } } + } catch (e) { + if (!resolved) + reject(promise, e); - return false; + return true; + } + + return false; } -/** - * Built-in hook to find Text objects. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Text object was found. - */ -function findText(item, queue) -{ - if (item instanceof text.Text) - { - // push the text style to prepare it - this can be really expensive - if (queue.indexOf(item.style) === -1) - { - queue.push(item.style); - } - // also push the text object so that we can render it (to canvas/texture) if needed - if (queue.indexOf(item) === -1) - { - queue.push(item); - } - // also push the Text's texture for upload to GPU - var texture = item._texture.baseTexture; +function resolve(promise, value){ + if (promise === value || !handleThenable(promise, value)) + fulfill(promise, value); +} - if (queue.indexOf(texture) === -1) - { - queue.push(texture); - } +function fulfill(promise, value){ + if (promise.state_ === PENDING) + { + promise.state_ = SEALED; + promise.data_ = value; - return true; - } + asyncCall(publishFulfillment, promise); + } +} - return false; +function reject(promise, reason){ + if (promise.state_ === PENDING) + { + promise.state_ = SEALED; + promise.data_ = reason; + + asyncCall(publishRejection, promise); + } } -/** - * Built-in hook to find TextStyle objects. - * - * @private - * @param {PIXI.TextStyle} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.TextStyle object was found. - */ -function findTextStyle(item, queue) -{ - if (item instanceof text.TextStyle) - { - if (queue.indexOf(item) === -1) - { - queue.push(item); - } +function publish(promise) { + var callbacks = promise.then_; + promise.then_ = undefined; - return true; - } + for (var i = 0; i < callbacks.length; i++) { + invokeCallback(callbacks[i]); + } +} - return false; +function publishFulfillment(promise){ + promise.state_ = FULFILLED; + publish(promise); +} + +function publishRejection(promise){ + promise.state_ = REJECTED; + publish(promise); } /** - * The prepare manager provides functionality to upload content to the GPU. - * - * An instance of this class is automatically created by default, and can be found at `renderer.plugins.prepare` - * - * @class - * @extends PIXI.prepare.BasePrepare - * @memberof PIXI.prepare - */ -var Prepare = /*@__PURE__*/(function (BasePrepare) { - function Prepare(renderer) - { - BasePrepare.call(this, renderer); +* @class +*/ +function Promise(resolver){ + if (typeof resolver !== 'function') + throw new TypeError('Promise constructor takes a function argument'); - this.uploadHookHelper = this.renderer; + if (this instanceof Promise === false) + throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); - // Add textures and graphics to upload - this.registerFindHook(findGraphics); - this.registerUploadHook(uploadBaseTextures); - this.registerUploadHook(uploadGraphics); - } + this.then_ = []; - if ( BasePrepare ) Prepare.__proto__ = BasePrepare; - Prepare.prototype = Object.create( BasePrepare && BasePrepare.prototype ); - Prepare.prototype.constructor = Prepare; + invokeResolver(resolver, this); +} - return Prepare; -}(BasePrepare)); -/** - * Built-in hook to upload PIXI.Texture objects to the GPU. - * - * @private - * @param {PIXI.Renderer} renderer - instance of the webgl renderer - * @param {PIXI.BaseTexture} item - Item to check - * @return {boolean} If item was uploaded. - */ -function uploadBaseTextures(renderer, item) -{ - if (item instanceof core.BaseTexture) - { - // if the texture already has a GL texture, then the texture has been prepared or rendered - // before now. If the texture changed, then the changer should be calling texture.update() which - // reuploads the texture without need for preparing it again - if (!item._glTextures[renderer.CONTEXT_UID]) - { - renderer.texture.bind(item); - } +Promise.prototype = { + constructor: Promise, - return true; - } + state_: PENDING, + then_: null, + data_: undefined, - return false; -} + then: function(onFulfillment, onRejection){ + var subscriber = { + owner: this, + then: new this.constructor(NOOP), + fulfilled: onFulfillment, + rejected: onRejection + }; -/** - * Built-in hook to upload PIXI.Graphics to the GPU. - * - * @private - * @param {PIXI.Renderer} renderer - instance of the webgl renderer - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ -function uploadGraphics(renderer, item) -{ - if (!(item instanceof graphics.Graphics)) + if (this.state_ === FULFILLED || this.state_ === REJECTED) { - return false; + // already resolved, call callback async + asyncCall(invokeCallback, subscriber); + } + else + { + // subscribe + this.then_.push(subscriber); } - var geometry = item.geometry; + return subscriber.then; + }, - // update dirty graphics to get batches - item.finishPoly(); - geometry.updateBatches(); + 'catch': function(onRejection) { + return this.then(null, onRejection); + } +}; - var batches = geometry.batches; +Promise.all = function(promises){ + var Class = this; - // upload all textures found in styles - for (var i = 0; i < batches.length; i++) - { - var ref = batches[i].style; - var texture = ref.texture; + if (!isArray(promises)) + throw new TypeError('You must pass an array to Promise.all().'); - if (texture) - { - uploadBaseTextures(renderer, texture.baseTexture); - } + return new Class(function(resolve, reject){ + var results = []; + var remaining = 0; + + function resolver(index){ + remaining++; + return function(value){ + results[index] = value; + if (!--remaining) + resolve(results); + }; } - // if its not batchable - update vao for particular shader - if (!geometry.batchable) + for (var i = 0, promise; i < promises.length; i++) { - renderer.geometry.bind(geometry, item._resolveDirectShader()); + promise = promises[i]; + + if (promise && typeof promise.then === 'function') + promise.then(resolver(i), reject); + else + results[i] = promise; } - return true; -} + if (!remaining) + resolve(results); + }); +}; -/** - * Built-in hook to find graphics. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Graphics object was found. - */ -function findGraphics(item, queue) -{ - if (item instanceof graphics.Graphics) - { - queue.push(item); +Promise.race = function(promises){ + var Class = this; - return true; - } + if (!isArray(promises)) + throw new TypeError('You must pass an array to Promise.race().'); - return false; -} + return new Class(function(resolve, reject) { + for (var i = 0, promise; i < promises.length; i++) + { + promise = promises[i]; -/** - * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified - * number of milliseconds per frame. - * - * @class - * @memberof PIXI.prepare - */ -var TimeLimiter = function TimeLimiter(maxMilliseconds) -{ - /** - * The maximum milliseconds that can be spent preparing items each frame. - * @type {number} - * @private - */ - this.maxMilliseconds = maxMilliseconds; - /** - * The start time of the current frame. - * @type {number} - * @private - */ - this.frameStart = 0; + if (promise && typeof promise.then === 'function') + promise.then(resolve, reject); + else + resolve(promise); + } + }); }; -/** - * Resets any counting properties to start fresh on a new frame. - */ -TimeLimiter.prototype.beginFrame = function beginFrame () -{ - this.frameStart = Date.now(); -}; +Promise.resolve = function(value){ + var Class = this; -/** - * Checks to see if another item can be uploaded. This should only be called once per item. - * @return {boolean} If the item is allowed to be uploaded. - */ -TimeLimiter.prototype.allowedToUpload = function allowedToUpload () -{ - return Date.now() - this.frameStart < this.maxMilliseconds; + if (value && typeof value === 'object' && value.constructor === Class) + return value; + + return new Class(function(resolve){ + resolve(value); + }); }; -/** - * The prepare namespace provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for - * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed. - * - * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property. - * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. - * @example - * // Create a new application - * const app = new PIXI.Application(); - * document.body.appendChild(app.view); - * - * // Don't start rendering right away - * app.stop(); - * - * // create a display object - * const rect = new PIXI.Graphics() - * .beginFill(0x00ff00) - * .drawRect(40, 40, 200, 200); - * - * // Add to the stage - * app.stage.addChild(rect); - * - * // Don't start rendering until the graphic is uploaded to the GPU - * app.renderer.plugins.prepare.upload(app.stage, () => { - * app.start(); - * }); - * @namespace PIXI.prepare - */ +Promise.reject = function(reason){ + var Class = this; -exports.BasePrepare = BasePrepare; -exports.CountLimiter = CountLimiter; -exports.Prepare = Prepare; -exports.TimeLimiter = TimeLimiter; + return new Class(function(resolve, reject){ + reject(reason); + }); +}; +})(typeof window != 'undefined' ? window : typeof global != 'undefined' ? global : typeof self != 'undefined' ? self : this); -},{"@pixi/core":17,"@pixi/display":18,"@pixi/graphics":26,"@pixi/settings":39,"@pixi/text":45,"@pixi/ticker":46}],38:[function(require,module,exports){ -/*! - * @pixi/runner - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/runner is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) +},{"timers":69}],41:[function(require,module,exports){ 'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); +var has = Object.prototype.hasOwnProperty + , prefix = '~'; /** - * A Runner is a highly performant and simple alternative to signals. Best used in situations - * where events are dispatched to many objects at high frequency (say every frame!) - * - * - * like a signal.. - * ``` - * import { Runner } from '@pixi/runner'; - * - * const myObject = { - * loaded: new Runner('loaded') - * } - * - * const listener = { - * loaded: function(){ - * // thin - * } - * } - * - * myObject.update.add(listener); - * - * myObject.loaded.emit(); - * ``` - * - * Or for handling calling the same function on many items - * ``` - * import { Runner } from '@pixi/runner'; - * - * const myGame = { - * update: new Runner('update') - * } - * - * const gameObject = { - * update: function(time){ - * // update my gamey state - * } - * } - * - * myGame.update.add(gameObject1); + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. * - * myGame.update.emit(time); - * ``` - * @class - * @memberof PIXI + * @constructor + * @private */ -var Runner = /** @class */ (function () { - /** - * @param {string} name the function name that will be executed on the listeners added to this Runner. - */ - function Runner(name) { - this.items = []; - this._name = name; - this._aliasCount = 0; - } - /** - * Dispatch/Broadcast Runner to all listeners added to the queue. - * @param {...any} params - optional parameters to pass to each listener - * @return {PIXI.Runner} - */ - Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) { - if (arguments.length > 8) { - throw new Error('max arguments reached'); - } - var _a = this, name = _a.name, items = _a.items; - this._aliasCount++; - for (var i = 0, len = items.length; i < len; i++) { - items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); - } - if (items === this.items) { - this._aliasCount--; - } - return this; - }; - Runner.prototype.ensureNonAliasedItems = function () { - if (this._aliasCount > 0 && this.items.length > 1) { - this._aliasCount = 0; - this.items = this.items.slice(0); - } - }; - /** - * Add a listener to the Runner - * - * Runners do not need to have scope or functions passed to them. - * All that is required is to pass the listening object and ensure that it has contains a function that has the same name - * as the name provided to the Runner when it was created. - * - * Eg A listener passed to this Runner will require a 'complete' function. - * - * ``` - * import { Runner } from '@pixi/runner'; - * - * const complete = new Runner('complete'); - * ``` - * - * The scope used will be the object itself. - * - * @param {any} item - The object that will be listening. - * @return {PIXI.Runner} - */ - Runner.prototype.add = function (item) { - if (item[this._name]) { - this.ensureNonAliasedItems(); - this.remove(item); - this.items.push(item); - } - return this; - }; - /** - * Remove a single listener from the dispatch queue. - * @param {any} item - The listenr that you would like to remove. - * @return {PIXI.Runner} - */ - Runner.prototype.remove = function (item) { - var index = this.items.indexOf(item); - if (index !== -1) { - this.ensureNonAliasedItems(); - this.items.splice(index, 1); - } - return this; - }; - /** - * Check to see if the listener is already in the Runner - * @param {any} item - The listener that you would like to check. - */ - Runner.prototype.contains = function (item) { - return this.items.indexOf(item) !== -1; - }; - /** - * Remove all listeners from the Runner - * @return {PIXI.Runner} - */ - Runner.prototype.removeAll = function () { - this.ensureNonAliasedItems(); - this.items.length = 0; - return this; - }; - /** - * Remove all references, don't use after this. - */ - Runner.prototype.destroy = function () { - this.removeAll(); - this.items = null; - this._name = null; - }; - Object.defineProperty(Runner.prototype, "empty", { - /** - * `true` if there are no this Runner contains no listeners - * - * @member {boolean} - * @readonly - */ - get: function () { - return this.items.length === 0; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Runner.prototype, "name", { - /** - * The name of the runner. - * - * @member {string} - * @readonly - */ - get: function () { - return this._name; - }, - enumerable: true, - configurable: true - }); - return Runner; -}()); -Object.defineProperties(Runner.prototype, { - /** - * Alias for `emit` - * @memberof PIXI.Runner# - * @method dispatch - * @see PIXI.Runner#emit - */ - dispatch: { value: Runner.prototype.emit }, - /** - * Alias for `emit` - * @memberof PIXI.Runner# - * @method run - * @see PIXI.Runner#emit - */ - run: { value: Runner.prototype.emit }, -}); +function Events() {} -exports.Runner = Runner; +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} -},{}],39:[function(require,module,exports){ -/*! - * @pixi/settings - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC +/** + * Representation of a single event listener. * - * @pixi/settings is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var isMobile = _interopDefault(require('ismobilejs')); +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} /** - * The maximum recommended texture units to use. - * In theory the bigger the better, and for desktop we'll use as many as we can. - * But some mobile devices slow down if there is to many branches in the shader. - * So in practice there seems to be a sweet spot size that varies depending on the device. - * - * In v4, all mobile devices were limited to 4 texture units because for this. - * In v5, we allow all texture units to be used on modern Apple or Android devices. + * Add a listener for a given event. * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} * @private - * @param {number} max - * @returns {number} */ -function maxRecommendedTextures(max) -{ - var allowMax = true; - - if (isMobile.tablet || isMobile.phone) - { - allowMax = false; - - if (isMobile.apple.device) - { - var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); - - if (match) - { - var majorVersion = parseInt(match[1], 10); - - // All texture units can be used on devices that support ios 11 or above - if (majorVersion >= 11) - { - allowMax = true; - } - } - } - if (isMobile.android.device) - { - var match$1 = (navigator.userAgent).match(/Android\s([0-9.]*)/); +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } - if (match$1) - { - var majorVersion$1 = parseInt(match$1[1], 10); + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; - // All texture units can be used on devices that support Android 7 (Nougat) or above - if (majorVersion$1 >= 7) - { - allowMax = true; - } - } - } - } + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; - return allowMax ? max : 4; + return emitter; } /** - * Uploading the same buffer multiple times in a single frame can cause performance issues. - * Apparent on iOS so only check for that at the moment - * This check may become more complex if this issue pops up elsewhere. + * Clear event by name. * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. * @private - * @returns {boolean} */ -function canUploadSameBuffer() -{ - return !isMobile.apple.device; +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; } /** - * User's customizable globals for overriding the default PIXI settings, such - * as a renderer's default resolution, framerate, float precision, etc. - * @example - * // Use the native window resolution as the default resolution - * // will support high-density displays when rendering - * PIXI.settings.RESOLUTION = window.devicePixelRatio; + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. * - * // Disable interpolation when scaling, will make texture be pixelated - * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; - * @namespace PIXI.settings + * @constructor + * @public */ -var settings = { +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} - /** - * If set to true WebGL will attempt make textures mimpaped by default. - * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. - * - * @static - * @name MIPMAP_TEXTURES - * @memberof PIXI.settings - * @type {PIXI.MIPMAP_MODES} - * @default PIXI.MIPMAP_MODES.POW2 - */ - MIPMAP_TEXTURES: 1, - - /** - * Default anisotropic filtering level of textures. - * Usually from 0 to 16 - * - * @static - * @name ANISOTROPIC_LEVEL - * @memberof PIXI.settings - * @type {number} - * @default 0 - */ - ANISOTROPIC_LEVEL: 0, +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; - /** - * Default resolution / device pixel ratio of the renderer. - * - * @static - * @name RESOLUTION - * @memberof PIXI.settings - * @type {number} - * @default 1 - */ - RESOLUTION: 1, + if (this._eventsCount === 0) return names; - /** - * Default filter resolution. - * - * @static - * @name FILTER_RESOLUTION - * @memberof PIXI.settings - * @type {number} - * @default 1 - */ - FILTER_RESOLUTION: 1, + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } - /** - * The maximum textures that this device supports. - * - * @static - * @name SPRITE_MAX_TEXTURES - * @memberof PIXI.settings - * @type {number} - * @default 32 - */ - SPRITE_MAX_TEXTURES: maxRecommendedTextures(32), + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } - // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 - // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + return names; +}; - /** - * The default sprite batch size. - * - * The default aims to balance desktop and mobile devices. - * - * @static - * @name SPRITE_BATCH_SIZE - * @memberof PIXI.settings - * @type {number} - * @default 4096 - */ - SPRITE_BATCH_SIZE: 4096, +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; - /** - * The default render options if none are supplied to {@link PIXI.Renderer} - * or {@link PIXI.CanvasRenderer}. - * - * @static - * @name RENDER_OPTIONS - * @memberof PIXI.settings - * @type {object} - * @property {HTMLCanvasElement} view=null - * @property {number} resolution=1 - * @property {boolean} antialias=false - * @property {boolean} forceFXAA=false - * @property {boolean} autoDensity=false - * @property {boolean} transparent=false - * @property {number} backgroundColor=0x000000 - * @property {boolean} clearBeforeRender=true - * @property {boolean} preserveDrawingBuffer=false - * @property {number} width=800 - * @property {number} height=600 - * @property {boolean} legacy=false - */ - RENDER_OPTIONS: { - view: null, - antialias: false, - forceFXAA: false, - autoDensity: false, - transparent: false, - backgroundColor: 0x000000, - clearBeforeRender: true, - preserveDrawingBuffer: false, - width: 800, - height: 600, - legacy: false, - }, + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; - /** - * Default Garbage Collection mode. - * - * @static - * @name GC_MODE - * @memberof PIXI.settings - * @type {PIXI.GC_MODES} - * @default PIXI.GC_MODES.AUTO - */ - GC_MODE: 0, + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } - /** - * Default Garbage Collection max idle. - * - * @static - * @name GC_MAX_IDLE - * @memberof PIXI.settings - * @type {number} - * @default 3600 - */ - GC_MAX_IDLE: 60 * 60, + return ee; +}; - /** - * Default Garbage Collection maximum check count. - * - * @static - * @name GC_MAX_CHECK_COUNT - * @memberof PIXI.settings - * @type {number} - * @default 600 - */ - GC_MAX_CHECK_COUNT: 60 * 10, +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; - /** - * Default wrap modes that are supported by pixi. - * - * @static - * @name WRAP_MODE - * @memberof PIXI.settings - * @type {PIXI.WRAP_MODES} - * @default PIXI.WRAP_MODES.CLAMP - */ - WRAP_MODE: 33071, + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; - /** - * Default scale mode for textures. - * - * @static - * @name SCALE_MODE - * @memberof PIXI.settings - * @type {PIXI.SCALE_MODES} - * @default PIXI.SCALE_MODES.LINEAR - */ - SCALE_MODE: 1, +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; - /** - * Default specify float precision in vertex shader. - * - * @static - * @name PRECISION_VERTEX - * @memberof PIXI.settings - * @type {PIXI.PRECISION} - * @default PIXI.PRECISION.HIGH - */ - PRECISION_VERTEX: 'highp', + if (!this._events[evt]) return false; - /** - * Default specify float precision in fragment shader. - * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 - * - * @static - * @name PRECISION_FRAGMENT - * @memberof PIXI.settings - * @type {PIXI.PRECISION} - * @default PIXI.PRECISION.MEDIUM - */ - PRECISION_FRAGMENT: isMobile.apple.device ? 'highp' : 'mediump', + var listeners = this._events[evt] + , len = arguments.length + , args + , i; - /** - * Can we upload the same buffer in a single frame? - * - * @static - * @name CAN_UPLOAD_SAME_BUFFER - * @memberof PIXI.settings - * @type {boolean} - */ - CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(), + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - /** - * Enables bitmap creation before image load. This feature is experimental. - * - * @static - * @name CREATE_IMAGE_BITMAP - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - CREATE_IMAGE_BITMAP: false, + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * - * @static - * @constant - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - ROUND_PIXELS: false, -}; + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } -exports.isMobile = isMobile; -exports.settings = settings; + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); -},{"ismobilejs":52}],40:[function(require,module,exports){ -/*! - * @pixi/sprite-animated - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/sprite-animated is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } -Object.defineProperty(exports, '__esModule', { value: true }); + listeners[i].fn.apply(listeners[i].context, args); + } + } + } -var core = require('@pixi/core'); -var sprite = require('@pixi/sprite'); -var ticker = require('@pixi/ticker'); + return true; +}; /** - * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. - * - * ```js - * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; - * let textureArray = []; - * - * for (let i=0; i < 4; i++) - * { - * let texture = PIXI.Texture.from(alienImages[i]); - * textureArray.push(texture); - * }; - * - * let animatedSprite = new PIXI.AnimatedSprite(textureArray); - * ``` - * - * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} - * containing the animation definitions: + * Add a listener for a given event. * - * ```js - * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; + +/** + * Add a one-time listener for a given event. * - * function setup() { - * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; - * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]); - * ... - * } - * ``` + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; + +/** + * Remove the listeners of a given event. * - * @class - * @extends PIXI.Sprite - * @memberof PIXI + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public */ -var AnimatedSprite = /*@__PURE__*/(function (Sprite) { - function AnimatedSprite(textures, autoUpdate) - { - Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture); +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; - /** - * @type {PIXI.Texture[]} - * @private - */ - this._textures = null; + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } - /** - * @type {number[]} - * @private - */ - this._durations = null; + var listeners = this._events[evt]; - this.textures = textures; + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } - /** - * `true` uses PIXI.Ticker.shared to auto update animation time. - * @type {boolean} - * @default true - * @private - */ - this._autoUpdate = autoUpdate !== false; + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } - /** - * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower. - * - * @member {number} - * @default 1 - */ - this.animationSpeed = 1; + return this; +}; - /** - * Whether or not the animate sprite repeats after playing. - * - * @member {boolean} - * @default true - */ - this.loop = true; +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; - /** - * Update anchor to [Texture's defaultAnchor]{@link PIXI.Texture#defaultAnchor} when frame changes. - * - * Useful with [sprite sheet animations]{@link PIXI.Spritesheet#animations} created with tools. - * Changing anchor for each frame allows to pin sprite origin to certain moving feature - * of the frame (e.g. left foot). - * - * Note: Enabling this will override any previously set `anchor` on each frame change. - * - * @member {boolean} - * @default false - */ - this.updateAnchor = false; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } - /** - * Function to call when an AnimatedSprite finishes playing. - * - * @member {Function} - */ - this.onComplete = null; + return this; +}; - /** - * Function to call when an AnimatedSprite changes which texture is being rendered. - * - * @member {Function} - */ - this.onFrameChange = null; +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; - /** - * Function to call when `loop` is true, and an AnimatedSprite is played and loops around to start again. - * - * @member {Function} - */ - this.onLoop = null; +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; - /** - * Elapsed time since animation has been started, used internally to display current texture. - * - * @member {number} - * @private - */ - this._currentTime = 0; +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; - /** - * Indicates if the AnimatedSprite is currently playing. - * - * @member {boolean} - * @readonly - */ - this.playing = false; - } +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} - if ( Sprite ) AnimatedSprite.__proto__ = Sprite; - AnimatedSprite.prototype = Object.create( Sprite && Sprite.prototype ); - AnimatedSprite.prototype.constructor = AnimatedSprite; +},{}],42:[function(require,module,exports){ +'use strict'; - var prototypeAccessors = { totalFrames: { configurable: true },textures: { configurable: true },currentFrame: { configurable: true } }; +// Programatically add fork me on github ribbon from javascript without making changes to CSS, HTML, or adding image files +// by David Figatner +// copyright 2018 YOPEY YOPEY LLC +// MIT license +// based on https://github.com/simonwhitaker/github-fork-ribbon-css (MIT license) - /** - * Stops the AnimatedSprite. - * - */ - AnimatedSprite.prototype.stop = function stop () - { - if (!this.playing) - { - return; - } +var RIBBON = { + width: '12.1em', + height: '12.1em', + overflow: 'hidden', + top: 0, + right: 0, + zIndex: 9999, + pointerEvents: 'none', + fontSize: '13px', + textDecoration: 'none', + textIndent: '-999999px' +}; - this.playing = false; - if (this._autoUpdate) - { - ticker.Ticker.shared.remove(this.update, this); - } - }; +var BEFORE_AFTER = [['position', 'absolute'], ['display', 'block'], ['width', '15.38em'], ['height', '1.54em'], ['top', '3.23em'], ['right', '-3.23em'], ['-webkit-box-sizing', 'content-box'], ['-moz-box-sizing', 'content-box'], ['box-sizing', 'content-box'], ['-webkit-transform', 'rotate(45deg)'], ['-moz-transform', 'rotate(45deg)'], ['-ms-Transform', 'rotate(45deg)'], ['-o-transform', 'rotate(45deg)'], ['transform', 'rotate(45deg)']]; - /** - * Plays the AnimatedSprite. - * - */ - AnimatedSprite.prototype.play = function play () - { - if (this.playing) - { - return; - } +var BEFORE = [['content', '""'], ['padding', '.38em 0'], ['background-color', '#a00'], ['background-image', '-webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0)), to(rgba(0, 0, 0, 0.15)))'], ['background-image', '-webkit-linear-gradient(top, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['background-image', '-moz-linear-gradient(top, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['background-image', '-ms-linear-gradient(top, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['background-image', '-o-linear-gradient(top, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['background-image', 'linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['box-shadow', '0 .15em .23em 0 rgba(0, 0, 0, 0.5)'], ['pointer-events', 'auto']]; - this.playing = true; - if (this._autoUpdate) - { - ticker.Ticker.shared.add(this.update, this, ticker.UPDATE_PRIORITY.HIGH); - } - }; +var AFTER = [['content', 'attr(data-ribbon)'], ['color', '#fff'], ['font', '700 1em "Helvetica Neue", Helvetica, Arial, sans-serif'], ['line-height', '1.54em'], ['text-decoration', 'none'], ['text-shadow', '0 -.08em rgba(0, 0, 0, 0.5)'], ['text-align', 'center'], ['text-indent', '0'], ['padding', '.15em 0'], ['margin', '.15em 0'], ['border-width', '.08em 0'], ['border-style', 'dotted'], ['border-color', '#fff'], ['border-color', 'rgba(255, 255, 255, 0.7)']]; - /** - * Stops the AnimatedSprite and goes to a specific frame. - * - * @param {number} frameNumber - Frame index to stop at. - */ - AnimatedSprite.prototype.gotoAndStop = function gotoAndStop (frameNumber) - { - this.stop(); +/** + * Programmatically add "Fork me Github" Ribbon using inline CSS + * Based on CSS from https,//github.com/simonwhitaker/github-fork-ribbon-css + * @param {string} [url] - do not need to include if URL is called from https://username.github.io/project/html + * @param {object} [options] + * @param {HTMLElement} [options.parent=document.body] + * @param {boolean} [options.fixed] + * @param {string} [options.corner=topright] some combination of top/bottom, and left/right + * @param {string} [options.text=fork me on github] text to show + * @param {string} [options.background=#a00] color for ribbon + */ +module.exports = function forkMe(url, options) { + options = options || {}; + var a = document.createElement('a'); + if (url) { + a.href = url; + } else { + var username = window.location.hostname.split('.')[0]; + var project = window.location.pathname.split('/')[1]; + a.href = 'https://github.com/' + username + '/' + project; + } - var previousFrame = this.currentFrame; + a.title = a.innerText = options.text || 'fork me on github'; + a.setAttribute('data-ribbon', options.text || 'fork me on github'); + a.className = 'github-fork-ribbon-' + Math.round(Math.random() * 100000); + if (options.parent) { + options.parent.appendChild(a); + } else { + document.body.appendChild(a); + } + a.style.position = options.fixed ? 'fixed' : 'absolute'; + if (options.background) { + BEFORE[2][1] = options.background; + } + if (options.color) { + AFTER[1][1] = options.color; + } + for (var _style in RIBBON) { + a.style[_style] = RIBBON[_style]; + } + var beforeAfter = '{'; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - this._currentTime = frameNumber; + try { + for (var _iterator = BEFORE_AFTER[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _style2 = _step.value; - if (previousFrame !== this.currentFrame) - { - this.updateTexture(); + beforeAfter += _style2[0] + ':' + _style2[1] + ';'; } - }; - - /** - * Goes to a specific frame and begins playing the AnimatedSprite. - * - * @param {number} frameNumber - Frame index to start at. - */ - AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay (frameNumber) - { - var previousFrame = this.currentFrame; - - this._currentTime = frameNumber; - - if (previousFrame !== this.currentFrame) - { - this.updateTexture(); + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } } + } - this.play(); - }; - - /** - * Updates the object transform for rendering. - * - * @private - * @param {number} deltaTime - Time since last tick. - */ - AnimatedSprite.prototype.update = function update (deltaTime) - { - var elapsed = this.animationSpeed * deltaTime; - var previousFrame = this.currentFrame; - - if (this._durations !== null) - { - var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + var before = beforeAfter; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - lag += elapsed / 60 * 1000; + try { + for (var _iterator2 = BEFORE[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _style3 = _step2.value; - while (lag < 0) - { - this._currentTime--; - lag += this._durations[this.currentFrame]; + before += _style3[0] + ':' + _style3[1] + ';'; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); } - - var sign = Math.sign(this.animationSpeed * deltaTime); - - this._currentTime = Math.floor(this._currentTime); - - while (lag >= this._durations[this.currentFrame]) - { - lag -= this._durations[this.currentFrame] * sign; - this._currentTime += sign; + } finally { + if (_didIteratorError2) { + throw _iteratorError2; } - - this._currentTime += lag / this._durations[this.currentFrame]; - } - else - { - this._currentTime += elapsed; } + } - if (this._currentTime < 0 && !this.loop) - { - this.gotoAndStop(0); + var after = beforeAfter; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; - if (this.onComplete) - { - this.onComplete(); - } - } - else if (this._currentTime >= this._textures.length && !this.loop) - { - this.gotoAndStop(this._textures.length - 1); + try { + for (var _iterator3 = AFTER[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _style4 = _step3.value; - if (this.onComplete) - { - this.onComplete(); - } + after += _style4[0] + ':' + _style4[1] + ';'; } - else if (previousFrame !== this.currentFrame) - { - if (this.loop && this.onLoop) - { - if (this.animationSpeed > 0 && this.currentFrame < previousFrame) - { - this.onLoop(); - } - else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) - { - this.onLoop(); - } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; } - - this.updateTexture(); } - }; + } - /** - * Updates the displayed texture to match the current frame index. - * - * @private - */ - AnimatedSprite.prototype.updateTexture = function updateTexture () - { - this._texture = this._textures[this.currentFrame]; - this._textureID = -1; - this._textureTrimmedID = -1; - this._cachedTint = 0xFFFFFF; - this.uvs = this._texture._uvs.uvsFloat32; + var bottom = void 0, + left = void 0; + if (options.side) { + bottom = options.side.toLowerCase().indexOf('bottom') !== -1; + left = options.side.toLowerCase().indexOf('left') !== -1; + } + if (bottom) { + a.style.top = 'auto'; + a.style.bottom = 0; + before += 'top:auto;bottom:3.23em;'; + after += 'top:auto;bottom:3.23em;'; + } + if (left) { + a.style.right = 'auto'; + a.style.left = 0; + before += 'right:auto;left:-3.23em;'; + after += 'right:auto;left:-3.23em;'; + } + if (left && !bottom || !left && bottom) { + before += 'transform:rotate(-45deg);'; + after += 'transform:rotate(-45deg);'; + } + var style = document.createElement('style'); + document.head.appendChild(style); + var sheet = style.sheet; + sheet.insertRule('.' + a.className + '::before' + before + '}'); + sheet.insertRule('.' + a.className + '::after' + after + '}'); +}; - if (this.updateAnchor) - { - this._anchor.copyFrom(this._texture.defaultAnchor); - } +},{}],43:[function(require,module,exports){ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +exports.__esModule = true; +__export(require("./isMobile")); +var isMobile_1 = require("./isMobile"); +exports["default"] = isMobile_1["default"]; + +},{"./isMobile":44}],44:[function(require,module,exports){ +"use strict"; +exports.__esModule = true; +var appleIphone = /iPhone/i; +var appleIpod = /iPod/i; +var appleTablet = /iPad/i; +var appleUniversal = /\biOS-universal(?:.+)Mac\b/i; +var androidPhone = /\bAndroid(?:.+)Mobile\b/i; +var androidTablet = /Android/i; +var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; +var amazonTablet = /Silk/i; +var windowsPhone = /Windows Phone/i; +var windowsTablet = /\bWindows(?:.+)ARM\b/i; +var otherBlackBerry = /BlackBerry/i; +var otherBlackBerry10 = /BB10/i; +var otherOpera = /Opera Mini/i; +var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i; +var otherFirefox = /Mobile(?:.+)Firefox\b/i; +var isAppleTabletOnIos13 = function (navigator) { + return (typeof navigator !== 'undefined' && + navigator.platform === 'MacIntel' && + typeof navigator.maxTouchPoints === 'number' && + navigator.maxTouchPoints > 1 && + typeof MSStream === 'undefined'); +}; +function createMatch(userAgent) { + return function (regex) { return regex.test(userAgent); }; +} +function isMobile(param) { + var nav = { + userAgent: '', + platform: '', + maxTouchPoints: 0 + }; + if (!param && typeof navigator !== 'undefined') { + nav = { + userAgent: navigator.userAgent, + platform: navigator.platform, + maxTouchPoints: navigator.maxTouchPoints || 0 + }; + } + else if (typeof param === 'string') { + nav.userAgent = param; + } + else if (param && param.userAgent) { + nav = { + userAgent: param.userAgent, + platform: param.platform, + maxTouchPoints: param.maxTouchPoints || 0 + }; + } + var userAgent = nav.userAgent; + var tmp = userAgent.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + tmp = userAgent.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + var match = createMatch(userAgent); + var result = { + apple: { + phone: match(appleIphone) && !match(windowsPhone), + ipod: match(appleIpod), + tablet: !match(appleIphone) && + (match(appleTablet) || isAppleTabletOnIos13(nav)) && + !match(windowsPhone), + universal: match(appleUniversal), + device: (match(appleIphone) || + match(appleIpod) || + match(appleTablet) || + match(appleUniversal) || + isAppleTabletOnIos13(nav)) && + !match(windowsPhone) + }, + amazon: { + phone: match(amazonPhone), + tablet: !match(amazonPhone) && match(amazonTablet), + device: match(amazonPhone) || match(amazonTablet) + }, + android: { + phone: (!match(windowsPhone) && match(amazonPhone)) || + (!match(windowsPhone) && match(androidPhone)), + tablet: !match(windowsPhone) && + !match(amazonPhone) && + !match(androidPhone) && + (match(amazonTablet) || match(androidTablet)), + device: (!match(windowsPhone) && + (match(amazonPhone) || + match(amazonTablet) || + match(androidPhone) || + match(androidTablet))) || + match(/\bokhttp\b/i) + }, + windows: { + phone: match(windowsPhone), + tablet: match(windowsTablet), + device: match(windowsPhone) || match(windowsTablet) + }, + other: { + blackberry: match(otherBlackBerry), + blackberry10: match(otherBlackBerry10), + opera: match(otherOpera), + firefox: match(otherFirefox), + chrome: match(otherChrome), + device: match(otherBlackBerry) || + match(otherBlackBerry10) || + match(otherOpera) || + match(otherFirefox) || + match(otherChrome) + }, + any: false, + phone: false, + tablet: false + }; + result.any = + result.apple.device || + result.android.device || + result.windows.device || + result.other.device; + result.phone = + result.apple.phone || result.android.phone || result.windows.phone; + result.tablet = + result.apple.tablet || result.android.tablet || result.windows.tablet; + return result; +} +exports["default"] = isMobile; - if (this.onFrameChange) - { - this.onFrameChange(this.currentFrame); - } - }; +},{}],45:[function(require,module,exports){ +'use strict'; - /** - * Stops the AnimatedSprite and destroys it. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value. - * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well. - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well. - */ - AnimatedSprite.prototype.destroy = function destroy (options) - { - this.stop(); - Sprite.prototype.destroy.call(this, options); +Object.defineProperty(exports, '__esModule', { + value: true +}); - this.onComplete = null; - this.onFrameChange = null; - this.onLoop = null; - }; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - /** - * A short hand way of creating an AnimatedSprite from an array of frame ids. - * - * @static - * @param {string[]} frames - The array of frames ids the AnimatedSprite will use as its texture frames. - * @return {AnimatedSprite} The new animated sprite with the specified frames. - */ - AnimatedSprite.fromFrames = function fromFrames (frames) - { - var textures = []; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - for (var i = 0; i < frames.length; ++i) - { - textures.push(core.Texture.from(frames[i])); - } +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; - return new AnimatedSprite(textures); - }; + _classCallCheck(this, MiniSignalBinding); - /** - * A short hand way of creating an AnimatedSprite from an array of image ids. - * - * @static - * @param {string[]} images - The array of image urls the AnimatedSprite will use as its texture frames. - * @return {AnimatedSprite} The new animate sprite with the specified images as frames. - */ - AnimatedSprite.fromImages = function fromImages (images) - { - var textures = []; + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } - for (var i = 0; i < images.length; ++i) - { - textures.push(core.Texture.from(images[i])); - } + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); - return new AnimatedSprite(textures); - }; + return MiniSignalBinding; +})(); - /** - * The total number of frames in the AnimatedSprite. This is the same as number of textures - * assigned to the AnimatedSprite. - * - * @readonly - * @member {number} - * @default 0 - */ - prototypeAccessors.totalFrames.get = function () - { - return this._textures.length; - }; +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } - /** - * The array of textures used for this AnimatedSprite. - * - * @member {PIXI.Texture[]} - */ - prototypeAccessors.textures.get = function () - { - return this._textures; - }; + node._owner = self; - prototypeAccessors.textures.set = function (value) // eslint-disable-line require-jsdoc - { - if (value[0] instanceof core.Texture) - { - this._textures = value; - this._durations = null; - } - else - { - this._textures = []; - this._durations = []; + return node; +} - for (var i = 0; i < value.length; i++) - { - this._textures.push(value[i].texture); - this._durations.push(value[i].time); - } - } - this.gotoAndStop(0); - this.updateTexture(); - }; +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); - /** - * The AnimatedSprites current frame index. - * - * @member {number} - * @readonly - */ - prototypeAccessors.currentFrame.get = function () - { - var currentFrame = Math.floor(this._currentTime) % this._textures.length; + this._head = this._tail = undefined; + } - if (currentFrame < 0) - { - currentFrame += this._textures.length; - } + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; - return currentFrame; - }; + var node = this._head; - Object.defineProperties( AnimatedSprite.prototype, prototypeAccessors ); + if (exists) return !!node; - return AnimatedSprite; -}(sprite.Sprite)); + var ee = []; -/** - * @memberof PIXI.AnimatedSprite - * @typedef {object} FrameObject - * @type {object} - * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame - * @property {number} time - the duration of the frame in ms - */ + while (node) { + ee.push(node); + node = node._next; + } -exports.AnimatedSprite = AnimatedSprite; + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; -},{"@pixi/core":17,"@pixi/sprite":42,"@pixi/ticker":46}],41:[function(require,module,exports){ -/*! - * @pixi/sprite-tiling - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/sprite-tiling is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; + if (!node) return false; -Object.defineProperty(exports, '__esModule', { value: true }); + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } -var core = require('@pixi/core'); -var math = require('@pixi/math'); -var utils = require('@pixi/utils'); -var sprite = require('@pixi/sprite'); -var constants = require('@pixi/constants'); + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; -var tempPoint = new math.Point(); + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; -/** - * A tiling sprite is a fast way of rendering a tiling image - * - * @class - * @extends PIXI.Sprite - * @memberof PIXI - */ -var TilingSprite = /*@__PURE__*/(function (Sprite) { - function TilingSprite(texture, width, height) - { - if ( width === void 0 ) width = 100; - if ( height === void 0 ) height = 100; + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; - Sprite.call(this, texture); + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; - /** - * Tile transform - * - * @member {PIXI.Transform} - */ - this.tileTransform = new math.Transform(); + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } - // /// private + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; - /** - * The with of the tiling sprite - * - * @member {number} - * @private - */ - this._width = width; + this._head = this._tail = null; - /** - * The height of the tiling sprite - * - * @member {number} - * @private - */ - this._height = height; - - /** - * Canvas pattern - * - * @type {CanvasPattern} - * @private - */ - this._canvasPattern = null; - - /** - * matrix that is applied to UV to get the coords in Texture normalized space to coords in BaseTexture space - * - * @member {PIXI.TextureMatrix} - */ - this.uvMatrix = texture.uvMatrix || new core.TextureMatrix(texture); - - /** - * Plugin that is responsible for rendering this element. - * Allows to customize the rendering process without overriding '_render' method. - * - * @member {string} - * @default 'tilingSprite' - */ - this.pluginName = 'tilingSprite'; - - /** - * Whether or not anchor affects uvs - * - * @member {boolean} - * @default false - */ - this.uvRespectAnchor = false; + while (node) { + node._owner = null; + node = node._next; + } + return this; } + }]); - if ( Sprite ) TilingSprite.__proto__ = Sprite; - TilingSprite.prototype = Object.create( Sprite && Sprite.prototype ); - TilingSprite.prototype.constructor = TilingSprite; - - var prototypeAccessors = { clampMargin: { configurable: true },tileScale: { configurable: true },tilePosition: { configurable: true },width: { configurable: true },height: { configurable: true } }; - /** - * Changes frame clamping in corresponding textureTransform, shortcut - * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas - * - * @default 0.5 - * @member {number} - */ - prototypeAccessors.clampMargin.get = function () - { - return this.uvMatrix.clampMargin; - }; - - prototypeAccessors.clampMargin.set = function (value) // eslint-disable-line require-jsdoc - { - this.uvMatrix.clampMargin = value; - this.uvMatrix.update(true); - }; - - /** - * The scaling of the image that is being tiled - * - * @member {PIXI.ObservablePoint} - */ - prototypeAccessors.tileScale.get = function () - { - return this.tileTransform.scale; - }; - - prototypeAccessors.tileScale.set = function (value) // eslint-disable-line require-jsdoc - { - this.tileTransform.scale.copyFrom(value); - }; - - /** - * The offset of the image that is being tiled - * - * @member {PIXI.ObservablePoint} - */ - prototypeAccessors.tilePosition.get = function () - { - return this.tileTransform.position; - }; - - prototypeAccessors.tilePosition.set = function (value) // eslint-disable-line require-jsdoc - { - this.tileTransform.position.copyFrom(value); - }; - - /** - * @private - */ - TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate () - { - if (this.uvMatrix) - { - this.uvMatrix.texture = this._texture; - } - this._cachedTint = 0xFFFFFF; - }; - - /** - * Renders the object using the WebGL renderer - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - TilingSprite.prototype._render = function _render (renderer) - { - // tweak our texture temporarily.. - var texture = this._texture; - - if (!texture || !texture.valid) - { - return; - } - - this.tileTransform.updateLocalTransform(); - this.uvMatrix.update(); - - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - - /** - * Updates the bounds of the tiling sprite. - * - * @protected - */ - TilingSprite.prototype._calculateBounds = function _calculateBounds () - { - var minX = this._width * -this._anchor._x; - var minY = this._height * -this._anchor._y; - var maxX = this._width * (1 - this._anchor._x); - var maxY = this._height * (1 - this._anchor._y); - - this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); - }; - - /** - * Gets the local bounds of the sprite object. - * - * @param {PIXI.Rectangle} rect - The output rectangle. - * @return {PIXI.Rectangle} The bounds. - */ - TilingSprite.prototype.getLocalBounds = function getLocalBounds (rect) - { - // we can do a fast local bounds if the sprite has no children! - if (this.children.length === 0) - { - this._bounds.minX = this._width * -this._anchor._x; - this._bounds.minY = this._height * -this._anchor._y; - this._bounds.maxX = this._width * (1 - this._anchor._x); - this._bounds.maxY = this._height * (1 - this._anchor._y); - - if (!rect) - { - if (!this._localBoundsRect) - { - this._localBoundsRect = new math.Rectangle(); - } - - rect = this._localBoundsRect; - } - - return this._bounds.getRectangle(rect); - } - - return Sprite.prototype.getLocalBounds.call(this, rect); - }; - - /** - * Checks if a point is inside this tiling sprite. - * - * @param {PIXI.Point} point - the point to check - * @return {boolean} Whether or not the sprite contains the point. - */ - TilingSprite.prototype.containsPoint = function containsPoint (point) - { - this.worldTransform.applyInverse(point, tempPoint); - - var width = this._width; - var height = this._height; - var x1 = -width * this.anchor._x; - - if (tempPoint.x >= x1 && tempPoint.x < x1 + width) - { - var y1 = -height * this.anchor._y; - - if (tempPoint.y >= y1 && tempPoint.y < y1 + height) - { - return true; - } - } - - return false; - }; - - /** - * Destroys this sprite and optionally its texture and children - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well - */ - TilingSprite.prototype.destroy = function destroy (options) - { - Sprite.prototype.destroy.call(this, options); - - this.tileTransform = null; - this.uvMatrix = null; - }; - - /** - * Helper function that creates a new tiling sprite based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * - * @static - * @param {number|string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from - * @param {number} width - the width of the tiling sprite - * @param {number} height - the height of the tiling sprite - * @return {PIXI.TilingSprite} The newly created texture - */ - TilingSprite.from = function from (source, width, height) - { - return new TilingSprite(core.Texture.from(source), width, height); - }; + return MiniSignal; +})(); - /** - * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @param {number} width - the width of the tiling sprite - * @param {number} height - the height of the tiling sprite - * @return {PIXI.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId - */ - TilingSprite.fromFrame = function fromFrame (frameId, width, height) - { - var texture = utils.TextureCache[frameId]; +MiniSignal.MiniSignalBinding = MiniSignalBinding; - if (!texture) - { - throw new Error(("The frameId \"" + frameId + "\" does not exist in the texture cache " + (this))); - } +exports['default'] = MiniSignal; +module.exports = exports['default']; - return new TilingSprite(texture, width, height); - }; +},{}],46:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ - /** - * Helper function that creates a sprite that will contain a texture based on an image url - * If the image is not in the texture cache it will be loaded - * - * @static - * @param {string} imageId - The image url of the texture - * @param {number} width - the width of the tiling sprite - * @param {number} height - the height of the tiling sprite - * @param {Object} [options] - See {@link PIXI.BaseTexture}'s constructor for options. - * @return {PIXI.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id - */ - TilingSprite.fromImage = function fromImage (imageId, width, height, options) - { - // Fallback support for crossorigin, scaleMode parameters - if (options && typeof options !== 'object') - { - options = { - scaleMode: arguments[4], - resourceOptions: { - crossorigin: arguments[3], - }, - }; - } +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; - return new TilingSprite(core.Texture.from(imageId, options), width, height); - }; +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } - /** - * The width of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - prototypeAccessors.width.get = function () - { - return this._width; - }; + return Object(val); +} - prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc - { - this._width = value; - }; +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } - /** - * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - prototypeAccessors.height.get = function () - { - return this._height; - }; + // Detect buggy property enumeration order in older V8 versions. - prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc - { - this._height = value; - }; + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } - Object.defineProperties( TilingSprite.prototype, prototypeAccessors ); + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } - return TilingSprite; -}(sprite.Sprite)); + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } -var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} -var fragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord - floor(vTextureCoord - uClampOffset);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture2D(uSampler, coord);\n gl_FragColor = texSample * uColor;\n}\n"; +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; -var fragmentSimple = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n"; + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); -var tempMat = new math.Matrix(); + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } -/** - * WebGL renderer plugin for tiling sprites - * - * @class - * @memberof PIXI - * @extends PIXI.ObjectRenderer - */ -var TilingSpriteRenderer = /*@__PURE__*/(function (ObjectRenderer) { - function TilingSpriteRenderer(renderer) - { - ObjectRenderer.call(this, renderer); + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } - var uniforms = { globals: this.renderer.globalUniforms }; + return to; +}; - this.shader = core.Shader.from(vertex, fragment, uniforms); +},{}],47:[function(require,module,exports){ +'use strict' - this.simpleShader = core.Shader.from(vertex, fragmentSimple, uniforms); +module.exports = function parseURI (str, opts) { + opts = opts || {} - this.quad = new core.QuadUv(); + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } + } - if ( ObjectRenderer ) TilingSpriteRenderer.__proto__ = ObjectRenderer; - TilingSpriteRenderer.prototype = Object.create( ObjectRenderer && ObjectRenderer.prototype ); - TilingSpriteRenderer.prototype.constructor = TilingSpriteRenderer; - - /** - * - * @param {PIXI.TilingSprite} ts tilingSprite to be rendered - */ - TilingSpriteRenderer.prototype.render = function render (ts) - { - var renderer = this.renderer; - var quad = this.quad; - - var vertices = quad.vertices; - - vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; - vertices[1] = vertices[3] = ts._height * -ts.anchor.y; - - vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); - vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); - - if (ts.uvRespectAnchor) - { - vertices = quad.uvs; - - vertices[0] = vertices[6] = -ts.anchor.x; - vertices[1] = vertices[3] = -ts.anchor.y; - - vertices[2] = vertices[4] = 1.0 - ts.anchor.x; - vertices[5] = vertices[7] = 1.0 - ts.anchor.y; - } - - quad.invalidate(); - - var tex = ts._texture; - var baseTex = tex.baseTexture; - var lt = ts.tileTransform.localTransform; - var uv = ts.uvMatrix; - var isSimple = baseTex.isPowerOfTwo - && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; - - // auto, force repeat wrapMode for big tiling textures - if (isSimple) - { - if (!baseTex._glTextures[renderer.CONTEXT_UID]) - { - if (baseTex.wrapMode === constants.WRAP_MODES.CLAMP) - { - baseTex.wrapMode = constants.WRAP_MODES.REPEAT; - } - } - else - { - isSimple = baseTex.wrapMode !== constants.WRAP_MODES.CLAMP; - } - } - - var shader = isSimple ? this.simpleShader : this.shader; - - var w = tex.width; - var h = tex.height; - var W = ts._width; - var H = ts._height; - - tempMat.set(lt.a * w / W, - lt.b * w / H, - lt.c * h / W, - lt.d * h / H, - lt.tx / W, - lt.ty / H); - - // that part is the same as above: - // tempMat.identity(); - // tempMat.scale(tex.width, tex.height); - // tempMat.prepend(lt); - // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); - - tempMat.invert(); - if (isSimple) - { - tempMat.prepend(uv.mapCoord); - } - else - { - shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); - shader.uniforms.uClampFrame = uv.uClampFrame; - shader.uniforms.uClampOffset = uv.uClampOffset; - } - - shader.uniforms.uTransform = tempMat.toArray(true); - shader.uniforms.uColor = utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, - shader.uniforms.uColor, baseTex.alphaMode); - shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); - shader.uniforms.uSampler = tex; + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 - renderer.shader.bind(shader); - renderer.geometry.bind(quad);// , renderer.shader.getGLShader()); + while (i--) uri[o.key[i]] = m[i] || '' - renderer.state.setBlendMode(utils.correctBlendMode(ts.blendMode, baseTex.alphaMode)); - renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0); - }; + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) - return TilingSpriteRenderer; -}(core.ObjectRenderer)); + return uri +} -exports.TilingSprite = TilingSprite; -exports.TilingSpriteRenderer = TilingSpriteRenderer; +},{}],48:[function(require,module,exports){ +(function (global){ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pixi.js")):"function"==typeof define&&define.amd?define(["exports","pixi.js"],e):e((t=t||self).Viewport={},t.PIXI)}(this,(function(t,e){"use strict";class i{constructor(t){this.viewport=t,this.touches=[],this.addListeners()}addListeners(){this.viewport.interactive=!0,this.viewport.forceHitArea||(this.viewport.hitArea=new e.Rectangle(0,0,this.viewport.worldWidth,this.viewport.worldHeight)),this.viewport.on("pointerdown",this.down,this),this.viewport.on("pointermove",this.move,this),this.viewport.on("pointerup",this.up,this),this.viewport.on("pointerupoutside",this.up,this),this.viewport.on("pointercancel",this.up,this),this.viewport.on("pointerout",this.up,this),this.wheelFunction=t=>this.handleWheel(t),this.viewport.options.divWheel.addEventListener("wheel",this.wheelFunction,{passive:this.viewport.options.passiveWheel}),this.isMouseDown=!1}destroy(){this.viewport.options.divWheel.removeEventListener("wheel",this.wheelFunction)}down(t){if(this.viewport.pause||!this.viewport.worldVisible)return;if("mouse"===t.data.pointerType?this.isMouseDown=!0:this.get(t.data.pointerId)||this.touches.push({id:t.data.pointerId,last:null}),1===this.count()){this.last=t.data.global.clone();const e=this.viewport.plugins.get("decelerate"),i=this.viewport.plugins.get("bounce");e&&e.isActive()||i&&i.isActive()?this.clickedAvailable=!1:this.clickedAvailable=!0}else this.clickedAvailable=!1;this.viewport.plugins.down(t)&&this.viewport.options.stopPropagation&&t.stopPropagation()}checkThreshold(t){return Math.abs(t)>=this.viewport.threshold}move(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.plugins.move(t);if(this.clickedAvailable){const e=t.data.global.x-this.last.x,i=t.data.global.y-this.last.y;(this.checkThreshold(e)||this.checkThreshold(i))&&(this.clickedAvailable=!1)}e&&this.viewport.options.stopPropagation&&t.stopPropagation()}up(t){if(this.viewport.pause||!this.viewport.worldVisible)return;"mouse"===t.data.pointerType&&(this.isMouseDown=!1),"mouse"!==t.data.pointerType&&this.remove(t.data.pointerId);const e=this.viewport.plugins.up(t);this.clickedAvailable&&0===this.count()&&(this.viewport.emit("clicked",{event:t,screen:this.last,world:this.viewport.toWorld(this.last),viewport:this}),this.clickedAvailable=!1),e&&this.viewport.options.stopPropagation&&t.stopPropagation()}getPointerPosition(t){let i=new e.Point;return this.viewport.options.interaction?this.viewport.options.interaction.mapPositionToPoint(i,t.clientX,t.clientY):(i.x=t.clientX,i.y=t.clientY),i}handleWheel(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.toLocal(this.getPointerPosition(t));if(this.viewport.left<=e.x&&e.x<=this.viewport.right&&this.viewport.top<=e.y&&e.y<=this.viewport.bottom){this.viewport.plugins.wheel(t)&&!this.viewport.options.passiveWheel&&t.preventDefault()}}pause(){this.touches=[],this.isMouseDown=!1}get(t){for(let e of this.touches)if(e.id===t)return e;return null}remove(t){for(let e=0;e{t.includes(e.code)&&(this.keyIsPressed=!0)}),parent.addEventListener("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)})}mouseButtons(t){this.mouse=t&&"all"!==t?[-1!==t.indexOf("left"),-1!==t.indexOf("middle"),-1!==t.indexOf("right")]:[!0,!0,!0]}parseUnderflow(){const t=this.options.underflow.toLowerCase();"center"===t?(this.underflowX=0,this.underflowY=0):(this.underflowX=-1!==t.indexOf("left")?-1:-1!==t.indexOf("right")?1:0,this.underflowY=-1!==t.indexOf("top")?-1:-1!==t.indexOf("bottom")?1:0)}checkButtons(t){const e="mouse"===t.data.pointerType,i=this.parent.input.count();return!(!(1===i||i>1&&!this.parent.plugins.get("pinch"))||e&&!this.mouse[t.data.button])}checkKeyPress(t){return!!(!this.options.keyToPress||this.keyIsPressed||this.options.ignoreKeyToPressOnTouch&&"touch"===t.data.pointerType)}down(t){if(!this.paused&&this.options.pressDrag)return this.checkButtons(t)&&this.checkKeyPress(t)?(this.last={x:t.data.global.x,y:t.data.global.y},this.current=t.data.pointerId,!0):void(this.last=null)}get active(){return this.moved}move(t){if(!this.paused&&this.options.pressDrag&&this.last&&this.current===t.data.pointerId){const i=t.data.global.x,s=t.data.global.y,n=this.parent.input.count();if(1===n||n>1&&!this.parent.plugins.get("pinch")){const n=i-this.last.x,h=s-this.last.y;if(this.moved||this.xDirection&&this.parent.input.checkThreshold(n)||this.yDirection&&this.parent.input.checkThreshold(h)){const n={x:i,y:s};return this.xDirection&&(this.parent.x+=(n.x-this.last.x)*this.options.factor),this.yDirection&&(this.parent.y+=(n.y-this.last.y)*this.options.factor),this.last=n,this.moved||this.parent.emit("drag-start",{event:t,screen:new e.Point(this.last.x,this.last.y),world:this.parent.toWorld(new e.Point(this.last.x,this.last.y)),viewport:this.parent}),this.moved=!0,this.parent.emit("moved",{viewport:this.parent,type:"drag"}),!0}}else this.moved=!1}}up(t){if(this.paused)return;const i=this.parent.input.touches;if(1===i.length){const t=i[0];return t.last&&(this.last={x:t.last.x,y:t.last.y},this.current=t.id),this.moved=!1,!0}if(this.last&&this.moved){const i=new e.Point(this.last.x,this.last.y);return this.parent.emit("drag-end",{event:t,screen:i,world:this.parent.toWorld(i),viewport:this.parent}),this.last=null,this.moved=!1,!0}}wheel(t){if(!this.paused&&this.options.wheel){if(!this.parent.plugins.get("wheel"))return this.xDirection&&(this.parent.x+=t.deltaX*this.options.wheelScroll*this.reverse),this.yDirection&&(this.parent.y+=t.deltaY*this.options.wheelScroll*this.reverse),this.options.clampWheel&&this.clamp(),this.parent.emit("wheel-scroll",this.parent),this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.options.passiveWheel||t.preventDefault(),!0}}resume(){this.last=null,this.paused=!1}clamp(){const t=this.parent.plugins.get("decelerate")||{};if("y"!==this.options.clampWheel)if(this.parent.screenWorldWidththis.parent.worldWidth&&(this.parent.x=-this.parent.worldWidth*this.parent.scale.x+this.parent.screenWidth,t.x=0);if("x"!==this.options.clampWheel)if(this.parent.screenWorldHeightthis.parent.worldHeight&&(this.parent.y=-this.parent.worldHeight*this.parent.scale.y+this.parent.screenHeight,t.y=0)}}const a={noDrag:!1,percent:1,center:null};class p extends h{constructor(t,e={}){super(t),this.options=Object.assign({},a,e)}down(){if(this.parent.input.count()>=2)return this.active=!0,!0}move(t){if(this.paused||!this.active)return;const e=t.data.global.x,i=t.data.global.y,s=this.parent.input.touches;if(s.length>=2){const n=s[0],h=s[1],o=n.last&&h.last?Math.sqrt(Math.pow(h.last.x-n.last.x,2)+Math.pow(h.last.y-n.last.y,2)):null;if(n.id===t.data.pointerId?n.last={x:e,y:i,data:t.data}:h.id===t.data.pointerId&&(h.last={x:e,y:i,data:t.data}),o){let t;const e={x:n.last.x+(h.last.x-n.last.x)/2,y:n.last.y+(h.last.y-n.last.y)/2};this.options.center||(t=this.parent.toLocal(e));let i=Math.sqrt(Math.pow(h.last.x-n.last.x,2)+Math.pow(h.last.y-n.last.y,2));i=0===i?i=1e-10:i;const s=(1-o/i)*this.options.percent*this.parent.scale.x;this.parent.scale.x+=s,this.parent.scale.y+=s,this.parent.emit("zoomed",{viewport:this.parent,type:"pinch"});const r=this.parent.plugins.get("clamp-zoom");if(r&&r.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=e.x-i.x,this.parent.y+=e.y-i.y,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})}!this.options.noDrag&&this.lastCenter&&(this.parent.x+=e.x-this.lastCenter.x,this.parent.y+=e.y-this.lastCenter.y,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})),this.lastCenter=e,this.moved=!0}else this.pinching||(this.parent.emit("pinch-start",this.parent),this.pinching=!0);return!0}}up(){if(this.pinching&&this.parent.input.touches.length<=1)return this.active=!1,this.lastCenter=null,this.pinching=!1,this.moved=!1,this.parent.emit("pinch-end",this.parent),!0}}const l={left:!1,right:!1,top:!1,bottom:!1,direction:null,underflow:"center"};class c extends h{constructor(t,e={}){super(t),this.options=Object.assign({},l,e),this.options.direction&&(this.options.left="x"===this.options.direction||"all"===this.options.direction||null,this.options.right="x"===this.options.direction||"all"===this.options.direction||null,this.options.top="y"===this.options.direction||"all"===this.options.direction||null,this.options.bottom="y"===this.options.direction||"all"===this.options.direction||null),this.parseUnderflow(),this.last={x:null,y:null,scaleX:null,scaleY:null},this.update()}parseUnderflow(){const t=this.options.underflow.toLowerCase();"none"===t?this.noUnderflow=!0:"center"===t?(this.underflowX=this.underflowY=0,this.noUnderflow=!1):(this.underflowX=-1!==t.indexOf("left")?-1:-1!==t.indexOf("right")?1:0,this.underflowY=-1!==t.indexOf("top")?-1:-1!==t.indexOf("bottom")?1:0,this.noUnderflow=!1)}move(){return this.update(),!1}update(){if(this.paused)return;if(this.parent.x===this.last.x&&this.parent.y===this.last.y&&this.parent.scale.x===this.last.scaleX&&this.parent.scale.y===this.last.scaleY)return;const t={x:this.parent.x,y:this.parent.y},e=this.parent.plugins.decelerate||{};if(null!==this.options.left||null!==this.options.right){let i=!1;if(this.parent.screenWorldWidth(!0===this.options.right?this.parent.worldWidth:this.options.right)&&(this.parent.x=-(!0===this.options.right?this.parent.worldWidth:this.options.right)*this.parent.scale.x+this.parent.screenWidth,e.x=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-x"})}if(null!==this.options.top||null!==this.options.bottom){let i=!1;if(this.parent.screenWorldHeight(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)&&(this.parent.y=-(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)*this.parent.scale.y+this.parent.screenHeight,e.y=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-y"})}this.last.x=this.parent.x,this.last.y=this.parent.y,this.last.scaleX=this.parent.scale.x,this.last.scaleY=this.parent.scale.y}reset(){this.update()}}const d={minWidth:null,minHeight:null,maxWidth:null,maxHeight:null,minScale:null,maxScale:null};class u extends h{constructor(t,e={}){super(t),this.options=Object.assign({},d,e),this.clamp()}resize(){this.clamp()}clamp(){if(!this.paused)if(this.options.minWidth||this.options.minHeight||this.options.maxWidth||this.options.maxHeight){let t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight;if(null!==this.options.minWidth&&tthis.options.maxWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.maxWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.minHeight&&ethis.options.maxHeight){const t=this.parent.scale.y;this.parent.fitHeight(this.options.maxHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/t,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}}else{let t=this.parent.scale.x;null!==this.options.minScale&&tthis.options.maxScale&&(t=this.options.maxScale),t!==this.parent.scale.x&&(this.parent.scale.set(t),this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"}))}}reset(){this.clamp()}}const g={friction:.95,bounce:.8,minSpeed:.01};class m extends h{constructor(t,e={}){super(t),this.options=Object.assign({},g,e),this.saved=[],this.reset(),this.parent.on("moved",t=>this.moved(t))}destroy(){this.parent}down(){this.saved=[],this.x=this.y=!1}isActive(){return this.x||this.y}move(){if(this.paused)return;const t=this.parent.input.count();(1===t||t>1&&!this.parent.plugins.get("pinch"))&&(this.saved.push({x:this.parent.x,y:this.parent.y,time:performance.now()}),this.saved.length>60&&this.saved.splice(0,30))}moved(t){if(this.saved.length){const e=this.saved[this.saved.length-1];"clamp-x"===t.type?e.x===t.original.x&&(e.x=this.parent.x):"clamp-y"===t.type&&e.y===t.original.y&&(e.y=this.parent.y)}}up(){if(0===this.parent.input.count()&&this.saved.length){const t=performance.now();for(let e of this.saved)if(e.time>=t-100){const i=t-e.time;this.x=(this.parent.x-e.x)/i,this.y=(this.parent.y-e.y)/i,this.percentChangeX=this.percentChangeY=this.options.friction;break}}}activate(t){void 0!==(t=t||{}).x&&(this.x=t.x,this.percentChangeX=this.options.friction),void 0!==t.y&&(this.y=t.y,this.percentChangeY=this.options.friction)}update(t){if(this.paused)return;let e;this.x&&(this.parent.x+=this.x*t,this.x*=this.percentChangeX,Math.abs(this.x)=this.options.time?(this.parent.x=e.end,this.toX=null,this.parent.emit("bounce-x-end",this.parent)):this.parent.x=this.ease(e.time,e.start,e.delta,this.options.time)}if(this.toY){const e=this.toY;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-y"}),e.time>=this.options.time?(this.parent.y=e.end,this.toY=null,this.parent.emit("bounce-y-end",this.parent)):this.parent.y=this.ease(e.time,e.start,e.delta,this.options.time)}}}calcUnderflowX(){let t;switch(this.underflowX){case-1:t=0;break;case 1:t=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:t=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}return t}calcUnderflowY(){let t;switch(this.underflowY){case-1:t=0;break;case 1:t=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:t=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}return t}oob(){const t=this.options.bounceBox;if(t){const i=void 0===t.x?0:t.x,s=void 0===t.y?0:t.y,n=void 0===t.width?this.parent.worldWidth:t.width,h=void 0===t.height?this.parent.worldHeight:t.height;return{left:this.parent.leftn,top:this.parent.toph,topLeft:new e.Point(i*this.parent.scale.x,s*this.parent.scale.y),bottomRight:new e.Point(n*this.parent.scale.x-this.parent.screenWidth,h*this.parent.scale.y-this.parent.screenHeight)}}return{left:this.parent.left<0,right:this.parent.right>this.parent.worldWidth,top:this.parent.top<0,bottom:this.parent.bottom>this.parent.worldHeight,topLeft:new e.Point(0,0),bottomRight:new e.Point(this.parent.worldWidth*this.parent.scale.x-this.parent.screenWidth,this.parent.worldHeight*this.parent.scale.y-this.parent.screenHeight)}}bounce(){if(this.paused)return;let t,e=this.parent.plugins.get("decelerate");e&&(e.x||e.y)&&(e.x&&e.percentChangeX===e.options.friction||e.y&&e.percentChangeY===e.options.friction)&&(t=this.oob(),(t.left&&this.left||t.right&&this.right)&&(e.percentChangeX=this.options.friction),(t.top&&this.top||t.bottom&&this.bottom)&&(e.percentChangeY=this.options.friction));const i=this.parent.plugins.get("drag")||{},s=this.parent.plugins.get("pinch")||{};if(e=e||{},!(i.active||s.active||this.toX&&this.toY||e.x&&e.y)){t=t||this.oob();const i=t.topLeft,s=t.bottomRight;if(!this.toX&&!e.x){let e=null;t.left&&this.left?e=this.parent.screenWorldWidththis.options.time)i=!0,s=this.startX+this.deltaX,n=this.startY+this.deltaY;else{const t=this.ease(e.time,0,1,this.options.time);s=this.startX+this.deltaX*t,n=this.startY+this.deltaY*t}this.options.topLeft?this.parent.moveCorner(s,n):this.parent.moveCenter(s,n),this.parent.emit("moved",{viewport:this.parent,type:"snap"}),i&&(this.options.removeOnComplete&&this.parent.plugins.remove("snap"),this.parent.emit("snap-end",this.parent),this.snapping=null)}else{const t=this.options.topLeft?this.parent.corner:this.parent.center;t.x===this.x&&t.y===this.y||this.snapStart()}}}const H={width:0,height:0,time:1e3,ease:"easeInOutSine",center:null,interrupt:!0,removeOnComplete:!1,removeOnInterrupts:!1,forceStart:!1,noMove:!1};class M extends h{constructor(t,e={}){super(t),this.options=Object.assign({},H,e),this.ease=y(this.options.ease),this.options.width>0&&(this.xScale=t.screenWidth/this.options.width),this.options.height>0&&(this.yScale=t.screenHeight/this.options.height),this.xIndependent=!!this.xScale,this.yIndependent=!!this.yScale,this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale,0===this.options.time?(t.container.scale.x=this.xScale,t.container.scale.y=this.yScale,this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom")):e.forceStart&&this.createSnapping()}createSnapping(){const t=this.parent.scale;this.snapping={time:0,startX:t.x,startY:t.y,deltaX:this.xScale-t.x,deltaY:this.yScale-t.y},this.parent.emit("snap-zoom-start",this.parent)}resize(){this.snapping=null,this.options.width>0&&(this.xScale=this.parent.screenWidth/this.options.width),this.options.height>0&&(this.yScale=this.parent.screenHeight/this.options.height),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale}wheel(){this.options.removeOnInterrupt&&this.parent.plugins.remove("snap-zoom")}down(){this.options.removeOnInterrupt?this.parent.plugins.remove("snap-zoom"):this.options.interrupt&&(this.snapping=null)}update(t){if(this.paused)return;if(this.options.interrupt&&0!==this.parent.input.count())return;let e;if(this.options.center||this.options.noMove||(e=this.parent.center),this.snapping){if(this.snapping){const i=this.snapping;if(i.time+=t,i.time>=this.options.time)this.parent.scale.set(this.xScale,this.yScale),this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom"),this.parent.emit("snap-zoom-end",this.parent),this.snapping=null;else{const t=this.snapping;this.parent.scale.x=this.ease(t.time,t.startX,t.deltaX,this.options.time),this.parent.scale.y=this.ease(t.time,t.startY,t.deltaY,this.options.time)}const s=this.parent.plugins.get("clamp-zoom");s&&s.clamp(),this.options.noMove||(this.options.center?this.parent.moveCenter(this.options.center):this.parent.moveCenter(e))}}else this.parent.scale.x===this.xScale&&this.parent.scale.y===this.yScale||this.createSnapping()}resume(){this.snapping=null,super.resume()}}const S={speed:0,acceleration:null,radius:null};class O extends h{constructor(t,e,i={}){super(t),this.target=e,this.options=Object.assign({},S,i),this.velocity={x:0,y:0}}update(t){if(this.paused)return;const e=this.parent.center;let i=this.target.x,s=this.target.y;if(this.options.radius){if(!(Math.sqrt(Math.pow(this.target.y-e.y,2)+Math.pow(this.target.x-e.x,2))>this.options.radius))return;{const t=Math.atan2(this.target.y-e.y,this.target.x-e.x);i=this.target.x-Math.cos(t)*this.options.radius,s=this.target.y-Math.sin(t)*this.options.radius}}const n=i-e.x,h=s-e.y;if(n||h)if(this.options.speed)if(this.options.acceleration){const o=Math.atan2(s-e.y,i-e.x),r=Math.sqrt(Math.pow(n,2)+Math.pow(h,2));if(r){const a=(Math.pow(this.velocity.x,2)+Math.pow(this.velocity.y,2))/(2*this.options.acceleration);this.velocity=r>a?{x:Math.min(this.velocity.x+this.options.acceleration*t,this.options.speed),y:Math.min(this.velocity.y+this.options.acceleration*t,this.options.speed)}:{x:Math.max(this.velocity.x-this.options.acceleration*this.options.speed,0),y:Math.max(this.velocity.y-this.options.acceleration*this.options.speed,0)};const p=Math.cos(o)*this.velocity.x,l=Math.sin(o)*this.velocity.y,c=Math.abs(p)>Math.abs(n)?i:e.x+p,d=Math.abs(l)>Math.abs(h)?s:e.y+l;this.parent.moveCenter(c,d),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}else{const t=Math.atan2(s-e.y,i-e.x),o=Math.cos(t)*this.options.speed,r=Math.sin(t)*this.options.speed,a=Math.abs(o)>Math.abs(n)?i:e.x+o,p=Math.abs(r)>Math.abs(h)?s:e.y+r;this.parent.moveCenter(a,p),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}else this.parent.moveCenter(i,s),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}const C={percent:.1,smooth:!1,interrupt:!0,reverse:!1,center:null,lineHeight:20};class z extends h{constructor(t,e={}){super(t),this.options=Object.assign({},C,e)}down(){this.options.interrupt&&(this.smoothing=null)}update(){if(this.smoothing){const t=this.smoothingCenter,e=this.smoothing;let i;this.options.center||(i=this.parent.toLocal(t)),this.parent.scale.x+=e.x,this.parent.scale.y+=e.y,this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const s=this.parent.plugins.get("clamp-zoom");if(s&&s.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const e=this.parent.toGlobal(i);this.parent.x+=t.x-e.x,this.parent.y+=t.y-e.y}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.smoothingCount++,this.smoothingCount>=this.options.smooth&&(this.smoothing=null)}}wheel(t){if(this.paused)return;let e=this.parent.input.getPointerPosition(t);const i=(this.options.reverse?-1:1)*-t.deltaY*(t.deltaMode?this.options.lineHeight:1)/500,s=Math.pow(2,(1+this.options.percent)*i);if(this.options.smooth){const t={x:this.smoothing?this.smoothing.x*(this.options.smooth-this.smoothingCount):0,y:this.smoothing?this.smoothing.y*(this.options.smooth-this.smoothingCount):0};this.smoothing={x:((this.parent.scale.x+t.x)*s-this.parent.scale.x)/this.options.smooth,y:((this.parent.scale.y+t.y)*s-this.parent.scale.y)/this.options.smooth},this.smoothingCount=0,this.smoothingCenter=e}else{let t;this.options.center||(t=this.parent.toLocal(e)),this.parent.scale.x*=s,this.parent.scale.y*=s,this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const i=this.parent.plugins.get("clamp-zoom");if(i&&i.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=e.x-i.x,this.parent.y+=e.y-i.y}}return this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel",{wheel:{dx:t.deltaX,dy:t.deltaY,dz:t.deltaZ},event:t,viewport:this.parent}),!this.parent.options.passiveWheel||void 0}}const k={radius:null,distance:null,top:null,bottom:null,left:null,right:null,speed:8,reverse:!1,noDecelerate:!1,linear:!1,allowButtons:!1};class I extends h{constructor(t,e={}){super(t),this.options=Object.assign({},k,e),this.reverse=this.options.reverse?1:-1,this.radiusSquared=Math.pow(this.options.radius,2),this.resize()}resize(){const t=this.options.distance;null!==t?(this.left=t,this.top=t,this.right=this.parent.worldScreenWidth-t,this.bottom=this.parent.worldScreenHeight-t):this.radius||(this.left=this.options.left,this.top=this.options.top,this.right=null===this.options.right?null:this.parent.worldScreenWidth-this.options.right,this.bottom=null===this.options.bottom?null:this.parent.worldScreenHeight-this.options.bottom)}down(){this.options.allowButtons||(this.horizontal=this.vertical=null)}move(t){if("mouse"!==t.data.pointerType&&1!==t.data.identifier||!this.options.allowButtons&&0!==t.data.buttons)return;const e=t.data.global.x,i=t.data.global.y;if(this.radiusSquared){const t=this.parent.toScreen(this.parent.center);if(Math.pow(t.x-e,2)+Math.pow(t.y-i,2)>=this.radiusSquared){const s=Math.atan2(t.y-i,t.x-e);this.options.linear?(this.horizontal=Math.round(Math.cos(s))*this.options.speed*this.reverse*.06,this.vertical=Math.round(Math.sin(s))*this.options.speed*this.reverse*.06):(this.horizontal=Math.cos(s)*this.options.speed*this.reverse*.06,this.vertical=Math.sin(s)*this.options.speed*this.reverse*.06)}else this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=0}else null!==this.left&&ethis.right?this.horizontal=-1*this.reverse*this.options.speed*.06:(this.decelerateHorizontal(),this.horizontal=0),null!==this.top&&ithis.bottom?this.vertical=-1*this.reverse*this.options.speed*.06:(this.decelerateVertical(),this.vertical=0)}decelerateHorizontal(){const t=this.parent.plugins.get("decelerate");this.horizontal&&t&&!this.options.noDecelerate&&t.activate({x:this.horizontal*this.options.speed*this.reverse/(1e3/60)})}decelerateVertical(){const t=this.parent.plugins.get("decelerate");this.vertical&&t&&!this.options.noDecelerate&&t.activate({y:this.vertical*this.options.speed*this.reverse/(1e3/60)})}up(){this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=null}update(){if(!this.paused&&(this.horizontal||this.vertical)){const t=this.parent.center;this.horizontal&&(t.x+=this.horizontal*this.options.speed),this.vertical&&(t.y+=this.vertical*this.options.speed),this.parent.moveCenter(t),this.parent.emit("moved",{viewport:this.parent,type:"mouse-edges"})}}}const P={removeOnInterrupt:!1,ease:"linear",time:1e3};class X extends h{constructor(t,e={}){super(t),this.options=Object.assign({},P,e),this.options.ease=y(this.options.ease),this.setupPosition(),this.setupZoom()}setupPosition(){void 0!==this.options.position?(this.startX=this.parent.center.x,this.startY=this.parent.center.y,this.deltaX=this.options.position.x-this.parent.center.x,this.deltaY=this.options.position.y-this.parent.center.y,this.keepCenter=!1):this.keepCenter=!0}setupZoom(){this.width=null,this.height=null,void 0!==this.options.scale?this.width=this.parent.screenWidth/this.options.scale:void 0!==this.options.scaleX||void 0!==this.options.scaleY?(void 0!==this.options.scaleX&&(this.width=this.parent.screenWidth/this.options.scaleX),void 0!==this.options.scaleY&&(this.height=this.parent.screenHeight/this.options.scaleY)):(void 0!==this.options.width&&(this.width=this.options.width),void 0!==this.options.height&&(this.height=this.options.height)),null!==typeof this.width&&(this.startWidth=this.parent.screenWidthInWorldPixels,this.deltaWidth=this.width-this.startWidth),null!==typeof this.height&&(this.startHeight=this.parent.screenHeightInWorldPixels,this.deltaHeight=this.height-this.startHeight),this.time=0}down(){this.options.removeOnInterrupt&&this.parent.plugins.remove("animate")}complete(){this.parent.plugins.remove("animate"),null!==this.width&&this.parent.fitWidth(this.width,this.keepCenter,null===this.height),null!==this.height&&this.parent.fitHeight(this.height,this.keepCenter,null===this.width),this.keepCenter||this.parent.moveCenter(this.options.position.x,this.options.position.y),this.parent.emit("animate-end",this.parent),this.options.callbackOnComplete&&this.options.callbackOnComplete(this.parent)}update(t){if(!this.paused)if(this.time+=t,this.time>=this.options.time)this.complete();else{const t=new e.Point(this.parent.scale.x,this.parent.scale.y),i=this.options.ease(this.time,0,1,this.options.time);if(null!==this.width&&this.parent.fitWidth(this.startWidth+this.deltaWidth*i,this.keepCenter,null===this.height),null!==this.height&&this.parent.fitHeight(this.startHeight+this.deltaHeight*i,this.keepCenter,null===this.width),null===this.width?this.parent.scale.x=this.parent.scale.y:null===this.height&&(this.parent.scale.y=this.parent.scale.x),!this.keepCenter){const t=new e.Point(this.parent.x,this.parent.y);this.parent.moveCenter(this.startX+this.deltaX*i,this.startY+this.deltaY*i),this.parent.emit("moved",{viewport:this.parent,original:t,type:"animate"})}(this.width||this.height)&&this.parent.emit("zoomed",{viewport:this.parent,original:t,type:"animate"}),this.keepCenter}}}const Y={screenWidth:window.innerWidth,screenHeight:window.innerHeight,worldWidth:null,worldHeight:null,threshold:5,passiveWheel:!0,stopPropagation:!1,forceHitArea:null,noTicker:!1,interaction:null,disableOnContextMenu:!1};class A extends e.Container{constructor(t={}){if(super(),this.options=Object.assign({},Y,t),t.ticker)this.options.ticker=t.ticker;else{let i;const s=e;i=parseInt(/^(\d+)\./.exec(e.VERSION)[1])<5?s.ticker.shared:s.Ticker.shared,this.options.ticker=t.ticker||i}this.screenWidth=this.options.screenWidth,this.screenHeight=this.options.screenHeight,this._worldWidth=this.options.worldWidth,this._worldHeight=this.options.worldHeight,this.forceHitArea=this.options.forceHitArea,this.threshold=this.options.threshold,this.options.divWheel=this.options.divWheel||document.body,this.options.disableOnContextMenu&&(this.options.divWheel.oncontextmenu=t=>t.preventDefault()),this.options.noTicker||(this.tickerFunction=()=>this.update(this.options.ticker.elapsedMS),this.options.ticker.add(this.tickerFunction)),this.input=new i(this),this.plugins=new n(this)}destroy(t){this.options.noTicker||this.options.ticker.remove(this.tickerFunction),this.input.destroy(),super.destroy(t)}update(t){this.pause||(this.plugins.update(t),this.lastViewport&&(this.lastViewport.x!==this.x||this.lastViewport.y!==this.y?this.moving=!0:this.moving&&(this.emit("moved-end",this),this.moving=!1),this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y?this.zooming=!0:this.zooming&&(this.emit("zoomed-end",this),this.zooming=!1)),this.forceHitArea||(this._hitAreaDefault=new e.Rectangle(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight),this.hitArea=this._hitAreaDefault),this._dirty=this._dirty||!this.lastViewport||this.lastViewport.x!==this.x||this.lastViewport.y!==this.y||this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y,this.lastViewport={x:this.x,y:this.y,scaleX:this.scale.x,scaleY:this.scale.y},this.emit("frame-end",this))}resize(t=window.innerWidth,e=window.innerHeight,i,s){this.screenWidth=t,this.screenHeight=e,void 0!==i&&(this._worldWidth=i),void 0!==s&&(this._worldHeight=s),this.plugins.resize(),this.dirty=!0}get worldWidth(){return this._worldWidth?this._worldWidth:this.width/this.scale.x}set worldWidth(t){this._worldWidth=t,this.plugins.resize()}get worldHeight(){return this._worldHeight?this._worldHeight:this.height/this.scale.y}set worldHeight(t){this._worldHeight=t,this.plugins.resize()}getVisibleBounds(){return new e.Rectangle(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight)}toWorld(t,i){return 2===arguments.length?this.toLocal(new e.Point(t,i)):this.toLocal(t)}toScreen(t,i){return 2===arguments.length?this.toGlobal(new e.Point(t,i)):this.toGlobal(t)}get worldScreenWidth(){return this.screenWidth/this.scale.x}get worldScreenHeight(){return this.screenHeight/this.scale.y}get screenWorldWidth(){return this.worldWidth*this.scale.x}get screenWorldHeight(){return this.worldHeight*this.scale.y}get center(){return new e.Point(this.worldScreenWidth/2-this.x/this.scale.x,this.worldScreenHeight/2-this.y/this.scale.y)}set center(t){this.moveCenter(t)}moveCenter(){let t,e;return isNaN(arguments[0])?(t=arguments[0].x,e=arguments[0].y):(t=arguments[0],e=arguments[1]),this.position.set((this.worldScreenWidth/2-t)*this.scale.x,(this.worldScreenHeight/2-e)*this.scale.y),this.plugins.reset(),this.dirty=!0,this}get corner(){return new e.Point(-this.x/this.scale.x,-this.y/this.scale.y)}set corner(t){this.moveCorner(t)}moveCorner(t,e){return 1===arguments.length?this.position.set(-t.x*this.scale.x,-t.y*this.scale.y):this.position.set(-t*this.scale.x,-e*this.scale.y),this.plugins.reset(),this}get screenWidthInWorldPixels(){return this.screenWidth/this.scale.x}get screenHeightInWorldPixels(){return this.screenHeight/this.scale.y}findFitWidth(t){return this.screenWidth/t}findFitHeight(t){return this.screenHeight/t}findFit(t,e){const i=this.screenWidth/t,s=this.screenHeight/e;return Math.min(i,s)}findCover(t,e){const i=this.screenWidth/t,s=this.screenHeight/e;return Math.max(i,s)}fitWidth(t,e,i=!0,s){let n;e&&(n=this.center),this.scale.x=this.screenWidth/t,i&&(this.scale.y=this.scale.x);const h=this.plugins.get("clamp-zoom");return!s&&h&&h.clamp(),e&&this.moveCenter(n),this}fitHeight(t,e,i=!0,s){let n;e&&(n=this.center),this.scale.y=this.screenHeight/t,i&&(this.scale.x=this.scale.y);const h=this.plugins.get("clamp-zoom");return!s&&h&&h.clamp(),e&&this.moveCenter(n),this}fitWorld(t){let e;t&&(e=this.center),this.scale.x=this.screenWidth/this.worldWidth,this.scale.y=this.screenHeight/this.worldHeight,this.scale.xthis.worldWidth,top:this.top<0,bottom:this.bottom>this._worldHeight,cornerPoint:new e.Point(this.worldWidth*this.scale.x-this.screenWidth,this.worldHeight*this.scale.y-this.screenHeight)}}get right(){return-this.x/this.scale.x+this.worldScreenWidth}set right(t){this.x=-t*this.scale.x+this.screenWidth,this.plugins.reset()}get left(){return-this.x/this.scale.x}set left(t){this.x=-t*this.scale.x,this.plugins.reset()}get top(){return-this.y/this.scale.y}set top(t){this.y=-t*this.scale.y,this.plugins.reset()}get bottom(){return-this.y/this.scale.y+this.worldScreenHeight}set bottom(t){this.y=-t*this.scale.y+this.screenHeight,this.plugins.reset()}get dirty(){return this._dirty}set dirty(t){this._dirty=t}get forceHitArea(){return this._forceHitArea}set forceHitArea(t){t?(this._forceHitArea=t,this.hitArea=t):(this._forceHitArea=null,this.hitArea=new e.Rectangle(0,0,this.worldWidth,this.worldHeight))}drag(t){return this.plugins.add("drag",new r(this,t)),this}clamp(t){return this.plugins.add("clamp",new c(this,t)),this}decelerate(t){return this.plugins.add("decelerate",new m(this,t)),this}bounce(t){return this.plugins.add("bounce",new v(this,t)),this}pinch(t){return this.plugins.add("pinch",new p(this,t)),this}snap(t,e,i){return this.plugins.add("snap",new b(this,t,e,i)),this}follow(t,e){return this.plugins.add("follow",new O(this,t,e)),this}wheel(t){return this.plugins.add("wheel",new z(this,t)),this}animate(t){return this.plugins.add("animate",new X(this,t)),this}clampZoom(t){return this.plugins.add("clamp-zoom",new u(this,t)),this}mouseEdges(t){return this.plugins.add("mouse-edges",new I(this,t)),this}get pause(){return this._pause}set pause(t){this._pause=t,this.lastViewport=null,this.moving=!1,this.zooming=!1,t&&this.input.pause()}ensureVisible(t,e,i,s,n){n&&(i>this.worldScreenWidth||s>this.worldScreenHeight)&&(this.fit(!0,i,s),this.emit("zoomed",{viewport:this,type:"ensureVisible"}));let h=!1;tthis.right&&(this.right=t+i,h=!0),ethis.bottom&&(this.bottom=e+s,h=!0),h&&this.emit("moved",{viewport:this,type:"ensureVisible"})}}t.Plugin=h,t.Viewport=A,Object.defineProperty(t,"__esModule",{value:!0})})); -},{"@pixi/constants":16,"@pixi/core":17,"@pixi/math":29,"@pixi/sprite":42,"@pixi/utils":47}],42:[function(require,module,exports){ +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"pixi.js":49}],49:[function(require,module,exports){ /*! - * @pixi/sprite - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC + * pixi.js - v5.3.3 + * Compiled Tue, 04 Aug 2020 16:23:09 UTC * - * @pixi/sprite is licensed under the MIT License. + * pixi.js is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); -var math = require('@pixi/math'); +require('@pixi/polyfill'); var utils = require('@pixi/utils'); +var accessibility = require('@pixi/accessibility'); +var interaction = require('@pixi/interaction'); +var app = require('@pixi/app'); var core = require('@pixi/core'); +var extract = require('@pixi/extract'); +var loaders = require('@pixi/loaders'); +var particles = require('@pixi/particles'); +var prepare = require('@pixi/prepare'); +var spritesheet = require('@pixi/spritesheet'); +var spriteTiling = require('@pixi/sprite-tiling'); +var textBitmap = require('@pixi/text-bitmap'); +var ticker = require('@pixi/ticker'); +var filterAlpha = require('@pixi/filter-alpha'); +var filterBlur = require('@pixi/filter-blur'); +var filterColorMatrix = require('@pixi/filter-color-matrix'); +var filterDisplacement = require('@pixi/filter-displacement'); +var filterFxaa = require('@pixi/filter-fxaa'); +var filterNoise = require('@pixi/filter-noise'); +require('@pixi/mixin-cache-as-bitmap'); +require('@pixi/mixin-get-child-by-name'); +require('@pixi/mixin-get-global-position'); var constants = require('@pixi/constants'); var display = require('@pixi/display'); +var graphics = require('@pixi/graphics'); +var math = require('@pixi/math'); +var mesh = require('@pixi/mesh'); +var meshExtras = require('@pixi/mesh-extras'); +var runner = require('@pixi/runner'); +var sprite = require('@pixi/sprite'); +var spriteAnimated = require('@pixi/sprite-animated'); +var text = require('@pixi/text'); var settings = require('@pixi/settings'); -var tempPoint = new math.Point(); -var indices = new Uint16Array([0, 1, 2, 0, 2, 3]); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +var v5 = '5.0.0'; /** - * The Sprite object is the base for all textured objects that are rendered to the screen -* - * A sprite can be created directly from an image like this: - * - * ```js - * let sprite = PIXI.Sprite.from('assets/image.png'); - * ``` - * - * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}, - * as swapping base textures when rendering to the screen is inefficient. - * - * ```js - * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); - * - * function setup() { - * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; - * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); - * ... - * } - * ``` - * - * @class - * @extends PIXI.Container + * Deprecations (backward compatibilities) are automatically applied for browser bundles + * in the UMD module format. If using Webpack or Rollup, you'll need to apply these + * deprecations manually by doing something like this: + * @example + * import * as PIXI from 'pixi.js'; + * PIXI.useDeprecated(); // MUST be bound to namespace * @memberof PIXI + * @function useDeprecated */ -var Sprite = /*@__PURE__*/(function (Container) { - function Sprite(texture) - { - Container.call(this); - +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function useDeprecated() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + var PIXI = this; + Object.defineProperties(PIXI, { /** - * The anchor point defines the normalized coordinates - * in the texture that map to the position of this - * sprite. - * - * By default, this is `(0,0)` (or `texture.defaultAnchor` - * if you have modified that), which means the position - * `(x,y)` of this `Sprite` will be the top-left corner. - * - * Note: Updating `texture.defaultAnchor` after - * constructing a `Sprite` does _not_ update its anchor. - * - * {@link https://docs.cocos2d-x.org/cocos2d-x/en/sprites/manipulation.html} - * - * @default `texture.defaultAnchor` - * @member {PIXI.ObservablePoint} - * @private + * @constant {RegExp|string} SVG_SIZE + * @memberof PIXI + * @see PIXI.resources.SVGResource.SVG_SIZE + * @deprecated since 5.0.0 */ - this._anchor = new math.ObservablePoint( - this._onAnchorUpdate, - this, - (texture ? texture.defaultAnchor.x : 0), - (texture ? texture.defaultAnchor.y : 0) - ); - + SVG_SIZE: { + get: function () { + utils.deprecation(v5, 'PIXI.utils.SVG_SIZE property has moved to PIXI.resources.SVGResource.SVG_SIZE'); + return PIXI.SVGResource.SVG_SIZE; + }, + }, /** - * The texture that the sprite is using - * - * @private - * @member {PIXI.Texture} + * @class PIXI.TransformStatic + * @deprecated since 5.0.0 + * @see PIXI.Transform */ - this._texture = null; - + TransformStatic: { + get: function () { + utils.deprecation(v5, 'PIXI.TransformStatic class has been removed, use PIXI.Transform'); + return PIXI.Transform; + }, + }, /** - * The width of the sprite (this is initially set by the texture) - * - * @private - * @member {number} + * @class PIXI.TransformBase + * @deprecated since 5.0.0 + * @see PIXI.Transform */ - this._width = 0; - + TransformBase: { + get: function () { + utils.deprecation(v5, 'PIXI.TransformBase class has been removed, use PIXI.Transform'); + return PIXI.Transform; + }, + }, /** - * The height of the sprite (this is initially set by the texture) + * Constants that specify the transform type. * - * @private - * @member {number} + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @enum {number} + * @deprecated since 5.0.0 + * @property {number} STATIC + * @property {number} DYNAMIC */ - this._height = 0; - + TRANSFORM_MODE: { + get: function () { + utils.deprecation(v5, 'PIXI.TRANSFORM_MODE property has been removed'); + return { STATIC: 0, DYNAMIC: 1 }; + }, + }, /** - * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. - * - * @private - * @member {number} - * @default 0xFFFFFF + * @class PIXI.WebGLRenderer + * @see PIXI.Renderer + * @deprecated since 5.0.0 */ - this._tint = null; - this._tintRGB = null; - this.tint = 0xFFFFFF; - + WebGLRenderer: { + get: function () { + utils.deprecation(v5, 'PIXI.WebGLRenderer class has moved to PIXI.Renderer'); + return PIXI.Renderer; + }, + }, /** - * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - * @see PIXI.BLEND_MODES + * @class PIXI.CanvasRenderTarget + * @see PIXI.utils.CanvasRenderTarget + * @deprecated since 5.0.0 */ - this.blendMode = constants.BLEND_MODES.NORMAL; - + CanvasRenderTarget: { + get: function () { + utils.deprecation(v5, 'PIXI.CanvasRenderTarget class has moved to PIXI.utils.CanvasRenderTarget'); + return PIXI.utils.CanvasRenderTarget; + }, + }, /** - * The shader that will be used to render the sprite. Set to null to remove a current shader. - * - * @member {PIXI.Filter|PIXI.Shader} + * @memberof PIXI + * @name loader + * @type {PIXI.Loader} + * @see PIXI.Loader.shared + * @deprecated since 5.0.0 */ - this.shader = null; - + loader: { + get: function () { + utils.deprecation(v5, 'PIXI.loader instance has moved to PIXI.Loader.shared'); + return PIXI.Loader.shared; + }, + }, /** - * Cached tint value so we can tell when the tint is changed. - * Value is used for 2d CanvasRenderer. - * - * @protected - * @member {number} - * @default 0xFFFFFF + * @class PIXI.FilterManager + * @see PIXI.systems.FilterSystem + * @deprecated since 5.0.0 */ - this._cachedTint = 0xFFFFFF; - + FilterManager: { + get: function () { + utils.deprecation(v5, 'PIXI.FilterManager class has moved to PIXI.systems.FilterSystem'); + return PIXI.systems.FilterSystem; + }, + }, /** - * this is used to store the uvs data of the sprite, assigned at the same time - * as the vertexData in calculateVertices() - * - * @private - * @member {Float32Array} + * @namespace PIXI.CanvasTinter + * @see PIXI.canvasUtils + * @deprecated since 5.2.0 */ - this.uvs = null; - - // call texture setter - this.texture = texture || core.Texture.EMPTY; - + CanvasTinter: { + get: function () { + utils.deprecation('5.2.0', 'PIXI.CanvasTinter namespace has moved to PIXI.canvasUtils'); + return PIXI.canvasUtils; + }, + }, /** - * this is used to store the vertex data of the sprite (basically a quad) - * - * @private - * @member {Float32Array} + * @namespace PIXI.GroupD8 + * @see PIXI.groupD8 + * @deprecated since 5.2.0 */ - this.vertexData = new Float32Array(8); - + GroupD8: { + get: function () { + utils.deprecation('5.2.0', 'PIXI.GroupD8 namespace has moved to PIXI.groupD8'); + return PIXI.groupD8; + }, + }, + }); + /** + * @namespace PIXI.accessibility + * @see PIXI + * @deprecated since 5.3.0 + */ + PIXI.accessibility = {}; + Object.defineProperties(PIXI.accessibility, { /** - * This is used to calculate the bounds of the object IF it is a trimmed sprite - * - * @private - * @member {Float32Array} + * @class PIXI.accessibility.AccessibilityManager + * @deprecated since 5.3.0 + * @see PIXI.AccessibilityManager */ - this.vertexTrimmedData = null; - - this._transformID = -1; - this._textureID = -1; - - this._transformTrimmedID = -1; - this._textureTrimmedID = -1; - - // Batchable stuff.. - // TODO could make this a mixin? - this.indices = indices; - this.size = 4; - this.start = 0; - + AccessibilityManager: { + get: function () { + utils.deprecation('5.3.0', 'PIXI.accessibility.AccessibilityManager moved to PIXI.AccessibilityManager'); + return PIXI.AccessibilityManager; + }, + }, + }); + /** + * @namespace PIXI.interaction + * @see PIXI + * @deprecated since 5.3.0 + */ + PIXI.interaction = {}; + Object.defineProperties(PIXI.interaction, { /** - * Plugin that is responsible for rendering this element. - * Allows to customize the rendering process without overriding '_render' & '_renderCanvas' methods. - * - * @member {string} - * @default 'batch' + * @class PIXI.interaction.InteractionManager + * @deprecated since 5.3.0 + * @see PIXI.InteractionManager */ - this.pluginName = 'batch'; - + InteractionManager: { + get: function () { + utils.deprecation('5.3.0', 'PIXI.interaction.InteractionManager moved to PIXI.InteractionManager'); + return PIXI.InteractionManager; + }, + }, /** - * used to fast check if a sprite is.. a sprite! - * @member {boolean} + * @class PIXI.interaction.InteractionData + * @deprecated since 5.3.0 + * @see PIXI.InteractionData */ - this.isSprite = true; - + InteractionData: { + get: function () { + utils.deprecation('5.3.0', 'PIXI.interaction.InteractionData moved to PIXI.InteractionData'); + return PIXI.InteractionData; + }, + }, /** - * Internal roundPixels field - * - * @member {boolean} - * @private + * @class PIXI.interaction.InteractionEvent + * @deprecated since 5.3.0 + * @see PIXI.InteractionEvent */ - this._roundPixels = settings.settings.ROUND_PIXELS; - } - - if ( Container ) Sprite.__proto__ = Container; - Sprite.prototype = Object.create( Container && Container.prototype ); - Sprite.prototype.constructor = Sprite; - - var prototypeAccessors = { roundPixels: { configurable: true },width: { configurable: true },height: { configurable: true },anchor: { configurable: true },tint: { configurable: true },texture: { configurable: true } }; - + InteractionEvent: { + get: function () { + utils.deprecation('5.3.0', 'PIXI.interaction.InteractionEvent moved to PIXI.InteractionEvent'); + return PIXI.InteractionEvent; + }, + }, + }); /** - * When the texture is updated, this event will fire to update the scale and frame - * - * @private + * @namespace PIXI.prepare + * @see PIXI + * @deprecated since 5.2.1 */ - Sprite.prototype._onTextureUpdate = function _onTextureUpdate () - { - this._textureID = -1; - this._textureTrimmedID = -1; - this._cachedTint = 0xFFFFFF; - - // so if _width is 0 then width was not set.. - if (this._width) - { - this.scale.x = utils.sign(this.scale.x) * this._width / this._texture.orig.width; - } - - if (this._height) - { - this.scale.y = utils.sign(this.scale.y) * this._height / this._texture.orig.height; - } - }; - + PIXI.prepare = {}; + Object.defineProperties(PIXI.prepare, { + /** + * @class PIXI.prepare.BasePrepare + * @deprecated since 5.2.1 + * @see PIXI.BasePrepare + */ + BasePrepare: { + get: function () { + utils.deprecation('5.2.1', 'PIXI.prepare.BasePrepare moved to PIXI.BasePrepare'); + return PIXI.BasePrepare; + }, + }, + /** + * @class PIXI.prepare.Prepare + * @deprecated since 5.2.1 + * @see PIXI.Prepare + */ + Prepare: { + get: function () { + utils.deprecation('5.2.1', 'PIXI.prepare.Prepare moved to PIXI.Prepare'); + return PIXI.Prepare; + }, + }, + /** + * @class PIXI.prepare.CanvasPrepare + * @deprecated since 5.2.1 + * @see PIXI.CanvasPrepare + */ + CanvasPrepare: { + get: function () { + utils.deprecation('5.2.1', 'PIXI.prepare.CanvasPrepare moved to PIXI.CanvasPrepare'); + return PIXI.CanvasPrepare; + }, + }, + }); /** - * Called when the anchor position updates. - * - * @private + * @namespace PIXI.extract + * @see PIXI + * @deprecated since 5.2.1 */ - Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate () - { - this._transformID = -1; - this._transformTrimmedID = -1; - }; - + PIXI.extract = {}; + Object.defineProperties(PIXI.extract, { + /** + * @class PIXI.extract.Extract + * @deprecated since 5.2.1 + * @see PIXI.Extract + */ + Extract: { + get: function () { + utils.deprecation('5.2.1', 'PIXI.extract.Extract moved to PIXI.Extract'); + return PIXI.Extract; + }, + }, + /** + * @class PIXI.extract.CanvasExtract + * @deprecated since 5.2.1 + * @see PIXI.CanvasExtract + */ + CanvasExtract: { + get: function () { + utils.deprecation('5.2.1', 'PIXI.extract.CanvasExtract moved to PIXI.CanvasExtract'); + return PIXI.CanvasExtract; + }, + }, + }); /** - * calculates worldTransform * vertices, store it in vertexData + * This namespace has been removed. All classes previous nested + * under this namespace have been moved to the top-level `PIXI` object. + * @namespace PIXI.extras + * @deprecated since 5.0.0 */ - Sprite.prototype.calculateVertices = function calculateVertices () - { - var texture = this._texture; - - if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) - { - return; - } - - // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` - if (this._textureID !== texture._updateID) - { - this.uvs = this._texture._uvs.uvsFloat32; - } - - this._transformID = this.transform._worldID; - this._textureID = texture._updateID; - - // set the vertex data - - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var vertexData = this.vertexData; - var trim = texture.trim; - var orig = texture.orig; - var anchor = this._anchor; - - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - - if (trim) - { - // if the sprite is trimmed and is not a tilingsprite then we need to add the extra - // space before transforming the sprite coords. - w1 = trim.x - (anchor._x * orig.width); - w0 = w1 + trim.width; - - h1 = trim.y - (anchor._y * orig.height); - h0 = h1 + trim.height; - } - else - { - w1 = -anchor._x * orig.width; - w0 = w1 + orig.width; - - h1 = -anchor._y * orig.height; - h0 = h1 + orig.height; - } - - // xy - vertexData[0] = (a * w1) + (c * h1) + tx; - vertexData[1] = (d * h1) + (b * w1) + ty; - - // xy - vertexData[2] = (a * w0) + (c * h1) + tx; - vertexData[3] = (d * h1) + (b * w0) + ty; - - // xy - vertexData[4] = (a * w0) + (c * h0) + tx; - vertexData[5] = (d * h0) + (b * w0) + ty; - - // xy - vertexData[6] = (a * w1) + (c * h0) + tx; - vertexData[7] = (d * h0) + (b * w1) + ty; - - if (this._roundPixels) - { - for (var i = 0; i < 8; i++) - { - vertexData[i] = Math.round(vertexData[i]); - } - } - }; - + PIXI.extras = {}; + Object.defineProperties(PIXI.extras, { + /** + * @class PIXI.extras.TilingSprite + * @see PIXI.TilingSprite + * @deprecated since 5.0.0 + */ + TilingSprite: { + get: function () { + utils.deprecation(v5, 'PIXI.extras.TilingSprite class has moved to PIXI.TilingSprite'); + return PIXI.TilingSprite; + }, + }, + /** + * @class PIXI.extras.TilingSpriteRenderer + * @see PIXI.TilingSpriteRenderer + * @deprecated since 5.0.0 + */ + TilingSpriteRenderer: { + get: function () { + utils.deprecation(v5, 'PIXI.extras.TilingSpriteRenderer class has moved to PIXI.TilingSpriteRenderer'); + return PIXI.TilingSpriteRenderer; + }, + }, + /** + * @class PIXI.extras.AnimatedSprite + * @see PIXI.AnimatedSprite + * @deprecated since 5.0.0 + */ + AnimatedSprite: { + get: function () { + utils.deprecation(v5, 'PIXI.extras.AnimatedSprite class has moved to PIXI.AnimatedSprite'); + return PIXI.AnimatedSprite; + }, + }, + /** + * @class PIXI.extras.BitmapText + * @see PIXI.BitmapText + * @deprecated since 5.0.0 + */ + BitmapText: { + get: function () { + utils.deprecation(v5, 'PIXI.extras.BitmapText class has moved to PIXI.BitmapText'); + return PIXI.BitmapText; + }, + }, + }); /** - * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData - * This is used to ensure that the true width and height of a trimmed texture is respected + * @static + * @method PIXI.TilingSprite.fromFrame + * @deprecated since 5.3.0 + * @see PIXI.TilingSprite.from */ - Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices () - { - if (!this.vertexTrimmedData) - { - this.vertexTrimmedData = new Float32Array(8); - } - else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) - { - return; - } - - this._transformTrimmedID = this.transform._worldID; - this._textureTrimmedID = this._texture._updateID; - - // lets do some special trim code! - var texture = this._texture; - var vertexData = this.vertexTrimmedData; - var orig = texture.orig; - var anchor = this._anchor; - - // lets calculate the new untrimmed bounds.. - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - - var w1 = -anchor._x * orig.width; - var w0 = w1 + orig.width; - - var h1 = -anchor._y * orig.height; - var h0 = h1 + orig.height; - - // xy - vertexData[0] = (a * w1) + (c * h1) + tx; - vertexData[1] = (d * h1) + (b * w1) + ty; - - // xy - vertexData[2] = (a * w0) + (c * h1) + tx; - vertexData[3] = (d * h1) + (b * w0) + ty; - - // xy - vertexData[4] = (a * w0) + (c * h0) + tx; - vertexData[5] = (d * h0) + (b * w0) + ty; - - // xy - vertexData[6] = (a * w1) + (c * h0) + tx; - vertexData[7] = (d * h0) + (b * w1) + ty; - }; - - /** - * - * Renders the object using the WebGL renderer - * - * @protected - * @param {PIXI.Renderer} renderer - The webgl renderer to use. - */ - Sprite.prototype._render = function _render (renderer) - { - this.calculateVertices(); - - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); + PIXI.TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + utils.deprecation('5.3.0', 'TilingSprite.fromFrame is deprecated, use TilingSprite.from'); + return PIXI.TilingSprite.from(frameId, { width: width, height: height }); }; - /** - * Updates the bounds of the sprite. - * - * @protected + * @static + * @method PIXI.TilingSprite.fromImage + * @deprecated since 5.3.0 + * @see PIXI.TilingSprite.from */ - Sprite.prototype._calculateBounds = function _calculateBounds () - { - var trim = this._texture.trim; - var orig = this._texture.orig; - - // First lets check to see if the current texture has a trim.. - if (!trim || (trim.width === orig.width && trim.height === orig.height)) - { - // no trim! lets use the usual calculations.. - this.calculateVertices(); - this._bounds.addQuad(this.vertexData); - } - else - { - // lets calculate a special trimmed bounds... - this.calculateTrimmedVertices(); - this._bounds.addQuad(this.vertexTrimmedData); + PIXI.TilingSprite.fromImage = function fromImage(imageId, width, height, options) { + if (options === void 0) { options = {}; } + utils.deprecation('5.3.0', 'TilingSprite.fromImage is deprecated, use TilingSprite.from'); + // Fallback support for crossorigin, scaleMode parameters + if (options && typeof options !== 'object') { + options = { + // eslint-disable-next-line prefer-rest-params + scaleMode: arguments[4], + resourceOptions: { + // eslint-disable-next-line prefer-rest-params + crossorigin: arguments[3], + }, + }; } + options.width = width; + options.height = height; + return PIXI.TilingSprite.from(imageId, options); }; - + Object.defineProperties(PIXI.utils, { + /** + * @function PIXI.utils.getSvgSize + * @see PIXI.resources.SVGResource.getSize + * @deprecated since 5.0.0 + */ + getSvgSize: { + get: function () { + utils.deprecation(v5, 'PIXI.utils.getSvgSize function has moved to PIXI.resources.SVGResource.getSize'); + return PIXI.resources.SVGResource.getSize; + }, + }, + }); /** - * Gets the local bounds of the sprite object. - * - * @param {PIXI.Rectangle} [rect] - The output rectangle. - * @return {PIXI.Rectangle} The bounds. + * All classes on this namespace have moved to the high-level `PIXI` object. + * @namespace PIXI.mesh + * @deprecated since 5.0.0 */ - Sprite.prototype.getLocalBounds = function getLocalBounds (rect) - { - // we can do a fast local bounds if the sprite has no children! - if (this.children.length === 0) - { - this._bounds.minX = this._texture.orig.width * -this._anchor._x; - this._bounds.minY = this._texture.orig.height * -this._anchor._y; - this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); - this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y); - - if (!rect) - { - if (!this._localBoundsRect) - { - this._localBoundsRect = new math.Rectangle(); - } - - rect = this._localBoundsRect; - } - - return this._bounds.getRectangle(rect); - } - - return Container.prototype.getLocalBounds.call(this, rect); - }; - - /** - * Tests if a point is inside this sprite - * - * @param {PIXI.Point} point - the point to test - * @return {boolean} the result of the test - */ - Sprite.prototype.containsPoint = function containsPoint (point) - { - this.worldTransform.applyInverse(point, tempPoint); - - var width = this._texture.orig.width; - var height = this._texture.orig.height; - var x1 = -width * this.anchor.x; - var y1 = 0; - - if (tempPoint.x >= x1 && tempPoint.x < x1 + width) - { - y1 = -height * this.anchor.y; - - if (tempPoint.y >= y1 && tempPoint.y < y1 + height) - { - return true; - } - } - - return false; - }; - - /** - * Destroys this sprite and optionally its texture and children - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well - */ - Sprite.prototype.destroy = function destroy (options) - { - Container.prototype.destroy.call(this, options); - - this._texture.off('update', this._onTextureUpdate, this); - - this._anchor = null; - - var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; - - if (destroyTexture) - { - var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; - - this._texture.destroy(!!destroyBaseTexture); - } - - this._texture = null; - this.shader = null; - }; - - // some helper functions.. - - /** - * Helper function that creates a new sprite based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * - * @static - * @param {number|string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from - * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. - * @return {PIXI.Sprite} The newly created sprite - */ - Sprite.from = function from (source, options) - { - var texture = (source instanceof core.Texture) - ? source - : core.Texture.from(source, options); - - return new Sprite(texture); - }; - - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} - * - * @member {boolean} - * @default false - */ - prototypeAccessors.roundPixels.set = function (value) - { - if (this._roundPixels !== value) - { - this._transformID = -1; - } - this._roundPixels = value; - }; - - prototypeAccessors.roundPixels.get = function () - { - return this._roundPixels; - }; - - /** - * The width of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - prototypeAccessors.width.get = function () - { - return Math.abs(this.scale.x) * this._texture.orig.width; - }; - - prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc - { - var s = utils.sign(this.scale.x) || 1; - - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - }; - + PIXI.mesh = {}; + Object.defineProperties(PIXI.mesh, { + /** + * @class PIXI.mesh.Mesh + * @see PIXI.SimpleMesh + * @deprecated since 5.0.0 + */ + Mesh: { + get: function () { + utils.deprecation(v5, 'PIXI.mesh.Mesh class has moved to PIXI.SimpleMesh'); + return PIXI.SimpleMesh; + }, + }, + /** + * @class PIXI.mesh.NineSlicePlane + * @see PIXI.NineSlicePlane + * @deprecated since 5.0.0 + */ + NineSlicePlane: { + get: function () { + utils.deprecation(v5, 'PIXI.mesh.NineSlicePlane class has moved to PIXI.NineSlicePlane'); + return PIXI.NineSlicePlane; + }, + }, + /** + * @class PIXI.mesh.Plane + * @see PIXI.SimplePlane + * @deprecated since 5.0.0 + */ + Plane: { + get: function () { + utils.deprecation(v5, 'PIXI.mesh.Plane class has moved to PIXI.SimplePlane'); + return PIXI.SimplePlane; + }, + }, + /** + * @class PIXI.mesh.Rope + * @see PIXI.SimpleRope + * @deprecated since 5.0.0 + */ + Rope: { + get: function () { + utils.deprecation(v5, 'PIXI.mesh.Rope class has moved to PIXI.SimpleRope'); + return PIXI.SimpleRope; + }, + }, + /** + * @class PIXI.mesh.RawMesh + * @see PIXI.Mesh + * @deprecated since 5.0.0 + */ + RawMesh: { + get: function () { + utils.deprecation(v5, 'PIXI.mesh.RawMesh class has moved to PIXI.Mesh'); + return PIXI.Mesh; + }, + }, + /** + * @class PIXI.mesh.CanvasMeshRenderer + * @see PIXI.CanvasMeshRenderer + * @deprecated since 5.0.0 + */ + CanvasMeshRenderer: { + get: function () { + utils.deprecation(v5, 'PIXI.mesh.CanvasMeshRenderer class has moved to PIXI.CanvasMeshRenderer'); + return PIXI.CanvasMeshRenderer; + }, + }, + /** + * @class PIXI.mesh.MeshRenderer + * @see PIXI.MeshRenderer + * @deprecated since 5.0.0 + */ + MeshRenderer: { + get: function () { + utils.deprecation(v5, 'PIXI.mesh.MeshRenderer class has moved to PIXI.MeshRenderer'); + return PIXI.MeshRenderer; + }, + }, + }); /** - * The height of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} + * This namespace has been removed and items have been moved to + * the top-level `PIXI` object. + * @namespace PIXI.particles + * @deprecated since 5.0.0 */ - prototypeAccessors.height.get = function () - { - return Math.abs(this.scale.y) * this._texture.orig.height; - }; - - prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc - { - var s = utils.sign(this.scale.y) || 1; - - this.scale.y = s * value / this._texture.orig.height; - this._height = value; - }; - + PIXI.particles = {}; + Object.defineProperties(PIXI.particles, { + /** + * @class PIXI.particles.ParticleContainer + * @deprecated since 5.0.0 + * @see PIXI.ParticleContainer + */ + ParticleContainer: { + get: function () { + utils.deprecation(v5, 'PIXI.particles.ParticleContainer class has moved to PIXI.ParticleContainer'); + return PIXI.ParticleContainer; + }, + }, + /** + * @class PIXI.particles.ParticleRenderer + * @deprecated since 5.0.0 + * @see PIXI.ParticleRenderer + */ + ParticleRenderer: { + get: function () { + utils.deprecation(v5, 'PIXI.particles.ParticleRenderer class has moved to PIXI.ParticleRenderer'); + return PIXI.ParticleRenderer; + }, + }, + }); /** - * The anchor sets the origin point of the text. The default value is taken from the {@link PIXI.Texture|Texture} - * and passed to the constructor. - * - * The default is `(0,0)`, this means the text's origin is the top left. - * - * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. - * - * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. - * - * If you pass only single parameter, it will set both x and y to the same value as shown in the example below. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5). - * - * @member {PIXI.ObservablePoint} + * This namespace has been removed and items have been moved to + * the top-level `PIXI` object. + * @namespace PIXI.ticker + * @deprecated since 5.0.0 */ - prototypeAccessors.anchor.get = function () - { - return this._anchor; - }; - - prototypeAccessors.anchor.set = function (value) // eslint-disable-line require-jsdoc - { - this._anchor.copyFrom(value); - }; - + PIXI.ticker = {}; + Object.defineProperties(PIXI.ticker, { + /** + * @class PIXI.ticker.Ticker + * @deprecated since 5.0.0 + * @see PIXI.Ticker + */ + Ticker: { + get: function () { + utils.deprecation(v5, 'PIXI.ticker.Ticker class has moved to PIXI.Ticker'); + return PIXI.Ticker; + }, + }, + /** + * @name PIXI.ticker.shared + * @type {PIXI.Ticker} + * @deprecated since 5.0.0 + * @see PIXI.Ticker.shared + */ + shared: { + get: function () { + utils.deprecation(v5, 'PIXI.ticker.shared instance has moved to PIXI.Ticker.shared'); + return PIXI.Ticker.shared; + }, + }, + }); /** - * The tint applied to the sprite. This is a hex value. - * A value of 0xFFFFFF will remove any tint effect. - * - * @member {number} - * @default 0xFFFFFF + * All classes on this namespace have moved to the high-level `PIXI` object. + * @namespace PIXI.loaders + * @deprecated since 5.0.0 */ - prototypeAccessors.tint.get = function () - { - return this._tint; - }; - - prototypeAccessors.tint.set = function (value) // eslint-disable-line require-jsdoc - { - this._tint = value; - this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); - }; - + PIXI.loaders = {}; + Object.defineProperties(PIXI.loaders, { + /** + * @class PIXI.loaders.Loader + * @see PIXI.Loader + * @deprecated since 5.0.0 + */ + Loader: { + get: function () { + utils.deprecation(v5, 'PIXI.loaders.Loader class has moved to PIXI.Loader'); + return PIXI.Loader; + }, + }, + /** + * @class PIXI.loaders.Resource + * @see PIXI.LoaderResource + * @deprecated since 5.0.0 + */ + Resource: { + get: function () { + utils.deprecation(v5, 'PIXI.loaders.Resource class has moved to PIXI.LoaderResource'); + return PIXI.LoaderResource; + }, + }, + /** + * @function PIXI.loaders.bitmapFontParser + * @see PIXI.BitmapFontLoader.use + * @deprecated since 5.0.0 + */ + bitmapFontParser: { + get: function () { + utils.deprecation(v5, 'PIXI.loaders.bitmapFontParser function has moved to PIXI.BitmapFontLoader.use'); + return PIXI.BitmapFontLoader.use; + }, + }, + /** + * @function PIXI.loaders.parseBitmapFontData + * @deprecated since 5.0.0 + */ + parseBitmapFontData: { + get: function () { + utils.deprecation(v5, 'PIXI.loaders.parseBitmapFontData function has removed'); + }, + }, + /** + * @function PIXI.loaders.spritesheetParser + * @see PIXI.SpritesheetLoader.use + * @deprecated since 5.0.0 + */ + spritesheetParser: { + get: function () { + utils.deprecation(v5, 'PIXI.loaders.spritesheetParser function has moved to PIXI.SpritesheetLoader.use'); + return PIXI.SpritesheetLoader.use; + }, + }, + /** + * @function PIXI.loaders.getResourcePath + * @see PIXI.SpritesheetLoader.getResourcePath + * @deprecated since 5.0.0 + */ + getResourcePath: { + get: function () { + utils.deprecation(v5, 'PIXI.loaders.getResourcePath property has moved to PIXI.SpritesheetLoader.getResourcePath'); + return PIXI.SpritesheetLoader.getResourcePath; + }, + }, + }); /** - * The texture that the sprite is using - * - * @member {PIXI.Texture} + * @function PIXI.loaders.Loader.addPixiMiddleware + * @see PIXI.Loader.registerPlugin + * @deprecated since 5.0.0 + * @param {function} middleware */ - prototypeAccessors.texture.get = function () - { - return this._texture; + PIXI.Loader.addPixiMiddleware = function addPixiMiddleware(middleware) { + utils.deprecation(v5, 'PIXI.loaders.Loader.addPixiMiddleware function is deprecated, use PIXI.loaders.Loader.registerPlugin'); + return PIXI.loaders.Loader.registerPlugin({ use: middleware() }); }; - - prototypeAccessors.texture.set = function (value) // eslint-disable-line require-jsdoc - { - if (this._texture === value) - { - return; - } - - if (this._texture) - { - this._texture.off('update', this._onTextureUpdate, this); - } - - this._texture = value || core.Texture.EMPTY; - this._cachedTint = 0xFFFFFF; - - this._textureID = -1; - this._textureTrimmedID = -1; - - if (value) - { - // wait for the texture to load - if (value.baseTexture.valid) - { - this._onTextureUpdate(); - } - else - { - value.once('update', this._onTextureUpdate, this); - } - } + // convenience for converting event name to signal name + var eventToSignal = function (event) { + return "on" + event.charAt(0).toUpperCase() + event.slice(1); }; - - Object.defineProperties( Sprite.prototype, prototypeAccessors ); - - return Sprite; -}(display.Container)); - -exports.Sprite = Sprite; - - -},{"@pixi/constants":16,"@pixi/core":17,"@pixi/display":18,"@pixi/math":29,"@pixi/settings":39,"@pixi/utils":47}],43:[function(require,module,exports){ -/*! - * @pixi/spritesheet - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/spritesheet is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var math = require('@pixi/math'); -var core = require('@pixi/core'); -var utils = require('@pixi/utils'); -var loaders = require('@pixi/loaders'); - -/** - * Utility class for maintaining reference to a collection - * of Textures on a single Spritesheet. - * - * To access a sprite sheet from your code pass its JSON data file to Pixi's loader: - * - * ```js - * PIXI.Loader.shared.add("images/spritesheet.json").load(setup); - * - * function setup() { - * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet; - * ... - * } - * ``` - * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. - * - * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, - * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. - * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only - * supported by TexturePacker. - * - * @class - * @memberof PIXI - */ -var Spritesheet = function Spritesheet(baseTexture, data, resolutionFilename) -{ - if ( resolutionFilename === void 0 ) resolutionFilename = null; - - /** - * Reference to ths source texture - * @type {PIXI.BaseTexture} - */ - this.baseTexture = baseTexture; - - /** - * A map containing all textures of the sprite sheet. - * Can be used to create a {@link PIXI.Sprite|Sprite}: - * ```js - * new PIXI.Sprite(sheet.textures["image.png"]); - * ``` - * @member {Object} - */ - this.textures = {}; - - /** - * A map containing the textures for each animation. - * Can be used to create an {@link PIXI.AnimatedSprite|AnimatedSprite}: - * ```js - * new PIXI.AnimatedSprite(sheet.animations["anim_name"]) - * ``` - * @member {Object} - */ - this.animations = {}; - - /** - * Reference to the original JSON data. - * @type {Object} - */ - this.data = data; - - /** - * The resolution of the spritesheet. - * @type {number} - */ - this.resolution = this._updateResolution( - resolutionFilename - || (this.baseTexture.resource ? this.baseTexture.resource.url : null) - ); - - /** - * Map of spritesheet frames. - * @type {Object} - * @private - */ - this._frames = this.data.frames; - - /** - * Collection of frame names. - * @type {string[]} - * @private - */ - this._frameKeys = Object.keys(this._frames); - - /** - * Current batch index being processed. - * @type {number} - * @private - */ - this._batchIndex = 0; - + Object.assign(PIXI.Loader.prototype, { + /** + * Use the corresponding signal, e.g., event `start`` is signal `onStart`. + * @method PIXI.Loader#on + * @deprecated since 5.0.0 + */ + on: function (event) { + var signal = eventToSignal(event); + utils.deprecation(v5, "PIXI.Loader#on is completely deprecated, use PIXI.Loader#" + signal + ".add"); + }, + /** + * Use the corresponding signal, e.g., event `start`` is signal `onStart`. + * @method PIXI.Loader#once + * @deprecated since 5.0.0 + */ + once: function (event) { + var signal = eventToSignal(event); + utils.deprecation(v5, "PIXI.Loader#once is completely deprecated, use PIXI.Loader#" + signal + ".once"); + }, + /** + * Use the corresponding signal, e.g., event `start`` is signal `onStart`. + * @method PIXI.Loader#off + * @deprecated since 5.0.0 + */ + off: function (event) { + var signal = eventToSignal(event); + utils.deprecation(v5, "PIXI.Loader#off is completely deprecated, use PIXI.Loader#" + signal + ".detach"); + }, + }); /** - * Callback when parse is completed. - * @type {Function} - * @private + * @class PIXI.extract.WebGLExtract + * @deprecated since 5.0.0 + * @see PIXI.Extract */ - this._callback = null; -}; - -var staticAccessors = { BATCH_SIZE: { configurable: true } }; - -/** - * Generate the resolution from the filename or fallback - * to the meta.scale field of the JSON data. - * - * @private - * @param {string} resolutionFilename - The filename to use for resolving - * the default resolution. - * @return {number} Resolution to use for spritesheet. - */ -staticAccessors.BATCH_SIZE.get = function () -{ - return 1000; -}; - -Spritesheet.prototype._updateResolution = function _updateResolution (resolutionFilename) -{ - var scale = this.data.meta.scale; - - // Use a defaultValue of `null` to check if a url-based resolution is set - var resolution = utils.getResolutionOfUrl(resolutionFilename, null); - - // No resolution found via URL - if (resolution === null) - { - // Use the scale value or default to 1 - resolution = scale !== undefined ? parseFloat(scale) : 1; - } - - // For non-1 resolutions, update baseTexture - if (resolution !== 1) - { - this.baseTexture.setResolution(resolution); - } - - return resolution; -}; - -/** - * Parser spritesheet from loaded data. This is done asynchronously - * to prevent creating too many Texture within a single process. - * - * @param {Function} callback - Callback when complete returns - * a map of the Textures for this spritesheet. - */ -Spritesheet.prototype.parse = function parse (callback) -{ - this._batchIndex = 0; - this._callback = callback; - - if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) - { - this._processFrames(0); - this._processAnimations(); - this._parseComplete(); - } - else - { - this._nextBatch(); - } -}; - -/** - * Process a batch of frames - * - * @private - * @param {number} initialFrameIndex - The index of frame to start. - */ -Spritesheet.prototype._processFrames = function _processFrames (initialFrameIndex) -{ - var frameIndex = initialFrameIndex; - var maxFrames = Spritesheet.BATCH_SIZE; - - while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) - { - var i = this._frameKeys[frameIndex]; - var data = this._frames[i]; - var rect = data.frame; - - if (rect) - { - var frame = null; - var trim = null; - var sourceSize = data.trimmed !== false && data.sourceSize - ? data.sourceSize : data.frame; - - var orig = new math.Rectangle( - 0, - 0, - Math.floor(sourceSize.w) / this.resolution, - Math.floor(sourceSize.h) / this.resolution - ); - - if (data.rotated) - { - frame = new math.Rectangle( - Math.floor(rect.x) / this.resolution, - Math.floor(rect.y) / this.resolution, - Math.floor(rect.h) / this.resolution, - Math.floor(rect.w) / this.resolution - ); - } - else - { - frame = new math.Rectangle( - Math.floor(rect.x) / this.resolution, - Math.floor(rect.y) / this.resolution, - Math.floor(rect.w) / this.resolution, - Math.floor(rect.h) / this.resolution - ); - } - - // Check to see if the sprite is trimmed - if (data.trimmed !== false && data.spriteSourceSize) - { - trim = new math.Rectangle( - Math.floor(data.spriteSourceSize.x) / this.resolution, - Math.floor(data.spriteSourceSize.y) / this.resolution, - Math.floor(rect.w) / this.resolution, - Math.floor(rect.h) / this.resolution - ); - } - - this.textures[i] = new core.Texture( - this.baseTexture, - frame, - orig, - trim, - data.rotated ? 2 : 0, - data.anchor - ); - - // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions - core.Texture.addToCache(this.textures[i], i); - } - - frameIndex++; - } -}; - -/** - * Parse animations config - * - * @private - */ -Spritesheet.prototype._processAnimations = function _processAnimations () -{ - var animations = this.data.animations || {}; - - for (var animName in animations) - { - this.animations[animName] = []; - for (var i = 0; i < animations[animName].length; i++) - { - var frameName = animations[animName][i]; - - this.animations[animName].push(this.textures[frameName]); - } - } -}; - -/** - * The parse has completed. - * - * @private - */ -Spritesheet.prototype._parseComplete = function _parseComplete () -{ - var callback = this._callback; - - this._callback = null; - this._batchIndex = 0; - callback.call(this, this.textures); -}; - -/** - * Begin the next batch of textures. - * - * @private - */ -Spritesheet.prototype._nextBatch = function _nextBatch () -{ - var this$1 = this; - - this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); - this._batchIndex++; - setTimeout(function () { - if (this$1._batchIndex * Spritesheet.BATCH_SIZE < this$1._frameKeys.length) - { - this$1._nextBatch(); - } - else - { - this$1._processAnimations(); - this$1._parseComplete(); - } - }, 0); -}; - -/** - * Destroy Spritesheet and don't use after this. - * - * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well - */ -Spritesheet.prototype.destroy = function destroy (destroyBase) -{ - if ( destroyBase === void 0 ) destroyBase = false; - - for (var i in this.textures) - { - this.textures[i].destroy(); - } - this._frames = null; - this._frameKeys = null; - this.data = null; - this.textures = null; - if (destroyBase) - { - this.baseTexture.destroy(); - } - this.baseTexture = null; -}; - -Object.defineProperties( Spritesheet, staticAccessors ); - -/** - * {@link PIXI.Loader Loader} middleware for loading texture atlases that have been created with - * TexturePacker or similar JSON-based spritesheet. - * - * This middleware automatically generates Texture resources. - * - * @class - * @memberof PIXI - * @implements PIXI.ILoaderPlugin - */ -var SpritesheetLoader = function SpritesheetLoader () {}; - -SpritesheetLoader.use = function use (resource, next) -{ - var imageResourceName = (resource.name) + "_image"; - - // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists - if (!resource.data - || resource.type !== loaders.LoaderResource.TYPE.JSON - || !resource.data.frames - || this.resources[imageResourceName] - ) - { - next(); - - return; - } - - var loadOptions = { - crossOrigin: resource.crossOrigin, - metadata: resource.metadata.imageMetadata, - parentResource: resource, - }; - - var resourcePath = SpritesheetLoader.getResourcePath(resource, this.baseUrl); - - // load the image for this sheet - this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) - { - if (res.error) - { - next(res.error); - - return; - } - - var spritesheet = new Spritesheet( - res.texture.baseTexture, - resource.data, - resource.url - ); - - spritesheet.parse(function () { - resource.spritesheet = spritesheet; - resource.textures = spritesheet.textures; - next(); - }); - }); -}; - -/** - * Get the spritesheets root path - * @param {PIXI.LoaderResource} resource - Resource to check path - * @param {string} baseUrl - Base root url - */ -SpritesheetLoader.getResourcePath = function getResourcePath (resource, baseUrl) -{ - // Prepend url path unless the resource image is a data url - if (resource.isDataUrl) - { - return resource.data.meta.image; - } - - return utils.url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); -}; - -exports.Spritesheet = Spritesheet; -exports.SpritesheetLoader = SpritesheetLoader; - - -},{"@pixi/core":17,"@pixi/loaders":28,"@pixi/math":29,"@pixi/utils":47}],44:[function(require,module,exports){ -/*! - * @pixi/text-bitmap - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/text-bitmap is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var core = require('@pixi/core'); -var display = require('@pixi/display'); -var math = require('@pixi/math'); -var settings = require('@pixi/settings'); -var sprite = require('@pixi/sprite'); -var utils = require('@pixi/utils'); -var loaders = require('@pixi/loaders'); - -/** - * A BitmapText object will create a line or multiple lines of text using bitmap font. - * - * The primary advantage of this class over Text is that all of your textures are pre-generated and loading, - * meaning that rendering is fast, and changing text has no performance implications. - * - * The primary disadvantage is that you need to preload the bitmap font assets, and thus the styling is set in stone. - * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters. - * - * To split a line you can use '\n', '\r' or '\r\n' in your string. - * - * You can generate the fnt files using - * http://www.angelcode.com/products/bmfont/ for Windows or - * http://www.bmglyph.com/ for Mac. - * - * A BitmapText can only be created when the font is loaded. - * - * ```js - * // in this case the font is in a file called 'desyrel.fnt' - * let bitmapText = new PIXI.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); - * ``` - * - * @class - * @extends PIXI.Container - * @memberof PIXI - */ -var BitmapText = /*@__PURE__*/(function (Container) { - function BitmapText(text, style) - { - var this$1 = this; - if ( style === void 0 ) style = {}; - - Container.call(this); - - /** - * Private tracker for the width of the overall text - * - * @member {number} - * @private - */ - this._textWidth = 0; - - /** - * Private tracker for the height of the overall text - * - * @member {number} - * @private - */ - this._textHeight = 0; - - /** - * Private tracker for the letter sprite pool. - * - * @member {PIXI.Sprite[]} - * @private - */ - this._glyphs = []; - - /** - * Private tracker for the current style. - * - * @member {object} - * @private - */ - this._font = { - tint: style.tint !== undefined ? style.tint : 0xFFFFFF, - align: style.align || 'left', - name: null, - size: 0, - }; - - /** - * Private tracker for the current font. - * - * @member {object} - * @private - */ - this.font = style.font; // run font setter - - /** - * Private tracker for the current text. - * - * @member {string} - * @private - */ - this._text = text; - - /** - * The max width of this bitmap text in pixels. If the text provided is longer than the - * value provided, line breaks will be automatically inserted in the last whitespace. - * Disable by setting value to 0 - * - * @member {number} - * @private - */ - this._maxWidth = 0; - - /** - * The max line height. This is useful when trying to use the total height of the Text, - * ie: when trying to vertically align. - * - * @member {number} - * @private - */ - this._maxLineHeight = 0; - - /** - * Letter spacing. This is useful for setting the space between characters. - * @member {number} - * @private - */ - this._letterSpacing = 0; - - /** - * Text anchor. read-only - * - * @member {PIXI.ObservablePoint} - * @private - */ - this._anchor = new math.ObservablePoint(function () { this$1.dirty = true; }, this, 0, 0); - - /** - * The dirty state of this object. - * - * @member {boolean} - */ - this.dirty = false; - - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} - * - * @member {boolean} - * @default false - */ - this.roundPixels = settings.settings.ROUND_PIXELS; - - this.updateText(); - } - - if ( Container ) BitmapText.__proto__ = Container; - BitmapText.prototype = Object.create( Container && Container.prototype ); - BitmapText.prototype.constructor = BitmapText; - - var prototypeAccessors = { tint: { configurable: true },align: { configurable: true },anchor: { configurable: true },font: { configurable: true },text: { configurable: true },maxWidth: { configurable: true },maxLineHeight: { configurable: true },textWidth: { configurable: true },letterSpacing: { configurable: true },textHeight: { configurable: true } }; - - /** - * Renders text and updates it when needed - * - * @private - */ - BitmapText.prototype.updateText = function updateText () - { - var data = BitmapText.fonts[this._font.name]; - var scale = this._font.size / data.size; - var pos = new math.Point(); - var chars = []; - var lineWidths = []; - var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' '; - var textLength = text.length; - var maxWidth = this._maxWidth * data.size / this._font.size; - - var prevCharCode = null; - var lastLineWidth = 0; - var maxLineWidth = 0; - var line = 0; - var lastBreakPos = -1; - var lastBreakWidth = 0; - var spacesRemoved = 0; - var maxLineHeight = 0; - - for (var i = 0; i < textLength; i++) - { - var charCode = text.charCodeAt(i); - var char = text.charAt(i); - - if ((/(?:\s)/).test(char)) - { - lastBreakPos = i; - lastBreakWidth = lastLineWidth; - } - - if (char === '\r' || char === '\n') - { - lineWidths.push(lastLineWidth); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - ++line; - ++spacesRemoved; - - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - continue; - } - - var charData = data.chars[charCode]; - - if (!charData) - { - continue; - } - - if (prevCharCode && charData.kerning[prevCharCode]) - { - pos.x += charData.kerning[prevCharCode]; - } - - chars.push({ - texture: charData.texture, - line: line, - charCode: charCode, - position: new math.Point(pos.x + charData.xOffset + (this._letterSpacing / 2), pos.y + charData.yOffset), - }); - pos.x += charData.xAdvance + this._letterSpacing; - lastLineWidth = pos.x; - maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); - prevCharCode = charCode; - - if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) - { - ++spacesRemoved; - utils.removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); - i = lastBreakPos; - lastBreakPos = -1; - - lineWidths.push(lastBreakWidth); - maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); - line++; - - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - } - } - - var lastChar = text.charAt(text.length - 1); - - if (lastChar !== '\r' && lastChar !== '\n') - { - if ((/(?:\s)/).test(lastChar)) - { - lastLineWidth = lastBreakWidth; - } - - lineWidths.push(lastLineWidth); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - } - - var lineAlignOffsets = []; - - for (var i$1 = 0; i$1 <= line; i$1++) - { - var alignOffset = 0; - - if (this._font.align === 'right') - { - alignOffset = maxLineWidth - lineWidths[i$1]; - } - else if (this._font.align === 'center') - { - alignOffset = (maxLineWidth - lineWidths[i$1]) / 2; - } - - lineAlignOffsets.push(alignOffset); - } - - var lenChars = chars.length; - var tint = this.tint; - - for (var i$2 = 0; i$2 < lenChars; i$2++) - { - var c = this._glyphs[i$2]; // get the next glyph sprite - - if (c) - { - c.texture = chars[i$2].texture; - } - else - { - c = new sprite.Sprite(chars[i$2].texture); - c.roundPixels = this.roundPixels; - this._glyphs.push(c); - } - - c.position.x = (chars[i$2].position.x + lineAlignOffsets[chars[i$2].line]) * scale; - c.position.y = chars[i$2].position.y * scale; - c.scale.x = c.scale.y = scale; - c.tint = tint; - - if (!c.parent) - { - this.addChild(c); - } - } - - // remove unnecessary children. - for (var i$3 = lenChars; i$3 < this._glyphs.length; ++i$3) - { - this.removeChild(this._glyphs[i$3]); - } - - this._textWidth = maxLineWidth * scale; - this._textHeight = (pos.y + data.lineHeight) * scale; - - // apply anchor - if (this.anchor.x !== 0 || this.anchor.y !== 0) - { - for (var i$4 = 0; i$4 < lenChars; i$4++) - { - this._glyphs[i$4].x -= this._textWidth * this.anchor.x; - this._glyphs[i$4].y -= this._textHeight * this.anchor.y; - } - } - this._maxLineHeight = maxLineHeight * scale; - }; - - /** - * Updates the transform of this object - * - * @private - */ - BitmapText.prototype.updateTransform = function updateTransform () - { - this.validate(); - this.containerUpdateTransform(); - }; - - /** - * Validates text before calling parent's getLocalBounds - * - * @return {PIXI.Rectangle} The rectangular bounding area - */ - BitmapText.prototype.getLocalBounds = function getLocalBounds () - { - this.validate(); - - return Container.prototype.getLocalBounds.call(this); - }; - - /** - * Updates text when needed - * - * @private - */ - BitmapText.prototype.validate = function validate () - { - if (this.dirty) - { - this.updateText(); - this.dirty = false; - } - }; - - /** - * The tint of the BitmapText object. - * - * @member {number} - */ - prototypeAccessors.tint.get = function () - { - return this._font.tint; - }; - - prototypeAccessors.tint.set = function (value) // eslint-disable-line require-jsdoc - { - this._font.tint = (typeof value === 'number' && value >= 0) ? value : 0xFFFFFF; - - this.dirty = true; - }; - - /** - * The alignment of the BitmapText object. - * - * @member {string} - * @default 'left' - */ - prototypeAccessors.align.get = function () - { - return this._font.align; - }; - - prototypeAccessors.align.set = function (value) // eslint-disable-line require-jsdoc - { - this._font.align = value || 'left'; - - this.dirty = true; - }; - - /** - * The anchor sets the origin point of the text. - * - * The default is `(0,0)`, this means the text's origin is the top left. - * - * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. - * - * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. - * - * @member {PIXI.Point | number} - */ - prototypeAccessors.anchor.get = function () - { - return this._anchor; - }; - - prototypeAccessors.anchor.set = function (value) // eslint-disable-line require-jsdoc - { - if (typeof value === 'number') - { - this._anchor.set(value); - } - else - { - this._anchor.copyFrom(value); - } - }; - - /** - * The font descriptor of the BitmapText object. - * - * @member {object} - */ - prototypeAccessors.font.get = function () - { - return this._font; - }; - - prototypeAccessors.font.set = function (value) // eslint-disable-line require-jsdoc - { - if (!value) - { - return; - } - - if (typeof value === 'string') - { - value = value.split(' '); - - this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); - this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; - } - else - { - this._font.name = value.name; - this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); - } - - this.dirty = true; - }; - - /** - * The text of the BitmapText object. - * - * @member {string} - */ - prototypeAccessors.text.get = function () - { - return this._text; - }; - - prototypeAccessors.text.set = function (text) // eslint-disable-line require-jsdoc - { - text = String(text === null || text === undefined ? '' : text); - - if (this._text === text) - { - return; - } - this._text = text; - this.dirty = true; - }; - - /** - * The max width of this bitmap text in pixels. If the text provided is longer than the - * value provided, line breaks will be automatically inserted in the last whitespace. - * Disable by setting the value to 0. - * - * @member {number} - */ - prototypeAccessors.maxWidth.get = function () - { - return this._maxWidth; - }; - - prototypeAccessors.maxWidth.set = function (value) // eslint-disable-line require-jsdoc - { - if (this._maxWidth === value) - { - return; - } - this._maxWidth = value; - this.dirty = true; - }; - - /** - * The max line height. This is useful when trying to use the total height of the Text, - * i.e. when trying to vertically align. - * - * @member {number} - * @readonly - */ - prototypeAccessors.maxLineHeight.get = function () - { - this.validate(); - - return this._maxLineHeight; - }; - - /** - * The width of the overall text, different from fontSize, - * which is defined in the style object. - * - * @member {number} - * @readonly - */ - prototypeAccessors.textWidth.get = function () - { - this.validate(); - - return this._textWidth; - }; - - /** - * Additional space between characters. - * - * @member {number} - */ - prototypeAccessors.letterSpacing.get = function () - { - return this._letterSpacing; - }; - - prototypeAccessors.letterSpacing.set = function (value) // eslint-disable-line require-jsdoc - { - if (this._letterSpacing !== value) - { - this._letterSpacing = value; - this.dirty = true; - } - }; - - /** - * The height of the overall text, different from fontSize, - * which is defined in the style object. - * - * @member {number} - * @readonly - */ - prototypeAccessors.textHeight.get = function () - { - this.validate(); - - return this._textHeight; - }; - - /** - * Register a bitmap font with data and a texture. - * - * @static - * @param {XMLDocument} xml - The XML document data. - * @param {Object.|PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. - * If providing an object, the key is the `` element's `file` attribute in the FNT file. - * @return {Object} Result font object with font, size, lineHeight and char fields. - */ - BitmapText.registerFont = function registerFont (xml, textures) - { - var data = {}; - var info = xml.getElementsByTagName('info')[0]; - var common = xml.getElementsByTagName('common')[0]; - var pages = xml.getElementsByTagName('page'); - var res = utils.getResolutionOfUrl(pages[0].getAttribute('file'), settings.settings.RESOLUTION); - var pagesTextures = {}; - - data.font = info.getAttribute('face'); - data.size = parseInt(info.getAttribute('size'), 10); - data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; - data.chars = {}; - - // Single texture, convert to list - if (textures instanceof core.Texture) - { - textures = [textures]; - } - - // Convert the input Texture, Textures or object - // into a page Texture lookup by "id" - for (var i = 0; i < pages.length; i++) - { - var id = pages[i].getAttribute('id'); - var file = pages[i].getAttribute('file'); - - pagesTextures[id] = textures instanceof Array ? textures[i] : textures[file]; - } - - // parse letters - var letters = xml.getElementsByTagName('char'); - - for (var i$1 = 0; i$1 < letters.length; i$1++) - { - var letter = letters[i$1]; - var charCode = parseInt(letter.getAttribute('id'), 10); - var page = letter.getAttribute('page') || 0; - var textureRect = new math.Rectangle( - (parseInt(letter.getAttribute('x'), 10) / res) + (pagesTextures[page].frame.x / res), - (parseInt(letter.getAttribute('y'), 10) / res) + (pagesTextures[page].frame.y / res), - parseInt(letter.getAttribute('width'), 10) / res, - parseInt(letter.getAttribute('height'), 10) / res - ); - - data.chars[charCode] = { - xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, - yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, - xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, - kerning: {}, - texture: new core.Texture(pagesTextures[page].baseTexture, textureRect), - page: page, - }; - } - - // parse kernings - var kernings = xml.getElementsByTagName('kerning'); - - for (var i$2 = 0; i$2 < kernings.length; i$2++) - { - var kerning = kernings[i$2]; - var first = parseInt(kerning.getAttribute('first'), 10) / res; - var second = parseInt(kerning.getAttribute('second'), 10) / res; - var amount = parseInt(kerning.getAttribute('amount'), 10) / res; - - if (data.chars[second]) - { - data.chars[second].kerning[first] = amount; - } - } - - // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 - // but it's very likely to change - BitmapText.fonts[data.font] = data; - - return data; - }; - - Object.defineProperties( BitmapText.prototype, prototypeAccessors ); - - return BitmapText; -}(display.Container)); - -BitmapText.fonts = {}; - -/** - * {@link PIXI.Loader Loader} middleware for loading - * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}. - * @class - * @memberof PIXI - * @implements PIXI.ILoaderPlugin - */ -var BitmapFontLoader = function BitmapFontLoader () {}; - -BitmapFontLoader.parse = function parse (resource, texture) -{ - resource.bitmapFont = BitmapText.registerFont(resource.data, texture); -}; - -/** - * Called when the plugin is installed. - * - * @see PIXI.Loader.registerPlugin - */ -BitmapFontLoader.add = function add () -{ - loaders.LoaderResource.setExtensionXhrType('fnt', loaders.LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT); -}; - -/** - * Replacement for NodeJS's path.dirname - * @private - * @param {string} url Path to get directory for - */ -BitmapFontLoader.dirname = function dirname (url) -{ - var dir = url - .replace(/\/$/, '') // replace trailing slash - .replace(/\/[^\/]*$/, ''); // remove everything after the last - - // File request is relative, use current directory - if (dir === url) - { - return '.'; - } - // Started with a slash - else if (dir === '') - { - return '/'; - } - - return dir; -}; - -/** - * Called after a resource is loaded. - * @see PIXI.Loader.loaderMiddleware - * @param {PIXI.LoaderResource} resource - * @param {function} next - */ -BitmapFontLoader.use = function use (resource, next) -{ - // skip if no data or not xml data - if (!resource.data || resource.type !== loaders.LoaderResource.TYPE.XML) - { - next(); - - return; - } - - // skip if not bitmap font data, using some silly duck-typing - if (resource.data.getElementsByTagName('page').length === 0 - || resource.data.getElementsByTagName('info').length === 0 - || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null - ) - { - next(); - - return; - } - - var xmlUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : ''; - - if (resource.isDataUrl) - { - if (xmlUrl === '.') - { - xmlUrl = ''; - } - - if (this.baseUrl && xmlUrl) - { - // if baseurl has a trailing slash then add one to xmlUrl so the replace works below - if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') - { - xmlUrl += '/'; - } - } - } - - // remove baseUrl from xmlUrl - xmlUrl = xmlUrl.replace(this.baseUrl, ''); - - // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. - if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') - { - xmlUrl += '/'; - } - - var pages = resource.data.getElementsByTagName('page'); - var textures = {}; - - // Handle completed, when the number of textures - // load is the same number as references in the fnt file - var completed = function (page) { - textures[page.metadata.pageFile] = page.texture; - - if (Object.keys(textures).length === pages.length) - { - BitmapFontLoader.parse(resource, textures); - next(); - } - }; - - for (var i = 0; i < pages.length; ++i) - { - var pageFile = pages[i].getAttribute('file'); - var url = xmlUrl + pageFile; - var exists = false; - - // incase the image is loaded outside - // using the same loader, resource will be available - for (var name in this.resources) - { - var bitmapResource = this.resources[name]; - - if (bitmapResource.url === url) - { - bitmapResource.metadata.pageFile = pageFile; - if (bitmapResource.texture) - { - completed(bitmapResource); - } - else - { - bitmapResource.onAfterMiddleware.add(completed); - } - exists = true; - break; - } - } - - // texture is not loaded, we'll attempt to add - // it to the load and add the texture to the list - if (!exists) - { - // Standard loading options for images - var options = { - crossOrigin: resource.crossOrigin, - loadType: loaders.LoaderResource.LOAD_TYPE.IMAGE, - metadata: Object.assign( - { pageFile: pageFile }, - resource.metadata.imageMetadata - ), - parentResource: resource, - }; - - this.add(url, options, completed); - } - } -}; - -exports.BitmapFontLoader = BitmapFontLoader; -exports.BitmapText = BitmapText; - - -},{"@pixi/core":17,"@pixi/display":18,"@pixi/loaders":28,"@pixi/math":29,"@pixi/settings":39,"@pixi/sprite":42,"@pixi/utils":47}],45:[function(require,module,exports){ -/*! - * @pixi/text - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/text is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var sprite = require('@pixi/sprite'); -var core = require('@pixi/core'); -var settings = require('@pixi/settings'); -var math = require('@pixi/math'); -var utils = require('@pixi/utils'); - -/** - * Constants that define the type of gradient on text. - * - * @static - * @constant - * @name TEXT_GRADIENT - * @memberof PIXI - * @type {object} - * @property {number} LINEAR_VERTICAL Vertical gradient - * @property {number} LINEAR_HORIZONTAL Linear gradient - */ -var TEXT_GRADIENT = { - LINEAR_VERTICAL: 0, - LINEAR_HORIZONTAL: 1, -}; - -// disabling eslint for now, going to rewrite this in v5 - -var defaultStyle = { - align: 'left', - breakWords: false, - dropShadow: false, - dropShadowAlpha: 1, - dropShadowAngle: Math.PI / 6, - dropShadowBlur: 0, - dropShadowColor: 'black', - dropShadowDistance: 5, - fill: 'black', - fillGradientType: TEXT_GRADIENT.LINEAR_VERTICAL, - fillGradientStops: [], - fontFamily: 'Arial', - fontSize: 26, - fontStyle: 'normal', - fontVariant: 'normal', - fontWeight: 'normal', - letterSpacing: 0, - lineHeight: 0, - lineJoin: 'miter', - miterLimit: 10, - padding: 0, - stroke: 'black', - strokeThickness: 0, - textBaseline: 'alphabetic', - trim: false, - whiteSpace: 'pre', - wordWrap: false, - wordWrapWidth: 100, - leading: 0, -}; - -var genericFontFamilies = [ - 'serif', - 'sans-serif', - 'monospace', - 'cursive', - 'fantasy', - 'system-ui' ]; - -/** - * A TextStyle Object contains information to decorate a Text objects. - * - * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it. - * - * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style). - * - * @class - * @memberof PIXI - */ -var TextStyle = function TextStyle(style) -{ - this.styleID = 0; - - this.reset(); - - deepCopyProperties(this, style, style); -}; - -var prototypeAccessors = { align: { configurable: true },breakWords: { configurable: true },dropShadow: { configurable: true },dropShadowAlpha: { configurable: true },dropShadowAngle: { configurable: true },dropShadowBlur: { configurable: true },dropShadowColor: { configurable: true },dropShadowDistance: { configurable: true },fill: { configurable: true },fillGradientType: { configurable: true },fillGradientStops: { configurable: true },fontFamily: { configurable: true },fontSize: { configurable: true },fontStyle: { configurable: true },fontVariant: { configurable: true },fontWeight: { configurable: true },letterSpacing: { configurable: true },lineHeight: { configurable: true },leading: { configurable: true },lineJoin: { configurable: true },miterLimit: { configurable: true },padding: { configurable: true },stroke: { configurable: true },strokeThickness: { configurable: true },textBaseline: { configurable: true },trim: { configurable: true },whiteSpace: { configurable: true },wordWrap: { configurable: true },wordWrapWidth: { configurable: true } }; - -/** - * Creates a new TextStyle object with the same values as this one. - * Note that the only the properties of the object are cloned. - * - * @return {PIXI.TextStyle} New cloned TextStyle object - */ -TextStyle.prototype.clone = function clone () -{ - var clonedProperties = {}; - - deepCopyProperties(clonedProperties, this, defaultStyle); - - return new TextStyle(clonedProperties); -}; - -/** - * Resets all properties to the defaults specified in TextStyle.prototype._default - */ -TextStyle.prototype.reset = function reset () -{ - deepCopyProperties(this, defaultStyle, defaultStyle); -}; - -/** - * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text - * - * @member {string} - */ -prototypeAccessors.align.get = function () -{ - return this._align; -}; -prototypeAccessors.align.set = function (align) // eslint-disable-line require-jsdoc -{ - if (this._align !== align) - { - this._align = align; - this.styleID++; - } -}; - -/** - * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true - * - * @member {boolean} - */ -prototypeAccessors.breakWords.get = function () -{ - return this._breakWords; -}; -prototypeAccessors.breakWords.set = function (breakWords) // eslint-disable-line require-jsdoc -{ - if (this._breakWords !== breakWords) - { - this._breakWords = breakWords; - this.styleID++; - } -}; - -/** - * Set a drop shadow for the text - * - * @member {boolean} - */ -prototypeAccessors.dropShadow.get = function () -{ - return this._dropShadow; -}; -prototypeAccessors.dropShadow.set = function (dropShadow) // eslint-disable-line require-jsdoc -{ - if (this._dropShadow !== dropShadow) - { - this._dropShadow = dropShadow; - this.styleID++; - } -}; - -/** - * Set alpha for the drop shadow - * - * @member {number} - */ -prototypeAccessors.dropShadowAlpha.get = function () -{ - return this._dropShadowAlpha; -}; -prototypeAccessors.dropShadowAlpha.set = function (dropShadowAlpha) // eslint-disable-line require-jsdoc -{ - if (this._dropShadowAlpha !== dropShadowAlpha) - { - this._dropShadowAlpha = dropShadowAlpha; - this.styleID++; - } -}; - -/** - * Set a angle of the drop shadow - * - * @member {number} - */ -prototypeAccessors.dropShadowAngle.get = function () -{ - return this._dropShadowAngle; -}; -prototypeAccessors.dropShadowAngle.set = function (dropShadowAngle) // eslint-disable-line require-jsdoc -{ - if (this._dropShadowAngle !== dropShadowAngle) - { - this._dropShadowAngle = dropShadowAngle; - this.styleID++; - } -}; - -/** - * Set a shadow blur radius - * - * @member {number} - */ -prototypeAccessors.dropShadowBlur.get = function () -{ - return this._dropShadowBlur; -}; -prototypeAccessors.dropShadowBlur.set = function (dropShadowBlur) // eslint-disable-line require-jsdoc -{ - if (this._dropShadowBlur !== dropShadowBlur) - { - this._dropShadowBlur = dropShadowBlur; - this.styleID++; - } -}; - -/** - * A fill style to be used on the dropshadow e.g 'red', '#00FF00' - * - * @member {string|number} - */ -prototypeAccessors.dropShadowColor.get = function () -{ - return this._dropShadowColor; -}; -prototypeAccessors.dropShadowColor.set = function (dropShadowColor) // eslint-disable-line require-jsdoc -{ - var outputColor = getColor(dropShadowColor); - if (this._dropShadowColor !== outputColor) - { - this._dropShadowColor = outputColor; - this.styleID++; - } -}; - -/** - * Set a distance of the drop shadow - * - * @member {number} - */ -prototypeAccessors.dropShadowDistance.get = function () -{ - return this._dropShadowDistance; -}; -prototypeAccessors.dropShadowDistance.set = function (dropShadowDistance) // eslint-disable-line require-jsdoc -{ - if (this._dropShadowDistance !== dropShadowDistance) - { - this._dropShadowDistance = dropShadowDistance; - this.styleID++; - } -}; - -/** - * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. - * Can be an array to create a gradient eg ['#000000','#FFFFFF'] - * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} - * - * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} - */ -prototypeAccessors.fill.get = function () -{ - return this._fill; -}; -prototypeAccessors.fill.set = function (fill) // eslint-disable-line require-jsdoc -{ - var outputColor = getColor(fill); - if (this._fill !== outputColor) - { - this._fill = outputColor; - this.styleID++; - } -}; - -/** - * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. - * See {@link PIXI.TEXT_GRADIENT} - * - * @member {number} - */ -prototypeAccessors.fillGradientType.get = function () -{ - return this._fillGradientType; -}; -prototypeAccessors.fillGradientType.set = function (fillGradientType) // eslint-disable-line require-jsdoc -{ - if (this._fillGradientType !== fillGradientType) - { - this._fillGradientType = fillGradientType; - this.styleID++; - } -}; - -/** - * If fill is an array of colours to create a gradient, this array can set the stop points - * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. - * - * @member {number[]} - */ -prototypeAccessors.fillGradientStops.get = function () -{ - return this._fillGradientStops; -}; -prototypeAccessors.fillGradientStops.set = function (fillGradientStops) // eslint-disable-line require-jsdoc -{ - if (!areArraysEqual(this._fillGradientStops,fillGradientStops)) - { - this._fillGradientStops = fillGradientStops; - this.styleID++; - } -}; - -/** - * The font family - * - * @member {string|string[]} - */ -prototypeAccessors.fontFamily.get = function () -{ - return this._fontFamily; -}; -prototypeAccessors.fontFamily.set = function (fontFamily) // eslint-disable-line require-jsdoc -{ - if (this.fontFamily !== fontFamily) - { - this._fontFamily = fontFamily; - this.styleID++; - } -}; - -/** - * The font size - * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') - * - * @member {number|string} - */ -prototypeAccessors.fontSize.get = function () -{ - return this._fontSize; -}; -prototypeAccessors.fontSize.set = function (fontSize) // eslint-disable-line require-jsdoc -{ - if (this._fontSize !== fontSize) - { - this._fontSize = fontSize; - this.styleID++; - } -}; - -/** - * The font style - * ('normal', 'italic' or 'oblique') - * - * @member {string} - */ -prototypeAccessors.fontStyle.get = function () -{ - return this._fontStyle; -}; -prototypeAccessors.fontStyle.set = function (fontStyle) // eslint-disable-line require-jsdoc -{ - if (this._fontStyle !== fontStyle) - { - this._fontStyle = fontStyle; - this.styleID++; - } -}; - -/** - * The font variant - * ('normal' or 'small-caps') - * - * @member {string} - */ -prototypeAccessors.fontVariant.get = function () -{ - return this._fontVariant; -}; -prototypeAccessors.fontVariant.set = function (fontVariant) // eslint-disable-line require-jsdoc -{ - if (this._fontVariant !== fontVariant) - { - this._fontVariant = fontVariant; - this.styleID++; - } -}; - -/** - * The font weight - * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') - * - * @member {string} - */ -prototypeAccessors.fontWeight.get = function () -{ - return this._fontWeight; -}; -prototypeAccessors.fontWeight.set = function (fontWeight) // eslint-disable-line require-jsdoc -{ - if (this._fontWeight !== fontWeight) - { - this._fontWeight = fontWeight; - this.styleID++; - } -}; - -/** - * The amount of spacing between letters, default is 0 - * - * @member {number} - */ -prototypeAccessors.letterSpacing.get = function () -{ - return this._letterSpacing; -}; -prototypeAccessors.letterSpacing.set = function (letterSpacing) // eslint-disable-line require-jsdoc -{ - if (this._letterSpacing !== letterSpacing) - { - this._letterSpacing = letterSpacing; - this.styleID++; - } -}; - -/** - * The line height, a number that represents the vertical space that a letter uses - * - * @member {number} - */ -prototypeAccessors.lineHeight.get = function () -{ - return this._lineHeight; -}; -prototypeAccessors.lineHeight.set = function (lineHeight) // eslint-disable-line require-jsdoc -{ - if (this._lineHeight !== lineHeight) - { - this._lineHeight = lineHeight; - this.styleID++; - } -}; - -/** - * The space between lines - * - * @member {number} - */ -prototypeAccessors.leading.get = function () -{ - return this._leading; -}; -prototypeAccessors.leading.set = function (leading) // eslint-disable-line require-jsdoc -{ - if (this._leading !== leading) - { - this._leading = leading; - this.styleID++; - } -}; - -/** - * The lineJoin property sets the type of corner created, it can resolve spiked text issues. - * Default is 'miter' (creates a sharp corner). - * - * @member {string} - */ -prototypeAccessors.lineJoin.get = function () -{ - return this._lineJoin; -}; -prototypeAccessors.lineJoin.set = function (lineJoin) // eslint-disable-line require-jsdoc -{ - if (this._lineJoin !== lineJoin) - { - this._lineJoin = lineJoin; - this.styleID++; - } -}; - -/** - * The miter limit to use when using the 'miter' lineJoin mode - * This can reduce or increase the spikiness of rendered text. - * - * @member {number} - */ -prototypeAccessors.miterLimit.get = function () -{ - return this._miterLimit; -}; -prototypeAccessors.miterLimit.set = function (miterLimit) // eslint-disable-line require-jsdoc -{ - if (this._miterLimit !== miterLimit) - { - this._miterLimit = miterLimit; - this.styleID++; - } -}; - -/** - * Occasionally some fonts are cropped. Adding some padding will prevent this from happening - * by adding padding to all sides of the text. - * - * @member {number} - */ -prototypeAccessors.padding.get = function () -{ - return this._padding; -}; -prototypeAccessors.padding.set = function (padding) // eslint-disable-line require-jsdoc -{ - if (this._padding !== padding) - { - this._padding = padding; - this.styleID++; - } -}; - -/** - * A canvas fillstyle that will be used on the text stroke - * e.g 'blue', '#FCFF00' - * - * @member {string|number} - */ -prototypeAccessors.stroke.get = function () -{ - return this._stroke; -}; -prototypeAccessors.stroke.set = function (stroke) // eslint-disable-line require-jsdoc -{ - var outputColor = getColor(stroke); - if (this._stroke !== outputColor) - { - this._stroke = outputColor; - this.styleID++; - } -}; - -/** - * A number that represents the thickness of the stroke. - * Default is 0 (no stroke) - * - * @member {number} - */ -prototypeAccessors.strokeThickness.get = function () -{ - return this._strokeThickness; -}; -prototypeAccessors.strokeThickness.set = function (strokeThickness) // eslint-disable-line require-jsdoc -{ - if (this._strokeThickness !== strokeThickness) - { - this._strokeThickness = strokeThickness; - this.styleID++; - } -}; - -/** - * The baseline of the text that is rendered. - * - * @member {string} - */ -prototypeAccessors.textBaseline.get = function () -{ - return this._textBaseline; -}; -prototypeAccessors.textBaseline.set = function (textBaseline) // eslint-disable-line require-jsdoc -{ - if (this._textBaseline !== textBaseline) - { - this._textBaseline = textBaseline; - this.styleID++; - } -}; - -/** - * Trim transparent borders - * - * @member {boolean} - */ -prototypeAccessors.trim.get = function () -{ - return this._trim; -}; -prototypeAccessors.trim.set = function (trim) // eslint-disable-line require-jsdoc -{ - if (this._trim !== trim) - { - this._trim = trim; - this.styleID++; - } -}; - -/** - * How newlines and spaces should be handled. - * Default is 'pre' (preserve, preserve). - * - * value | New lines | Spaces - * --- | --- | --- - * 'normal' | Collapse | Collapse - * 'pre' | Preserve | Preserve - * 'pre-line' | Preserve | Collapse - * - * @member {string} - */ -prototypeAccessors.whiteSpace.get = function () -{ - return this._whiteSpace; -}; -prototypeAccessors.whiteSpace.set = function (whiteSpace) // eslint-disable-line require-jsdoc -{ - if (this._whiteSpace !== whiteSpace) - { - this._whiteSpace = whiteSpace; - this.styleID++; - } -}; - -/** - * Indicates if word wrap should be used - * - * @member {boolean} - */ -prototypeAccessors.wordWrap.get = function () -{ - return this._wordWrap; -}; -prototypeAccessors.wordWrap.set = function (wordWrap) // eslint-disable-line require-jsdoc -{ - if (this._wordWrap !== wordWrap) - { - this._wordWrap = wordWrap; - this.styleID++; - } -}; - -/** - * The width at which text will wrap, it needs wordWrap to be set to true - * - * @member {number} - */ -prototypeAccessors.wordWrapWidth.get = function () -{ - return this._wordWrapWidth; -}; -prototypeAccessors.wordWrapWidth.set = function (wordWrapWidth) // eslint-disable-line require-jsdoc -{ - if (this._wordWrapWidth !== wordWrapWidth) - { - this._wordWrapWidth = wordWrapWidth; - this.styleID++; - } -}; - -/** - * Generates a font style string to use for `TextMetrics.measureFont()`. - * - * @return {string} Font style string, for passing to `TextMetrics.measureFont()` - */ -TextStyle.prototype.toFontString = function toFontString () -{ - // build canvas api font setting from individual components. Convert a numeric this.fontSize to px - var fontSizeString = (typeof this.fontSize === 'number') ? ((this.fontSize) + "px") : this.fontSize; - - // Clean-up fontFamily property by quoting each font name - // this will support font names with spaces - var fontFamilies = this.fontFamily; - - if (!Array.isArray(this.fontFamily)) - { - fontFamilies = this.fontFamily.split(','); - } - - for (var i = fontFamilies.length - 1; i >= 0; i--) - { - // Trim any extra white-space - var fontFamily = fontFamilies[i].trim(); - - // Check if font already contains strings - if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) - { - fontFamily = "\"" + fontFamily + "\""; - } - fontFamilies[i] = fontFamily; - } - - return ((this.fontStyle) + " " + (this.fontVariant) + " " + (this.fontWeight) + " " + fontSizeString + " " + (fontFamilies.join(','))); -}; - -Object.defineProperties( TextStyle.prototype, prototypeAccessors ); - -/** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * @private - * @param {number|number[]} color - * @return {string} The color as a string. - */ -function getSingleColor(color) -{ - if (typeof color === 'number') - { - return utils.hex2string(color); - } - else if ( typeof color === 'string' ) - { - if ( color.indexOf('0x') === 0 ) - { - color = color.replace('0x', '#'); - } - } - - return color; -} - -/** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * This version can also convert array of colors - * @private - * @param {number|number[]} color - * @return {string} The color as a string. - */ -function getColor(color) -{ - if (!Array.isArray(color)) - { - return getSingleColor(color); - } - else - { - for (var i = 0; i < color.length; ++i) - { - color[i] = getSingleColor(color[i]); - } - - return color; - } -} - -/** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * This version can also convert array of colors - * @private - * @param {Array} array1 First array to compare - * @param {Array} array2 Second array to compare - * @return {boolean} Do the arrays contain the same values in the same order - */ -function areArraysEqual(array1, array2) -{ - if (!Array.isArray(array1) || !Array.isArray(array2)) - { - return false; - } - - if (array1.length !== array2.length) - { - return false; - } - - for (var i = 0; i < array1.length; ++i) - { - if (array1[i] !== array2[i]) - { - return false; - } - } - - return true; -} - -/** - * Utility function to ensure that object properties are copied by value, and not by reference - * @private - * @param {Object} target Target object to copy properties into - * @param {Object} source Source object for the properties to copy - * @param {string} propertyObj Object containing properties names we want to loop over - */ -function deepCopyProperties(target, source, propertyObj) { - for (var prop in propertyObj) { - if (Array.isArray(source[prop])) { - target[prop] = source[prop].slice(); - } else { - target[prop] = source[prop]; - } - } -} - -/** - * The TextMetrics object represents the measurement of a block of text with a specified style. - * - * ```js - * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) - * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) - * ``` - * - * @class - * @memberof PIXI - */ -var TextMetrics = function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) -{ - /** - * The text that was measured - * - * @member {string} - */ - this.text = text; - - /** - * The style that was measured - * - * @member {PIXI.TextStyle} - */ - this.style = style; - - /** - * The measured width of the text - * - * @member {number} - */ - this.width = width; - - /** - * The measured height of the text - * - * @member {number} - */ - this.height = height; - - /** - * An array of lines of the text broken by new lines and wrapping is specified in style - * - * @member {string[]} - */ - this.lines = lines; - - /** - * An array of the line widths for each line matched to `lines` - * - * @member {number[]} - */ - this.lineWidths = lineWidths; - - /** - * The measured line height for this style - * - * @member {number} - */ - this.lineHeight = lineHeight; - - /** - * The maximum line width for all measured lines - * - * @member {number} - */ - this.maxLineWidth = maxLineWidth; - - /** - * The font properties object from TextMetrics.measureFont - * - * @member {PIXI.IFontMetrics} - */ - this.fontProperties = fontProperties; -}; - -/** - * Measures the supplied string of text and returns a Rectangle. - * - * @param {string} text - the text to measure. - * @param {PIXI.TextStyle} style - the text style to use for measuring - * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. - * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. - * @return {PIXI.TextMetrics} measured width and height of the text. - */ -TextMetrics.measureText = function measureText (text, style, wordWrap, canvas) -{ - if ( canvas === void 0 ) canvas = TextMetrics._canvas; - - wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap; - var font = style.toFontString(); - var fontProperties = TextMetrics.measureFont(font); - - // fallback in case UA disallow canvas data extraction - // (toDataURI, getImageData functions) - if (fontProperties.fontSize === 0) - { - fontProperties.fontSize = style.fontSize; - fontProperties.ascent = style.fontSize; - } - - var context = canvas.getContext('2d'); - - context.font = font; - - var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; - var lines = outputText.split(/(?:\r\n|\r|\n)/); - var lineWidths = new Array(lines.length); - var maxLineWidth = 0; - - for (var i = 0; i < lines.length; i++) - { - var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); - - lineWidths[i] = lineWidth; - maxLineWidth = Math.max(maxLineWidth, lineWidth); - } - var width = maxLineWidth + style.strokeThickness; - - if (style.dropShadow) - { - width += style.dropShadowDistance; - } - - var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; - var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) - + ((lines.length - 1) * (lineHeight + style.leading)); - - if (style.dropShadow) - { - height += style.dropShadowDistance; - } - - return new TextMetrics( - text, - style, - width, - height, - lines, - lineWidths, - lineHeight + style.leading, - maxLineWidth, - fontProperties - ); -}; - -/** - * Applies newlines to a string to have it optimally fit into the horizontal - * bounds set by the Text object's wordWrapWidth property. - * - * @private - * @param {string} text - String to apply word wrapping to - * @param {PIXI.TextStyle} style - the style to use when wrapping - * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. - * @return {string} New string with new lines applied where required - */ -TextMetrics.wordWrap = function wordWrap (text, style, canvas) -{ - if ( canvas === void 0 ) canvas = TextMetrics._canvas; - - var context = canvas.getContext('2d'); - - var width = 0; - var line = ''; - var lines = ''; - - var cache = {}; - var letterSpacing = style.letterSpacing; - var whiteSpace = style.whiteSpace; - - // How to handle whitespaces - var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); - var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); - - // whether or not spaces may be added to the beginning of lines - var canPrependSpaces = !collapseSpaces; - - // There is letterSpacing after every char except the last one - // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! - // so for convenience the above needs to be compared to width + 1 extra letterSpace - // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ - // ________________________________________________ - // And then the final space is simply no appended to each line - var wordWrapWidth = style.wordWrapWidth + letterSpacing; - - // break text into words, spaces and newline chars - var tokens = TextMetrics.tokenize(text); - - for (var i = 0; i < tokens.length; i++) - { - // get the word, space or newlineChar - var token = tokens[i]; - - // if word is a new line - if (TextMetrics.isNewline(token)) - { - // keep the new line - if (!collapseNewlines) - { - lines += TextMetrics.addLine(line); - canPrependSpaces = !collapseSpaces; - line = ''; - width = 0; - continue; - } - - // if we should collapse new lines - // we simply convert it into a space - token = ' '; - } - - // if we should collapse repeated whitespaces - if (collapseSpaces) - { - // check both this and the last tokens for spaces - var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); - var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); - - if (currIsBreakingSpace && lastIsBreakingSpace) - { - continue; - } - } - - // get word width from cache if possible - var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); - - // word is longer than desired bounds - if (tokenWidth > wordWrapWidth) - { - // if we are not already at the beginning of a line - if (line !== '') - { - // start newlines for overflow words - lines += TextMetrics.addLine(line); - line = ''; - width = 0; - } - - // break large word over multiple lines - if (TextMetrics.canBreakWords(token, style.breakWords)) - { - // break word into characters - var characters = token.split(''); - - // loop the characters - for (var j = 0; j < characters.length; j++) - { - var char = characters[j]; - - var k = 1; - // we are not at the end of the token - - while (characters[j + k]) - { - var nextChar = characters[j + k]; - var lastChar = char[char.length - 1]; - - // should not split chars - if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) - { - // combine chars & move forward one - char += nextChar; - } - else - { - break; - } - - k++; - } - - j += char.length - 1; - - var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); - - if (characterWidth + width > wordWrapWidth) - { - lines += TextMetrics.addLine(line); - canPrependSpaces = false; - line = ''; - width = 0; - } - - line += char; - width += characterWidth; - } - } - - // run word out of the bounds - else - { - // if there are words in this line already - // finish that line and start a new one - if (line.length > 0) - { - lines += TextMetrics.addLine(line); - line = ''; - width = 0; - } - - var isLastToken = i === tokens.length - 1; - - // give it its own line if it's not the end - lines += TextMetrics.addLine(token, !isLastToken); - canPrependSpaces = false; - line = ''; - width = 0; - } - } - - // word could fit - else - { - // word won't fit because of existing words - // start a new line - if (tokenWidth + width > wordWrapWidth) - { - // if its a space we don't want it - canPrependSpaces = false; - - // add a new line - lines += TextMetrics.addLine(line); - - // start a new line - line = ''; - width = 0; - } - - // don't add spaces to the beginning of lines - if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) - { - // add the word to the current line - line += token; - - // update width counter - width += tokenWidth; - } - } - } - - lines += TextMetrics.addLine(line, false); - - return lines; -}; - -/** - * Convienience function for logging each line added during the wordWrap - * method - * - * @private - * @param {string} line - The line of text to add - * @param {boolean} newLine - Add new line character to end - * @return {string} A formatted line - */ -TextMetrics.addLine = function addLine (line, newLine) -{ - if ( newLine === void 0 ) newLine = true; - - line = TextMetrics.trimRight(line); - - line = (newLine) ? (line + "\n") : line; - - return line; -}; - -/** - * Gets & sets the widths of calculated characters in a cache object - * - * @private - * @param {string} key The key - * @param {number} letterSpacing The letter spacing - * @param {object} cache The cache - * @param {CanvasRenderingContext2D} context The canvas context - * @return {number} The from cache. - */ -TextMetrics.getFromCache = function getFromCache (key, letterSpacing, cache, context) -{ - var width = cache[key]; - - if (width === undefined) - { - var spacing = ((key.length) * letterSpacing); - - width = context.measureText(key).width + spacing; - cache[key] = width; - } - - return width; -}; - -/** - * Determines whether we should collapse breaking spaces - * - * @private - * @param {string} whiteSpace The TextStyle property whiteSpace - * @return {boolean} should collapse - */ -TextMetrics.collapseSpaces = function collapseSpaces (whiteSpace) -{ - return (whiteSpace === 'normal' || whiteSpace === 'pre-line'); -}; - -/** - * Determines whether we should collapse newLine chars - * - * @private - * @param {string} whiteSpace The white space - * @return {boolean} should collapse - */ -TextMetrics.collapseNewlines = function collapseNewlines (whiteSpace) -{ - return (whiteSpace === 'normal'); -}; - -/** - * trims breaking whitespaces from string - * - * @private - * @param {string} text The text - * @return {string} trimmed string - */ -TextMetrics.trimRight = function trimRight (text) -{ - if (typeof text !== 'string') - { - return ''; - } - - for (var i = text.length - 1; i >= 0; i--) - { - var char = text[i]; - - if (!TextMetrics.isBreakingSpace(char)) - { - break; - } - - text = text.slice(0, -1); - } - - return text; -}; - -/** - * Determines if char is a newline. - * - * @private - * @param {string} char The character - * @return {boolean} True if newline, False otherwise. - */ -TextMetrics.isNewline = function isNewline (char) -{ - if (typeof char !== 'string') - { - return false; - } - - return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0); -}; - -/** - * Determines if char is a breaking whitespace. - * - * @private - * @param {string} char The character - * @return {boolean} True if whitespace, False otherwise. - */ -TextMetrics.isBreakingSpace = function isBreakingSpace (char) -{ - if (typeof char !== 'string') - { - return false; - } - - return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0); -}; - -/** - * Splits a string into words, breaking-spaces and newLine characters - * - * @private - * @param {string} text The text - * @return {string[]} A tokenized array - */ -TextMetrics.tokenize = function tokenize (text) -{ - var tokens = []; - var token = ''; - - if (typeof text !== 'string') - { - return tokens; - } - - for (var i = 0; i < text.length; i++) - { - var char = text[i]; - - if (TextMetrics.isBreakingSpace(char) || TextMetrics.isNewline(char)) - { - if (token !== '') - { - tokens.push(token); - token = ''; - } - - tokens.push(char); - - continue; - } - - token += char; - } - - if (token !== '') - { - tokens.push(token); - } - - return tokens; -}; - -/** - * This method exists to be easily overridden - * It allows one to customise which words should break - * Examples are if the token is CJK or numbers. - * It must return a boolean. - * - * @private - * @param {string} token The token - * @param {boolean} breakWords The style attr break words - * @return {boolean} whether to break word or not - */ -TextMetrics.canBreakWords = function canBreakWords (token, breakWords) -{ - return breakWords; -}; - -/** - * This method exists to be easily overridden - * It allows one to determine whether a pair of characters - * should be broken by newlines - * For example certain characters in CJK langs or numbers. - * It must return a boolean. - * - * @private - * @param {string} char The character - * @param {string} nextChar The next character - * @param {string} token The token/word the characters are from - * @param {number} index The index in the token of the char - * @param {boolean} breakWords The style attr break words - * @return {boolean} whether to break word or not - */ -TextMetrics.canBreakChars = function canBreakChars (char, nextChar, token, index, breakWords) // eslint-disable-line no-unused-vars -{ - return true; -}; - -/** - * Calculates the ascent, descent and fontSize of a given font-style - * - * @static - * @param {string} font - String representing the style of the font - * @return {PIXI.IFontMetrics} Font properties object - */ -TextMetrics.measureFont = function measureFont (font) -{ - // as this method is used for preparing assets, don't recalculate things if we don't need to - if (TextMetrics._fonts[font]) - { - return TextMetrics._fonts[font]; - } - - var properties = {}; - - var canvas = TextMetrics._canvas; - var context = TextMetrics._context; - - context.font = font; - - var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; - var width = Math.ceil(context.measureText(metricsString).width); - var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); - var height = 2 * baseline; - - baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; - - canvas.width = width; - canvas.height = height; - - context.fillStyle = '#f00'; - context.fillRect(0, 0, width, height); - - context.font = font; - - context.textBaseline = 'alphabetic'; - context.fillStyle = '#000'; - context.fillText(metricsString, 0, baseline); - - var imagedata = context.getImageData(0, 0, width, height).data; - var pixels = imagedata.length; - var line = width * 4; - - var i = 0; - var idx = 0; - var stop = false; - - // ascent. scan from top to bottom until we find a non red pixel - for (i = 0; i < baseline; ++i) - { - for (var j = 0; j < line; j += 4) - { - if (imagedata[idx + j] !== 255) - { - stop = true; - break; - } - } - if (!stop) - { - idx += line; - } - else - { - break; - } - } - - properties.ascent = baseline - i; - - idx = pixels - line; - stop = false; - - // descent. scan from bottom to top until we find a non red pixel - for (i = height; i > baseline; --i) - { - for (var j$1 = 0; j$1 < line; j$1 += 4) - { - if (imagedata[idx + j$1] !== 255) - { - stop = true; - break; - } - } - - if (!stop) - { - idx -= line; - } - else - { - break; - } - } - - properties.descent = i - baseline; - properties.fontSize = properties.ascent + properties.descent; - - TextMetrics._fonts[font] = properties; - - return properties; -}; - -/** - * Clear font metrics in metrics cache. - * - * @static - * @param {string} [font] - font name. If font name not set then clear cache for all fonts. - */ -TextMetrics.clearMetrics = function clearMetrics (font) -{ - if ( font === void 0 ) font = ''; - - if (font) - { - delete TextMetrics._fonts[font]; - } - else - { - TextMetrics._fonts = {}; - } -}; - -/** - * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. - * - * @typedef {object} FontMetrics - * @property {number} ascent - The ascent distance - * @property {number} descent - The descent distance - * @property {number} fontSize - Font size from ascent to descent - * @memberof PIXI.TextMetrics - * @private - */ - -var canvas = (function () { - try - { - // OffscreenCanvas2D measureText can be up to 40% faster. - var c = new OffscreenCanvas(0, 0); - - return c.getContext('2d') ? c : document.createElement('canvas'); - } - catch (ex) - { - return document.createElement('canvas'); - } -})(); - -canvas.width = canvas.height = 10; - -/** - * Cached canvas element for measuring text - * - * @memberof PIXI.TextMetrics - * @type {HTMLCanvasElement} - * @private - */ -TextMetrics._canvas = canvas; - -/** - * Cache for context to use. - * - * @memberof PIXI.TextMetrics - * @type {CanvasRenderingContext2D} - * @private - */ -TextMetrics._context = canvas.getContext('2d'); - -/** - * Cache of {@see PIXI.TextMetrics.FontMetrics} objects. - * - * @memberof PIXI.TextMetrics - * @type {Object} - * @private - */ -TextMetrics._fonts = {}; - -/** - * String used for calculate font metrics. - * These characters are all tall to help calculate the height required for text. - * - * @static - * @memberof PIXI.TextMetrics - * @name METRICS_STRING - * @type {string} - * @default |ÉqÅ - */ -TextMetrics.METRICS_STRING = '|ÉqÅ'; - -/** - * Baseline symbol for calculate font metrics. - * - * @static - * @memberof PIXI.TextMetrics - * @name BASELINE_SYMBOL - * @type {string} - * @default M - */ -TextMetrics.BASELINE_SYMBOL = 'M'; - -/** - * Baseline multiplier for calculate font metrics. - * - * @static - * @memberof PIXI.TextMetrics - * @name BASELINE_MULTIPLIER - * @type {number} - * @default 1.4 - */ -TextMetrics.BASELINE_MULTIPLIER = 1.4; - -/** - * Cache of new line chars. - * - * @memberof PIXI.TextMetrics - * @type {number[]} - * @private - */ -TextMetrics._newlines = [ - 0x000A, // line feed - 0x000D ]; - -/** - * Cache of breaking spaces. - * - * @memberof PIXI.TextMetrics - * @type {number[]} - * @private - */ -TextMetrics._breakingSpaces = [ - 0x0009, // character tabulation - 0x0020, // space - 0x2000, // en quad - 0x2001, // em quad - 0x2002, // en space - 0x2003, // em space - 0x2004, // three-per-em space - 0x2005, // four-per-em space - 0x2006, // six-per-em space - 0x2008, // punctuation space - 0x2009, // thin space - 0x200A, // hair space - 0x205F, // medium mathematical space - 0x3000 ]; - -/** - * A number, or a string containing a number. - * - * @memberof PIXI - * @typedef IFontMetrics - * @property {number} ascent - Font ascent - * @property {number} descent - Font descent - * @property {number} fontSize - Font size - */ - -/* eslint max-depth: [2, 8] */ - -var defaultDestroyOptions = { - texture: true, - children: false, - baseTexture: true, -}; - -/** - * A Text Object will create a line or multiple lines of text. - * - * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). - * - * The primary advantage of this class over BitmapText is that you have great control over the style of the next, - * which you can change at runtime. - * - * The primary disadvantages is that each piece of text has it's own texture, which can use more memory. - * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time. - * - * To split a line you can use '\n' in your text string, or, on the `style` object, - * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value. - * - * A Text can be created directly from a string and a style object, - * which can be generated [here](https://pixijs.io/pixi-text-style). - * - * ```js - * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); - * ``` - * - * @class - * @extends PIXI.Sprite - * @memberof PIXI - */ -var Text = /*@__PURE__*/(function (Sprite) { - function Text(text, style, canvas) - { - canvas = canvas || document.createElement('canvas'); - - canvas.width = 3; - canvas.height = 3; - - var texture = core.Texture.from(canvas); - - texture.orig = new math.Rectangle(); - texture.trim = new math.Rectangle(); - - Sprite.call(this, texture); - - /** - * The canvas element that everything is drawn to - * - * @member {HTMLCanvasElement} - */ - this.canvas = canvas; - - /** - * The canvas 2d context that everything is drawn with - * @member {CanvasRenderingContext2D} - */ - this.context = this.canvas.getContext('2d'); - - /** - * The resolution / device pixel ratio of the canvas. - * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. - * @member {number} - * @default 1 - */ - this._resolution = settings.settings.RESOLUTION; - this._autoResolution = true; - - /** - * Private tracker for the current text. - * - * @member {string} - * @private - */ - this._text = null; - - /** - * Private tracker for the current style. - * - * @member {object} - * @private - */ - this._style = null; - /** - * Private listener to track style changes. - * - * @member {Function} - * @private - */ - this._styleListener = null; - - /** - * Private tracker for the current font. - * - * @member {string} - * @private - */ - this._font = ''; - - this.text = text; - this.style = style; - - this.localStyleID = -1; - } - - if ( Sprite ) Text.__proto__ = Sprite; - Text.prototype = Object.create( Sprite && Sprite.prototype ); - Text.prototype.constructor = Text; - - var prototypeAccessors = { width: { configurable: true },height: { configurable: true },style: { configurable: true },text: { configurable: true },resolution: { configurable: true } }; - - /** - * Renders text and updates it when needed. - * - * @private - * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. - */ - Text.prototype.updateText = function updateText (respectDirty) - { - var style = this._style; - - // check if style has changed.. - if (this.localStyleID !== style.styleID) - { - this.dirty = true; - this.localStyleID = style.styleID; - } - - if (!this.dirty && respectDirty) - { - return; - } - - this._font = this._style.toFontString(); - - var context = this.context; - var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas); - var width = measured.width; - var height = measured.height; - var lines = measured.lines; - var lineHeight = measured.lineHeight; - var lineWidths = measured.lineWidths; - var maxLineWidth = measured.maxLineWidth; - var fontProperties = measured.fontProperties; - - this.canvas.width = Math.ceil((Math.max(1, width) + (style.padding * 2)) * this._resolution); - this.canvas.height = Math.ceil((Math.max(1, height) + (style.padding * 2)) * this._resolution); - - context.scale(this._resolution, this._resolution); - - context.clearRect(0, 0, this.canvas.width, this.canvas.height); - - context.font = this._font; - context.lineWidth = style.strokeThickness; - context.textBaseline = style.textBaseline; - context.lineJoin = style.lineJoin; - context.miterLimit = style.miterLimit; - - var linePositionX; - var linePositionY; - - // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text - var passesCount = style.dropShadow ? 2 : 1; - - // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex, - // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow. - // - // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more - // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill - // and the stroke; and fill drop shadows would appear over the top of the stroke. - // - // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal - // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the - // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow - // beneath the text, whilst also having the proper text shadow styling. - for (var i = 0; i < passesCount; ++i) - { - var isShadowPass = style.dropShadow && i === 0; - var dsOffsetText = isShadowPass ? height * 2 : 0; // we only want the drop shadow, so put text way off-screen - var dsOffsetShadow = dsOffsetText * this.resolution; - - if (isShadowPass) - { - // On Safari, text with gradient and drop shadows together do not position correctly - // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689 - // Therefore we'll set the styles to be a plain black whilst generating this drop shadow - context.fillStyle = 'black'; - context.strokeStyle = 'black'; - - var dropShadowColor = style.dropShadowColor; - var rgb = utils.hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : utils.string2hex(dropShadowColor)); - - context.shadowColor = "rgba(" + (rgb[0] * 255) + "," + (rgb[1] * 255) + "," + (rgb[2] * 255) + "," + (style.dropShadowAlpha) + ")"; - context.shadowBlur = style.dropShadowBlur; - context.shadowOffsetX = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; - context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * style.dropShadowDistance) + dsOffsetShadow; - } - else - { - // set canvas text styles - context.fillStyle = this._generateFillStyle(style, lines); - context.strokeStyle = style.stroke; - - context.shadowColor = 0; - context.shadowBlur = 0; - context.shadowOffsetX = 0; - context.shadowOffsetY = 0; - } - - // draw lines line by line - for (var i$1 = 0; i$1 < lines.length; i$1++) - { - linePositionX = style.strokeThickness / 2; - linePositionY = ((style.strokeThickness / 2) + (i$1 * lineHeight)) + fontProperties.ascent; - - if (style.align === 'right') - { - linePositionX += maxLineWidth - lineWidths[i$1]; - } - else if (style.align === 'center') - { - linePositionX += (maxLineWidth - lineWidths[i$1]) / 2; - } - - if (style.stroke && style.strokeThickness) - { - this.drawLetterSpacing( - lines[i$1], - linePositionX + style.padding, - linePositionY + style.padding - dsOffsetText, - true - ); - } - - if (style.fill) - { - this.drawLetterSpacing( - lines[i$1], - linePositionX + style.padding, - linePositionY + style.padding - dsOffsetText - ); - } - } - } - - this.updateTexture(); - }; - - /** - * Render the text with letter-spacing. - * @param {string} text - The text to draw - * @param {number} x - Horizontal position to draw the text - * @param {number} y - Vertical position to draw the text - * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the - * text? If not, it's for the inside fill - * @private - */ - Text.prototype.drawLetterSpacing = function drawLetterSpacing (text, x, y, isStroke) - { - if ( isStroke === void 0 ) isStroke = false; - - var style = this._style; - - // letterSpacing of 0 means normal - var letterSpacing = style.letterSpacing; - - if (letterSpacing === 0) - { - if (isStroke) - { - this.context.strokeText(text, x, y); - } - else - { - this.context.fillText(text, x, y); - } - - return; - } - - var currentPosition = x; - - // Using Array.from correctly splits characters whilst keeping emoji together. - // This is not supported on IE as it requires ES6, so regular text splitting occurs. - // This also doesn't account for emoji that are multiple emoji put together to make something else. - // Handling all of this would require a big library itself. - // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516 - // https://github.com/orling/grapheme-splitter - var stringArray = Array.from ? Array.from(text) : text.split(''); - var previousWidth = this.context.measureText(text).width; - var currentWidth = 0; - - for (var i = 0; i < stringArray.length; ++i) - { - var currentChar = stringArray[i]; - - if (isStroke) - { - this.context.strokeText(currentChar, currentPosition, y); - } - else - { - this.context.fillText(currentChar, currentPosition, y); - } - currentWidth = this.context.measureText(text.substring(i + 1)).width; - currentPosition += previousWidth - currentWidth + letterSpacing; - previousWidth = currentWidth; - } - }; - - /** - * Updates texture size based on canvas size - * - * @private - */ - Text.prototype.updateTexture = function updateTexture () - { - var canvas = this.canvas; - - if (this._style.trim) - { - var trimmed = utils.trimCanvas(canvas); - - if (trimmed.data) - { - canvas.width = trimmed.width; - canvas.height = trimmed.height; - this.context.putImageData(trimmed.data, 0, 0); - } - } - - var texture = this._texture; - var style = this._style; - var padding = style.trim ? 0 : style.padding; - var baseTexture = texture.baseTexture; - - texture.trim.width = texture._frame.width = Math.ceil(canvas.width / this._resolution); - texture.trim.height = texture._frame.height = Math.ceil(canvas.height / this._resolution); - texture.trim.x = -padding; - texture.trim.y = -padding; - - texture.orig.width = texture._frame.width - (padding * 2); - texture.orig.height = texture._frame.height - (padding * 2); - - // call sprite onTextureUpdate to update scale if _width or _height were set - this._onTextureUpdate(); - - baseTexture.setRealSize(canvas.width, canvas.height, this._resolution); - - this.dirty = false; - }; - - /** - * Renders the object using the WebGL renderer - * - * @private - * @param {PIXI.Renderer} renderer - The renderer - */ - Text.prototype._render = function _render (renderer) - { - if (this._autoResolution && this._resolution !== renderer.resolution) - { - this._resolution = renderer.resolution; - this.dirty = true; - } - - this.updateText(true); - - Sprite.prototype._render.call(this, renderer); - }; - - /** - * Gets the local bounds of the text object. - * - * @param {PIXI.Rectangle} rect - The output rectangle. - * @return {PIXI.Rectangle} The bounds. - */ - Text.prototype.getLocalBounds = function getLocalBounds (rect) - { - this.updateText(true); - - return Sprite.prototype.getLocalBounds.call(this, rect); - }; - - /** - * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. - * @protected - */ - Text.prototype._calculateBounds = function _calculateBounds () - { - this.updateText(true); - this.calculateVertices(); - // if we have already done this on THIS frame. - this._bounds.addQuad(this.vertexData); - }; - - /** - * Method to be called upon a TextStyle change. - * @private - */ - Text.prototype._onStyleChange = function _onStyleChange () - { - this.dirty = true; - }; - - /** - * Generates the fill style. Can automatically generate a gradient based on the fill style being an array - * - * @private - * @param {object} style - The style. - * @param {string[]} lines - The lines of text. - * @return {string|number|CanvasGradient} The fill style - */ - Text.prototype._generateFillStyle = function _generateFillStyle (style, lines) - { - if (!Array.isArray(style.fill)) - { - return style.fill; - } - else if (style.fill.length === 1) - { - return style.fill[0]; - } - - // the gradient will be evenly spaced out according to how large the array is. - // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 - var gradient; - var totalIterations; - var currentIteration; - var stop; - - var width = Math.ceil(this.canvas.width / this._resolution); - var height = Math.ceil(this.canvas.height / this._resolution); - - // make a copy of the style settings, so we can manipulate them later - var fill = style.fill.slice(); - var fillGradientStops = style.fillGradientStops.slice(); - - // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 - if (!fillGradientStops.length) - { - var lengthPlus1 = fill.length + 1; - - for (var i = 1; i < lengthPlus1; ++i) - { - fillGradientStops.push(i / lengthPlus1); - } - } - - // stop the bleeding of the last gradient on the line above to the top gradient of the this line - // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 - fill.unshift(style.fill[0]); - fillGradientStops.unshift(0); - - fill.push(style.fill[style.fill.length - 1]); - fillGradientStops.push(1); - - if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL) - { - // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas - gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); - - // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect - // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 - totalIterations = (fill.length + 1) * lines.length; - currentIteration = 0; - for (var i$1 = 0; i$1 < lines.length; i$1++) - { - currentIteration += 1; - for (var j = 0; j < fill.length; j++) - { - if (typeof fillGradientStops[j] === 'number') - { - stop = (fillGradientStops[j] / lines.length) + (i$1 / lines.length); - } - else - { - stop = currentIteration / totalIterations; - } - gradient.addColorStop(stop, fill[j]); - currentIteration++; - } - } - } - else - { - // start the gradient at the center left of the canvas, and end at the center right of the canvas - gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); - - // can just evenly space out the gradients in this case, as multiple lines makes no difference - // to an even left to right gradient - totalIterations = fill.length + 1; - currentIteration = 1; - - for (var i$2 = 0; i$2 < fill.length; i$2++) - { - if (typeof fillGradientStops[i$2] === 'number') - { - stop = fillGradientStops[i$2]; - } - else - { - stop = currentIteration / totalIterations; - } - gradient.addColorStop(stop, fill[i$2]); - currentIteration++; - } - } - - return gradient; - }; - - /** - * Destroys this text object. - * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as - * the majority of the time the texture will not be shared with any other Sprites. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their - * destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well - */ - Text.prototype.destroy = function destroy (options) - { - if (typeof options === 'boolean') - { - options = { children: options }; - } - - options = Object.assign({}, defaultDestroyOptions, options); - - Sprite.prototype.destroy.call(this, options); - - // make sure to reset the the context and canvas.. dont want this hanging around in memory! - this.context = null; - this.canvas = null; - - this._style = null; - }; - - /** - * The width of the Text, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - prototypeAccessors.width.get = function () - { - this.updateText(true); - - return Math.abs(this.scale.x) * this._texture.orig.width; - }; - - prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc - { - this.updateText(true); - - var s = utils.sign(this.scale.x) || 1; - - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - }; - - /** - * The height of the Text, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - prototypeAccessors.height.get = function () - { - this.updateText(true); - - return Math.abs(this.scale.y) * this._texture.orig.height; - }; - - prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc - { - this.updateText(true); - - var s = utils.sign(this.scale.y) || 1; - - this.scale.y = s * value / this._texture.orig.height; - this._height = value; - }; - - /** - * Set the style of the text. Set up an event listener to listen for changes on the style - * object and mark the text as dirty. - * - * @member {object|PIXI.TextStyle} - */ - prototypeAccessors.style.get = function () - { - return this._style; - }; - - prototypeAccessors.style.set = function (style) // eslint-disable-line require-jsdoc - { - style = style || {}; - - if (style instanceof TextStyle) - { - this._style = style; - } - else - { - this._style = new TextStyle(style); - } - - this.localStyleID = -1; - this.dirty = true; - }; - - /** - * Set the copy for the text object. To split a line you can use '\n'. - * - * @member {string} - */ - prototypeAccessors.text.get = function () - { - return this._text; - }; - - prototypeAccessors.text.set = function (text) // eslint-disable-line require-jsdoc - { - text = String(text === null || text === undefined ? '' : text); - - if (this._text === text) - { - return; - } - this._text = text; - this.dirty = true; - }; - - /** - * The resolution / device pixel ratio of the canvas. - * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. - * @member {number} - * @default 1 - */ - prototypeAccessors.resolution.get = function () - { - return this._resolution; - }; - - prototypeAccessors.resolution.set = function (value) // eslint-disable-line require-jsdoc - { - this._autoResolution = false; - - if (this._resolution === value) - { - return; - } - - this._resolution = value; - this.dirty = true; - }; - - Object.defineProperties( Text.prototype, prototypeAccessors ); - - return Text; -}(sprite.Sprite)); - -exports.TEXT_GRADIENT = TEXT_GRADIENT; -exports.Text = Text; -exports.TextMetrics = TextMetrics; -exports.TextStyle = TextStyle; - - -},{"@pixi/core":17,"@pixi/math":29,"@pixi/settings":39,"@pixi/sprite":42,"@pixi/utils":47}],46:[function(require,module,exports){ -/*! - * @pixi/ticker - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/ticker is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var settings = require('@pixi/settings'); - -/** - * Target frames per millisecond. - * - * @static - * @name TARGET_FPMS - * @memberof PIXI.settings - * @type {number} - * @default 0.06 - */ -settings.settings.TARGET_FPMS = 0.06; - -/** - * Represents the update priorities used by internal PIXI classes when registered with - * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower - * priority items, such as render, should go later. - * - * @static - * @constant - * @name UPDATE_PRIORITY - * @memberof PIXI - * @enum {number} - * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} - * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite} - * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.Ticker#add}. - * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. - * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. - */ -(function (UPDATE_PRIORITY) { - UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION"; - UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH"; - UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL"; - UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW"; - UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY"; -})(exports.UPDATE_PRIORITY || (exports.UPDATE_PRIORITY = {})); - -/** - * Internal class for handling the priority sorting of ticker handlers. - * - * @private - * @class - * @memberof PIXI - */ -var TickerListener = /** @class */ (function () { - /** - * Constructor - * @private - * @param {Function} fn - The listener function to be added for one update - * @param {*} [context=null] - The listener context - * @param {number} [priority=0] - The priority for emitting - * @param {boolean} [once=false] - If the handler should fire once - */ - function TickerListener(fn, context, priority, once) { - if (context === void 0) { context = null; } - if (priority === void 0) { priority = 0; } - if (once === void 0) { once = false; } - /** - * The handler function to execute. - * @private - * @member {Function} - */ - this.fn = fn; - /** - * The calling to execute. - * @private - * @member {*} - */ - this.context = context; - /** - * The current priority. - * @private - * @member {number} - */ - this.priority = priority; - /** - * If this should only execute once. - * @private - * @member {boolean} - */ - this.once = once; - /** - * The next item in chain. - * @private - * @member {TickerListener} - */ - this.next = null; - /** - * The previous item in chain. - * @private - * @member {TickerListener} - */ - this.previous = null; - /** - * `true` if this listener has been destroyed already. - * @member {boolean} - * @private - */ - this._destroyed = false; - } - /** - * Simple compare function to figure out if a function and context match. - * @private - * @param {Function} fn - The listener function to be added for one update - * @param {any} [context] - The listener context - * @return {boolean} `true` if the listener match the arguments - */ - TickerListener.prototype.match = function (fn, context) { - if (context === void 0) { context = null; } - return this.fn === fn && this.context === context; - }; - /** - * Emit by calling the current function. - * @private - * @param {number} deltaTime - time since the last emit. - * @return {TickerListener} Next ticker - */ - TickerListener.prototype.emit = function (deltaTime) { - if (this.fn) { - if (this.context) { - this.fn.call(this.context, deltaTime); - } - else { - this.fn(deltaTime); - } - } - var redirect = this.next; - if (this.once) { - this.destroy(true); - } - // Soft-destroying should remove - // the next reference - if (this._destroyed) { - this.next = null; - } - return redirect; - }; - /** - * Connect to the list. - * @private - * @param {TickerListener} previous - Input node, previous listener - */ - TickerListener.prototype.connect = function (previous) { - this.previous = previous; - if (previous.next) { - previous.next.previous = this; - } - this.next = previous.next; - previous.next = this; - }; - /** - * Destroy and don't use after this. - * @private - * @param {boolean} [hard = false] `true` to remove the `next` reference, this - * is considered a hard destroy. Soft destroy maintains the next reference. - * @return {TickerListener} The listener to redirect while emitting or removing. - */ - TickerListener.prototype.destroy = function (hard) { - if (hard === void 0) { hard = false; } - this._destroyed = true; - this.fn = null; - this.context = null; - // Disconnect, hook up next and previous - if (this.previous) { - this.previous.next = this.next; - } - if (this.next) { - this.next.previous = this.previous; - } - // Redirect to the next item - var redirect = this.next; - // Remove references - this.next = hard ? null : redirect; - this.previous = null; - return redirect; - }; - return TickerListener; -}()); - -/** - * A Ticker class that runs an update loop that other objects listen to. - * - * This class is composed around listeners meant for execution on the next requested animation frame. - * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners. - * - * @class - * @memberof PIXI - */ -var Ticker = /** @class */ (function () { - function Ticker() { - var _this = this; - /** - * The first listener. All new listeners added are chained on this. - * @private - * @type {TickerListener} - */ - this._head = new TickerListener(null, null, Infinity); - /** - * Internal current frame request ID - * @type {?number} - * @private - */ - this._requestId = null; - /** - * Internal value managed by minFPS property setter and getter. - * This is the maximum allowed milliseconds between updates. - * @type {number} - * @private - */ - this._maxElapsedMS = 100; - /** - * Internal value managed by maxFPS property setter and getter. - * This is the minimum allowed milliseconds between updates. - * @type {number} - * @private - */ - this._minElapsedMS = 0; - /** - * Whether or not this ticker should invoke the method - * {@link PIXI.Ticker#start} automatically - * when a listener is added. - * - * @member {boolean} - * @default false - */ - this.autoStart = false; - /** - * Scalar time value from last frame to this frame. - * This value is capped by setting {@link PIXI.Ticker#minFPS} - * and is scaled with {@link PIXI.Ticker#speed}. - * **Note:** The cap may be exceeded by scaling. - * - * @member {number} - * @default 1 - */ - this.deltaTime = 1; - /** - * Scaler time elapsed in milliseconds from last frame to this frame. - * This value is capped by setting {@link PIXI.Ticker#minFPS} - * and is scaled with {@link PIXI.Ticker#speed}. - * **Note:** The cap may be exceeded by scaling. - * If the platform supports DOMHighResTimeStamp, - * this value will have a precision of 1 µs. - * Defaults to target frame time - * - * @member {number} - * @default 16.66 - */ - this.deltaMS = 1 / settings.settings.TARGET_FPMS; - /** - * Time elapsed in milliseconds from last frame to this frame. - * Opposed to what the scalar {@link PIXI.Ticker#deltaTime} - * is based, this value is neither capped nor scaled. - * If the platform supports DOMHighResTimeStamp, - * this value will have a precision of 1 µs. - * Defaults to target frame time - * - * @member {number} - * @default 16.66 - */ - this.elapsedMS = 1 / settings.settings.TARGET_FPMS; - /** - * The last time {@link PIXI.Ticker#update} was invoked. - * This value is also reset internally outside of invoking - * update, but only when a new animation frame is requested. - * If the platform supports DOMHighResTimeStamp, - * this value will have a precision of 1 µs. - * - * @member {number} - * @default -1 - */ - this.lastTime = -1; - /** - * Factor of current {@link PIXI.Ticker#deltaTime}. - * @example - * // Scales ticker.deltaTime to what would be - * // the equivalent of approximately 120 FPS - * ticker.speed = 2; - * - * @member {number} - * @default 1 - */ - this.speed = 1; - /** - * Whether or not this ticker has been started. - * `true` if {@link PIXI.Ticker#start} has been called. - * `false` if {@link PIXI.Ticker#stop} has been called. - * While `false`, this value may change to `true` in the - * event of {@link PIXI.Ticker#autoStart} being `true` - * and a listener is added. - * - * @member {boolean} - * @default false - */ - this.started = false; - /** - * If enabled, deleting is disabled. - * @member {boolean} - * @default false - * @private - */ - this._protected = false; - /** - * The last time keyframe was executed. - * Maintains a relatively fixed interval with the previous value. - * @member {number} - * @default -1 - * @private - */ - this._lastFrame = -1; - /** - * Internal tick method bound to ticker instance. - * This is because in early 2015, Function.bind - * is still 60% slower in high performance scenarios. - * Also separating frame requests from update method - * so listeners may be called at any time and with - * any animation API, just invoke ticker.update(time). - * - * @private - * @param {number} time - Time since last tick. - */ - this._tick = function (time) { - _this._requestId = null; - if (_this.started) { - // Invoke listeners now - _this.update(time); - // Listener side effects may have modified ticker state. - if (_this.started && _this._requestId === null && _this._head.next) { - _this._requestId = requestAnimationFrame(_this._tick); - } - } - }; - } - /** - * Conditionally requests a new animation frame. - * If a frame has not already been requested, and if the internal - * emitter has listeners, a new frame is requested. - * - * @private - */ - Ticker.prototype._requestIfNeeded = function () { - if (this._requestId === null && this._head.next) { - // ensure callbacks get correct delta - this.lastTime = performance.now(); - this._lastFrame = this.lastTime; - this._requestId = requestAnimationFrame(this._tick); - } - }; - /** - * Conditionally cancels a pending animation frame. - * - * @private - */ - Ticker.prototype._cancelIfNeeded = function () { - if (this._requestId !== null) { - cancelAnimationFrame(this._requestId); - this._requestId = null; - } - }; - /** - * Conditionally requests a new animation frame. - * If the ticker has been started it checks if a frame has not already - * been requested, and if the internal emitter has listeners. If these - * conditions are met, a new frame is requested. If the ticker has not - * been started, but autoStart is `true`, then the ticker starts now, - * and continues with the previous conditions to request a new frame. - * - * @private - */ - Ticker.prototype._startIfPossible = function () { - if (this.started) { - this._requestIfNeeded(); - } - else if (this.autoStart) { - this.start(); - } - }; - /** - * Register a handler for tick events. Calls continuously unless - * it is removed or the ticker is stopped. - * - * @param {Function} fn - The listener function to be added for updates - * @param {*} [context] - The listener context - * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting - * @returns {PIXI.Ticker} This instance of a ticker - */ - Ticker.prototype.add = function (fn, context, priority) { - if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } - return this._addListener(new TickerListener(fn, context, priority)); - }; - /** - * Add a handler for the tick event which is only execute once. - * - * @param {Function} fn - The listener function to be added for one update - * @param {*} [context] - The listener context - * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting - * @returns {PIXI.Ticker} This instance of a ticker - */ - Ticker.prototype.addOnce = function (fn, context, priority) { - if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } - return this._addListener(new TickerListener(fn, context, priority, true)); - }; - /** - * Internally adds the event handler so that it can be sorted by priority. - * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run - * before the rendering. - * - * @private - * @param {TickerListener} listener - Current listener being added. - * @returns {PIXI.Ticker} This instance of a ticker - */ - Ticker.prototype._addListener = function (listener) { - // For attaching to head - var current = this._head.next; - var previous = this._head; - // Add the first item - if (!current) { - listener.connect(previous); - } - else { - // Go from highest to lowest priority - while (current) { - if (listener.priority > current.priority) { - listener.connect(previous); - break; - } - previous = current; - current = current.next; - } - // Not yet connected - if (!listener.previous) { - listener.connect(previous); - } - } - this._startIfPossible(); - return this; - }; - /** - * Removes any handlers matching the function and context parameters. - * If no handlers are left after removing, then it cancels the animation frame. - * - * @param {Function} fn - The listener function to be removed - * @param {*} [context] - The listener context to be removed - * @returns {PIXI.Ticker} This instance of a ticker - */ - Ticker.prototype.remove = function (fn, context) { - var listener = this._head.next; - while (listener) { - // We found a match, lets remove it - // no break to delete all possible matches - // incase a listener was added 2+ times - if (listener.match(fn, context)) { - listener = listener.destroy(); - } - else { - listener = listener.next; - } - } - if (!this._head.next) { - this._cancelIfNeeded(); - } - return this; - }; - /** - * Starts the ticker. If the ticker has listeners - * a new animation frame is requested at this point. - */ - Ticker.prototype.start = function () { - if (!this.started) { - this.started = true; - this._requestIfNeeded(); - } - }; - /** - * Stops the ticker. If the ticker has requested - * an animation frame it is canceled at this point. - */ - Ticker.prototype.stop = function () { - if (this.started) { - this.started = false; - this._cancelIfNeeded(); - } - }; - /** - * Destroy the ticker and don't use after this. Calling - * this method removes all references to internal events. - */ - Ticker.prototype.destroy = function () { - if (!this._protected) { - this.stop(); - var listener = this._head.next; - while (listener) { - listener = listener.destroy(true); - } - this._head.destroy(); - this._head = null; - } - }; - /** - * Triggers an update. An update entails setting the - * current {@link PIXI.Ticker#elapsedMS}, - * the current {@link PIXI.Ticker#deltaTime}, - * invoking all listeners with current deltaTime, - * and then finally setting {@link PIXI.Ticker#lastTime} - * with the value of currentTime that was provided. - * This method will be called automatically by animation - * frame callbacks if the ticker instance has been started - * and listeners are added. - * - * @param {number} [currentTime=performance.now()] - the current time of execution - */ - Ticker.prototype.update = function (currentTime) { - if (currentTime === void 0) { currentTime = performance.now(); } - var elapsedMS; - // If the difference in time is zero or negative, we ignore most of the work done here. - // If there is no valid difference, then should be no reason to let anyone know about it. - // A zero delta, is exactly that, nothing should update. - // - // The difference in time can be negative, and no this does not mean time traveling. - // This can be the result of a race condition between when an animation frame is requested - // on the current JavaScript engine event loop, and when the ticker's start method is invoked - // (which invokes the internal _requestIfNeeded method). If a frame is requested before - // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, - // can receive a time argument that can be less than the lastTime value that was set within - // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. - // - // This check covers this browser engine timing issue, as well as if consumers pass an invalid - // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. - if (currentTime > this.lastTime) { - // Save uncapped elapsedMS for measurement - elapsedMS = this.elapsedMS = currentTime - this.lastTime; - // cap the milliseconds elapsed used for deltaTime - if (elapsedMS > this._maxElapsedMS) { - elapsedMS = this._maxElapsedMS; - } - elapsedMS *= this.speed; - // If not enough time has passed, exit the function. - // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS - // adjustment to ensure a relatively stable interval. - if (this._minElapsedMS) { - var delta = currentTime - this._lastFrame | 0; - if (delta < this._minElapsedMS) { - return; - } - this._lastFrame = currentTime - (delta % this._minElapsedMS); - } - this.deltaMS = elapsedMS; - this.deltaTime = this.deltaMS * settings.settings.TARGET_FPMS; - // Cache a local reference, in-case ticker is destroyed - // during the emit, we can still check for head.next - var head = this._head; - // Invoke listeners added to internal emitter - var listener = head.next; - while (listener) { - listener = listener.emit(this.deltaTime); - } - if (!head.next) { - this._cancelIfNeeded(); - } - } - else { - this.deltaTime = this.deltaMS = this.elapsedMS = 0; - } - this.lastTime = currentTime; - }; - Object.defineProperty(Ticker.prototype, "FPS", { - /** - * The frames per second at which this ticker is running. - * The default is approximately 60 in most modern browsers. - * **Note:** This does not factor in the value of - * {@link PIXI.Ticker#speed}, which is specific - * to scaling {@link PIXI.Ticker#deltaTime}. - * - * @member {number} - * @readonly - */ - get: function () { - return 1000 / this.elapsedMS; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Ticker.prototype, "minFPS", { - /** - * Manages the maximum amount of milliseconds allowed to - * elapse between invoking {@link PIXI.Ticker#update}. - * This value is used to cap {@link PIXI.Ticker#deltaTime}, - * but does not effect the measured value of {@link PIXI.Ticker#FPS}. - * When setting this property it is clamped to a value between - * `0` and `PIXI.settings.TARGET_FPMS * 1000`. - * - * @member {number} - * @default 10 - */ - get: function () { - return 1000 / this._maxElapsedMS; - }, - set: function (fps) { - // Minimum must be below the maxFPS - var minFPS = Math.min(this.maxFPS, fps); - // Must be at least 0, but below 1 / settings.TARGET_FPMS - var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings.settings.TARGET_FPMS); - this._maxElapsedMS = 1 / minFPMS; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Ticker.prototype, "maxFPS", { - /** - * Manages the minimum amount of milliseconds required to - * elapse between invoking {@link PIXI.Ticker#update}. - * This will effect the measured value of {@link PIXI.Ticker#FPS}. - * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can. - * Otherwise it will be at least `minFPS` - * - * @member {number} - * @default 0 - */ - get: function () { - if (this._minElapsedMS) { - return Math.round(1000 / this._minElapsedMS); - } - return 0; - }, - set: function (fps) { - if (fps === 0) { - this._minElapsedMS = 0; - } - else { - // Max must be at least the minFPS - var maxFPS = Math.max(this.minFPS, fps); - this._minElapsedMS = 1 / (maxFPS / 1000); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Ticker, "shared", { - /** - * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by - * {@link PIXI.VideoResource} to update animation frames / video textures. - * - * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true. - * - * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. - * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker. - * - * @example - * let ticker = PIXI.Ticker.shared; - * // Set this to prevent starting this ticker when listeners are added. - * // By default this is true only for the PIXI.Ticker.shared instance. - * ticker.autoStart = false; - * // FYI, call this to ensure the ticker is stopped. It should be stopped - * // if you have not attempted to render anything yet. - * ticker.stop(); - * // Call this when you are ready for a running shared ticker. - * ticker.start(); - * - * @example - * // You may use the shared ticker to render... - * let renderer = PIXI.autoDetectRenderer(); - * let stage = new PIXI.Container(); - * document.body.appendChild(renderer.view); - * ticker.add(function (time) { - * renderer.render(stage); - * }); - * - * @example - * // Or you can just update it manually. - * ticker.autoStart = false; - * ticker.stop(); - * function animate(time) { - * ticker.update(time); - * renderer.render(stage); - * requestAnimationFrame(animate); - * } - * animate(performance.now()); - * - * @member {PIXI.Ticker} - * @static - */ - get: function () { - if (!Ticker._shared) { - var shared = Ticker._shared = new Ticker(); - shared.autoStart = true; - shared._protected = true; - } - return Ticker._shared; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Ticker, "system", { - /** - * The system ticker instance used by {@link PIXI.interaction.InteractionManager} and by - * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused, - * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused. - * - * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. - * - * @member {PIXI.Ticker} - * @static - */ - get: function () { - if (!Ticker._system) { - var system = Ticker._system = new Ticker(); - system.autoStart = true; - system._protected = true; - } - return Ticker._system; - }, - enumerable: true, - configurable: true - }); - return Ticker; -}()); - -/** - * Middleware for for Application Ticker. - * - * @example - * import {TickerPlugin} from '@pixi/ticker'; - * import {Application} from '@pixi/app'; - * Application.registerPlugin(TickerPlugin); - * - * @class - * @memberof PIXI - */ -var TickerPlugin = /** @class */ (function () { - function TickerPlugin() { - } - /** - * Initialize the plugin with scope of application instance - * - * @static - * @private - * @param {object} [options] - See application options - */ - TickerPlugin.init = function (options) { - var _this = this; - // Set default - options = Object.assign({ - autoStart: true, - sharedTicker: false, - }, options); - // Create ticker setter - Object.defineProperty(this, 'ticker', { - set: function (ticker) { - if (this._ticker) { - this._ticker.remove(this.render, this); - } - this._ticker = ticker; - if (ticker) { - ticker.add(this.render, this, exports.UPDATE_PRIORITY.LOW); - } - }, - get: function () { - return this._ticker; - }, - }); - /** - * Convenience method for stopping the render. - * - * @method PIXI.Application#stop - */ - this.stop = function () { - _this._ticker.stop(); - }; - /** - * Convenience method for starting the render. - * - * @method PIXI.Application#start - */ - this.start = function () { - _this._ticker.start(); - }; - /** - * Internal reference to the ticker. - * - * @type {PIXI.Ticker} - * @name _ticker - * @memberof PIXI.Application# - * @private - */ - this._ticker = null; - /** - * Ticker for doing render updates. - * - * @type {PIXI.Ticker} - * @name ticker - * @memberof PIXI.Application# - * @default PIXI.Ticker.shared - */ - this.ticker = options.sharedTicker ? Ticker.shared : new Ticker(); - // Start the rendering - if (options.autoStart) { - this.start(); - } - }; - /** - * Clean up the ticker, scoped to application. - * - * @static - * @private - */ - TickerPlugin.destroy = function () { - if (this._ticker) { - var oldTicker = this._ticker; - this.ticker = null; - oldTicker.destroy(); - } - }; - return TickerPlugin; -}()); - -exports.Ticker = Ticker; -exports.TickerPlugin = TickerPlugin; - - -},{"@pixi/settings":39}],47:[function(require,module,exports){ -/*! - * @pixi/utils - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC - * - * @pixi/utils is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var settings = require('@pixi/settings'); -var eventemitter3 = _interopDefault(require('eventemitter3')); -var earcut = _interopDefault(require('earcut')); -var _url = _interopDefault(require('url')); -var constants = require('@pixi/constants'); - -/** - * The prefix that denotes a URL is for a retina asset. - * - * @static - * @name RETINA_PREFIX - * @memberof PIXI.settings - * @type {RegExp} - * @default /@([0-9\.]+)x/ - * @example `@2x` - */ -settings.settings.RETINA_PREFIX = /@([0-9\.]+)x/; - -/** - * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. - * For most scenarios this should be left as true, as otherwise the user may have a poor experience. - * However, it can be useful to disable under certain scenarios, such as headless unit tests. - * - * @static - * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT - * @memberof PIXI.settings - * @type {boolean} - * @default true - */ -settings.settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = true; - -var saidHello = false; -var VERSION = '5.2.0'; - -/** - * Skips the hello message of renderers that are created after this is run. - * - * @function skipHello - * @memberof PIXI.utils - */ -function skipHello() -{ - saidHello = true; -} - -/** - * Logs out the version and renderer information for this running instance of PIXI. - * If you don't want to see this message you can run `PIXI.utils.skipHello()` before - * creating your renderer. Keep in mind that doing that will forever make you a jerk face. - * - * @static - * @function sayHello - * @memberof PIXI.utils - * @param {string} type - The string renderer type to log. - */ -function sayHello(type) -{ - if (saidHello) - { - return; - } - - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) - { - var args = [ - ("\n %c %c %c PixiJS " + VERSION + " - ✰ " + type + " ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n"), - 'background: #ff66a5; padding:5px 0;', - 'background: #ff66a5; padding:5px 0;', - 'color: #ff66a5; background: #030307; padding:5px 0;', - 'background: #ff66a5; padding:5px 0;', - 'background: #ffc3dc; padding:5px 0;', - 'background: #ff66a5; padding:5px 0;', - 'color: #ff2424; background: #fff; padding:5px 0;', - 'color: #ff2424; background: #fff; padding:5px 0;', - 'color: #ff2424; background: #fff; padding:5px 0;' ]; - - window.console.log.apply(console, args); - } - else if (window.console) - { - window.console.log(("PixiJS " + VERSION + " - " + type + " - http://www.pixijs.com/")); - } - - saidHello = true; -} - -var supported; - -/** - * Helper for checking for WebGL support. - * - * @memberof PIXI.utils - * @function isWebGLSupported - * @return {boolean} Is WebGL supported. - */ -function isWebGLSupported() -{ - if (typeof supported === 'undefined') - { - supported = (function supported() - { - var contextOptions = { - stencil: true, - failIfMajorPerformanceCaveat: settings.settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT, - }; - - try - { - if (!window.WebGLRenderingContext) - { - return false; - } - - var canvas = document.createElement('canvas'); - var gl = canvas.getContext('webgl', contextOptions) - || canvas.getContext('experimental-webgl', contextOptions); - - var success = !!(gl && gl.getContextAttributes().stencil); - - if (gl) - { - var loseContext = gl.getExtension('WEBGL_lose_context'); - - if (loseContext) - { - loseContext.loseContext(); - } - } - - gl = null; - - return success; - } - catch (e) - { - return false; - } - })(); - } - - return supported; -} - -/** - * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0). - * - * @example - * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1] - * @memberof PIXI.utils - * @function hex2rgb - * @param {number} hex - The hexadecimal number to convert - * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one - * @return {number[]} An array representing the [R, G, B] of the color where all values are floats. - */ -function hex2rgb(hex, out) -{ - out = out || []; - - out[0] = ((hex >> 16) & 0xFF) / 255; - out[1] = ((hex >> 8) & 0xFF) / 255; - out[2] = (hex & 0xFF) / 255; - - return out; -} - -/** - * Converts a hexadecimal color number to a string. - * - * @example - * PIXI.utils.hex2string(0xffffff); // returns "#ffffff" - * @memberof PIXI.utils - * @function hex2string - * @param {number} hex - Number in hex (e.g., `0xffffff`) - * @return {string} The string color (e.g., `"#ffffff"`). - */ -function hex2string(hex) -{ - hex = hex.toString(16); - hex = '000000'.substr(0, 6 - hex.length) + hex; - - return ("#" + hex); -} - -/** - * Converts a hexadecimal string to a hexadecimal color number. - * - * @example - * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff - * @memberof PIXI.utils - * @function string2hex - * @param {string} The string color (e.g., `"#ffffff"`) - * @return {number} Number in hexadecimal. - */ -function string2hex(string) -{ - if (typeof string === 'string' && string[0] === '#') - { - string = string.substr(1); - } - - return parseInt(string, 16); -} - -/** - * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. - * - * @example - * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff - * @memberof PIXI.utils - * @function rgb2hex - * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. - * @return {number} Number in hexadecimal. - */ -function rgb2hex(rgb) -{ - return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0)); -} - -/** - * Corrects PixiJS blend, takes premultiplied alpha into account - * - * @memberof PIXI.utils - * @function mapPremultipliedBlendModes - * @private - * @param {Array} [array] - The array to output into. - * @return {Array} Mapped modes. - */ -function mapPremultipliedBlendModes() -{ - var pm = []; - var npm = []; - - for (var i = 0; i < 32; i++) - { - pm[i] = i; - npm[i] = i; - } - - pm[constants.BLEND_MODES.NORMAL_NPM] = constants.BLEND_MODES.NORMAL; - pm[constants.BLEND_MODES.ADD_NPM] = constants.BLEND_MODES.ADD; - pm[constants.BLEND_MODES.SCREEN_NPM] = constants.BLEND_MODES.SCREEN; - - npm[constants.BLEND_MODES.NORMAL] = constants.BLEND_MODES.NORMAL_NPM; - npm[constants.BLEND_MODES.ADD] = constants.BLEND_MODES.ADD_NPM; - npm[constants.BLEND_MODES.SCREEN] = constants.BLEND_MODES.SCREEN_NPM; - - var array = []; - - array.push(npm); - array.push(pm); - - return array; -} - -/** - * maps premultiply flag and blendMode to adjusted blendMode - * @memberof PIXI.utils - * @const premultiplyBlendMode - * @type {Array} - */ -var premultiplyBlendMode = mapPremultipliedBlendModes(); - -/** - * changes blendMode according to texture format - * - * @memberof PIXI.utils - * @function correctBlendMode - * @param {number} blendMode supposed blend mode - * @param {boolean} premultiplied whether source is premultiplied - * @returns {number} true blend mode for this texture - */ -function correctBlendMode(blendMode, premultiplied) -{ - return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; -} - -/** - * combines rgb and alpha to out array - * - * @memberof PIXI.utils - * @function premultiplyRgba - * @param {Float32Array|number[]} rgb input rgb - * @param {number} alpha alpha param - * @param {Float32Array} [out] output - * @param {boolean} [premultiply=true] do premultiply it - * @returns {Float32Array} vec4 rgba - */ -function premultiplyRgba(rgb, alpha, out, premultiply) -{ - out = out || new Float32Array(4); - if (premultiply || premultiply === undefined) - { - out[0] = rgb[0] * alpha; - out[1] = rgb[1] * alpha; - out[2] = rgb[2] * alpha; - } - else - { - out[0] = rgb[0]; - out[1] = rgb[1]; - out[2] = rgb[2]; - } - out[3] = alpha; - - return out; -} - -/** - * premultiplies tint - * - * @memberof PIXI.utils - * @function premultiplyTint - * @param {number} tint integer RGB - * @param {number} alpha floating point alpha (0.0-1.0) - * @returns {number} tint multiplied by alpha - */ -function premultiplyTint(tint, alpha) -{ - if (alpha === 1.0) - { - return (alpha * 255 << 24) + tint; - } - if (alpha === 0.0) - { - return 0; - } - var R = ((tint >> 16) & 0xFF); - var G = ((tint >> 8) & 0xFF); - var B = (tint & 0xFF); - - R = ((R * alpha) + 0.5) | 0; - G = ((G * alpha) + 0.5) | 0; - B = ((B * alpha) + 0.5) | 0; - - return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; -} - -/** - * converts integer tint and float alpha to vec4 form, premultiplies by default - * - * @memberof PIXI.utils - * @function premultiplyTintToRgba - * @param {number} tint input tint - * @param {number} alpha alpha param - * @param {Float32Array} [out] output - * @param {boolean} [premultiply=true] do premultiply it - * @returns {Float32Array} vec4 rgba - */ -function premultiplyTintToRgba(tint, alpha, out, premultiply) -{ - out = out || new Float32Array(4); - out[0] = ((tint >> 16) & 0xFF) / 255.0; - out[1] = ((tint >> 8) & 0xFF) / 255.0; - out[2] = (tint & 0xFF) / 255.0; - if (premultiply || premultiply === undefined) - { - out[0] *= alpha; - out[1] *= alpha; - out[2] *= alpha; - } - out[3] = alpha; - - return out; -} - -/** - * Generic Mask Stack data structure - * - * @memberof PIXI.utils - * @function createIndicesForQuads - * @param {number} size - Number of quads - * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size` - * @return {Uint16Array|Uint32Array} - Resulting index buffer - */ -function createIndicesForQuads(size, outBuffer) -{ - if ( outBuffer === void 0 ) outBuffer = null; - - // the total number of indices in our array, there are 6 points per quad. - var totalIndices = size * 6; - - outBuffer = outBuffer || new Uint16Array(totalIndices); - - if (outBuffer.length !== totalIndices) - { - throw new Error(("Out buffer length is incorrect, got " + (outBuffer.length) + " and expected " + totalIndices)); - } - - // fill the indices with the quads to draw - for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) - { - outBuffer[i + 0] = j + 0; - outBuffer[i + 1] = j + 1; - outBuffer[i + 2] = j + 2; - outBuffer[i + 3] = j + 0; - outBuffer[i + 4] = j + 2; - outBuffer[i + 5] = j + 3; - } - - return outBuffer; -} - -/** - * Remove items from a javascript array without generating garbage - * - * @function removeItems - * @memberof PIXI.utils - * @param {Array} arr Array to remove elements from - * @param {number} startIdx starting index - * @param {number} removeCount how many to remove - */ -function removeItems(arr, startIdx, removeCount) -{ - var length = arr.length; - var i; - - if (startIdx >= length || removeCount === 0) - { - return; - } - - removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); - - var len = length - removeCount; - - for (i = startIdx; i < len; ++i) - { - arr[i] = arr[i + removeCount]; - } - - arr.length = len; -} - -var nextUid = 0; - -/** - * Gets the next unique identifier - * - * @memberof PIXI.utils - * @function uid - * @return {number} The next unique identifier to use. - */ -function uid() -{ - return ++nextUid; -} - -/** - * Returns sign of number - * - * @memberof PIXI.utils - * @function sign - * @param {number} n - the number to check the sign of - * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive - */ -function sign(n) -{ - if (n === 0) { return 0; } - - return n < 0 ? -1 : 1; -} - -// Taken from the bit-twiddle package - -/** - * Rounds to next power of two. - * - * @function nextPow2 - * @memberof PIXI.utils - * @param {number} v input value - * @return {number} - */ -function nextPow2(v) -{ - v += v === 0; - --v; - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - - return v + 1; -} - -/** - * Checks if a number is a power of two. - * - * @function isPow2 - * @memberof PIXI.utils - * @param {number} v input value - * @return {boolean} `true` if value is power of two - */ -function isPow2(v) -{ - return !(v & (v - 1)) && (!!v); -} - -/** - * Computes ceil of log base 2 - * - * @function log2 - * @memberof PIXI.utils - * @param {number} v input value - * @return {number} logarithm base 2 - */ -function log2(v) -{ - var r = (v > 0xFFFF) << 4; - - v >>>= r; - - var shift = (v > 0xFF) << 3; - - v >>>= shift; r |= shift; - shift = (v > 0xF) << 2; - v >>>= shift; r |= shift; - shift = (v > 0x3) << 1; - v >>>= shift; r |= shift; - - return r | (v >> 1); -} - -/** - * @todo Describe property usage - * - * @static - * @name ProgramCache - * @memberof PIXI.utils - * @type {Object} - */ -var ProgramCache = {}; - -/** - * @todo Describe property usage - * - * @static - * @name TextureCache - * @memberof PIXI.utils - * @type {Object} - */ -var TextureCache = Object.create(null); - -/** - * @todo Describe property usage - * - * @static - * @name BaseTextureCache - * @memberof PIXI.utils - * @type {Object} - */ - -var BaseTextureCache = Object.create(null); -/** - * Destroys all texture in the cache - * - * @memberof PIXI.utils - * @function destroyTextureCache - */ -function destroyTextureCache() -{ - var key; - - for (key in TextureCache) - { - TextureCache[key].destroy(); - } - for (key in BaseTextureCache) - { - BaseTextureCache[key].destroy(); - } -} - -/** - * Removes all textures from cache, but does not destroy them - * - * @memberof PIXI.utils - * @function clearTextureCache - */ -function clearTextureCache() -{ - var key; - - for (key in TextureCache) - { - delete TextureCache[key]; - } - for (key in BaseTextureCache) - { - delete BaseTextureCache[key]; - } -} - -/** - * Trim transparent borders from a canvas - * - * @memberof PIXI.utils - * @function trimCanvas - * @param {HTMLCanvasElement} canvas - the canvas to trim - * @returns {object} Trim data - */ -function trimCanvas(canvas) -{ - // https://gist.github.com/remy/784508 - - var width = canvas.width; - var height = canvas.height; - - var context = canvas.getContext('2d'); - var imageData = context.getImageData(0, 0, width, height); - var pixels = imageData.data; - var len = pixels.length; - - var bound = { - top: null, - left: null, - right: null, - bottom: null, - }; - var data = null; - var i; - var x; - var y; - - for (i = 0; i < len; i += 4) - { - if (pixels[i + 3] !== 0) - { - x = (i / 4) % width; - y = ~~((i / 4) / width); - - if (bound.top === null) - { - bound.top = y; - } - - if (bound.left === null) - { - bound.left = x; - } - else if (x < bound.left) - { - bound.left = x; - } - - if (bound.right === null) - { - bound.right = x + 1; - } - else if (bound.right < x) - { - bound.right = x + 1; - } - - if (bound.bottom === null) - { - bound.bottom = y; - } - else if (bound.bottom < y) - { - bound.bottom = y; - } - } - } - - if (bound.top !== null) - { - width = bound.right - bound.left; - height = bound.bottom - bound.top + 1; - data = context.getImageData(bound.left, bound.top, width, height); - } - - return { - height: height, - width: width, - data: data, - }; -} - -/** - * Creates a Canvas element of the given size to be used as a target for rendering to. - * - * @class - * @memberof PIXI.utils - */ -var CanvasRenderTarget = function CanvasRenderTarget(width, height, resolution) -{ - /** - * The Canvas object that belongs to this CanvasRenderTarget. - * - * @member {HTMLCanvasElement} - */ - this.canvas = document.createElement('canvas'); - - /** - * A CanvasRenderingContext2D object representing a two-dimensional rendering context. - * - * @member {CanvasRenderingContext2D} - */ - this.context = this.canvas.getContext('2d'); - - this.resolution = resolution || settings.settings.RESOLUTION; - - this.resize(width, height); -}; - -var prototypeAccessors = { width: { configurable: true },height: { configurable: true } }; - -/** - * Clears the canvas that was created by the CanvasRenderTarget class. - * - * @private - */ -CanvasRenderTarget.prototype.clear = function clear () -{ - this.context.setTransform(1, 0, 0, 1, 0, 0); - this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); -}; - -/** - * Resizes the canvas to the specified width and height. - * - * @param {number} width - the new width of the canvas - * @param {number} height - the new height of the canvas - */ -CanvasRenderTarget.prototype.resize = function resize (width, height) -{ - this.canvas.width = width * this.resolution; - this.canvas.height = height * this.resolution; -}; - -/** - * Destroys this canvas. - * - */ -CanvasRenderTarget.prototype.destroy = function destroy () -{ - this.context = null; - this.canvas = null; -}; - -/** - * The width of the canvas buffer in pixels. - * - * @member {number} - */ -prototypeAccessors.width.get = function () -{ - return this.canvas.width; -}; - -prototypeAccessors.width.set = function (val) // eslint-disable-line require-jsdoc -{ - this.canvas.width = val; -}; - -/** - * The height of the canvas buffer in pixels. - * - * @member {number} - */ -prototypeAccessors.height.get = function () -{ - return this.canvas.height; -}; - -prototypeAccessors.height.set = function (val) // eslint-disable-line require-jsdoc -{ - this.canvas.height = val; -}; - -Object.defineProperties( CanvasRenderTarget.prototype, prototypeAccessors ); - -/** - * Regexp for data URI. - * Based on: {@link https://github.com/ragingwind/data-uri-regex} - * - * @static - * @constant {RegExp|string} DATA_URI - * @memberof PIXI - * @example data:image/png;base64 - */ -var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; - -/** - * Typedef for decomposeDataUri return object. - * - * @memberof PIXI.utils - * @typedef {object} DecomposedDataUri - * @property {string} mediaType Media type, eg. `image` - * @property {string} subType Sub type, eg. `png` - * @property {string} encoding Data encoding, eg. `base64` - * @property {string} data The actual data - */ - -/** - * Split a data URI into components. Returns undefined if - * parameter `dataUri` is not a valid data URI. - * - * @memberof PIXI.utils - * @function decomposeDataUri - * @param {string} dataUri - the data URI to check - * @return {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined - */ -function decomposeDataUri(dataUri) -{ - var dataUriMatch = DATA_URI.exec(dataUri); - - if (dataUriMatch) - { - return { - mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, - subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, - charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, - encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, - data: dataUriMatch[5], - }; - } - - return undefined; -} - -var tempAnchor; - -/** - * Sets the `crossOrigin` property for this resource based on if the url - * for this resource is cross-origin. If crossOrigin was manually set, this - * function does nothing. - * Nipped from the resource loader! - * - * @ignore - * @param {string} url - The url to test. - * @param {object} [loc=window.location] - The location object to test against. - * @return {string} The crossOrigin value to use (or empty string for none). - */ -function determineCrossOrigin(url, loc) -{ - if ( loc === void 0 ) loc = window.location; - - // data: and javascript: urls are considered same-origin - if (url.indexOf('data:') === 0) - { - return ''; - } - - // default is window.location - loc = loc || window.location; - - if (!tempAnchor) - { - tempAnchor = document.createElement('a'); - } - - // let the browser determine the full href for the url of this resource and then - // parse with the node url lib, we can't use the properties of the anchor element - // because they don't work in IE9 :( - tempAnchor.href = url; - url = _url.parse(tempAnchor.href); - - var samePort = (!url.port && loc.port === '') || (url.port === loc.port); - - // if cross origin - if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) - { - return 'anonymous'; - } - - return ''; -} - -/** - * get the resolution / device pixel ratio of an asset by looking for the prefix - * used by spritesheets and image urls - * - * @memberof PIXI.utils - * @function getResolutionOfUrl - * @param {string} url - the image path - * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. - * @return {number} resolution / device pixel ratio of an asset - */ -function getResolutionOfUrl(url, defaultValue) -{ - var resolution = settings.settings.RETINA_PREFIX.exec(url); - - if (resolution) - { - return parseFloat(resolution[1]); - } - - return defaultValue !== undefined ? defaultValue : 1; -} - -// A map of warning messages already fired -var warnings = {}; - -/** - * Helper for warning developers about deprecated features & settings. - * A stack track for warnings is given; useful for tracking-down where - * deprecated methods/properties/classes are being used within the code. - * - * @memberof PIXI.utils - * @function deprecation - * @param {string} version - The version where the feature became deprecated - * @param {string} message - Message should include what is deprecated, where, and the new solution - * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack - * this is mostly to ignore internal deprecation calls. - */ -function deprecation(version, message, ignoreDepth) -{ - if ( ignoreDepth === void 0 ) ignoreDepth = 3; - - // Ignore duplicat - if (warnings[message]) - { - return; - } - - /* eslint-disable no-console */ - var stack = new Error().stack; - - // Handle IE < 10 and Safari < 6 - if (typeof stack === 'undefined') - { - console.warn('PixiJS Deprecation Warning: ', (message + "\nDeprecated since v" + version)); - } - else - { - // chop off the stack trace which includes PixiJS internal calls - stack = stack.split('\n').splice(ignoreDepth).join('\n'); - - if (console.groupCollapsed) - { - console.groupCollapsed( - '%cPixiJS Deprecation Warning: %c%s', - 'color:#614108;background:#fffbe6', - 'font-weight:normal;color:#614108;background:#fffbe6', - (message + "\nDeprecated since v" + version) - ); - console.warn(stack); - console.groupEnd(); - } - else - { - console.warn('PixiJS Deprecation Warning: ', (message + "\nDeprecated since v" + version)); - console.warn(stack); - } - } - /* eslint-enable no-console */ - - warnings[message] = true; -} - -/** - * Generalized convenience utilities for PIXI. - * @example - * // Extend PIXI's internal Event Emitter. - * class MyEmitter extends PIXI.utils.EventEmitter { - * constructor() { - * super(); - * console.log("Emitter created!"); - * } - * } - * - * // Get info on current device - * console.log(PIXI.utils.isMobile); - * - * // Convert hex color to string - * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" - * @namespace PIXI.utils - */ - -Object.defineProperty(exports, 'isMobile', { - enumerable: true, - get: function () { - return settings.isMobile; - } -}); -exports.EventEmitter = eventemitter3; -exports.earcut = earcut; -exports.url = _url; -exports.BaseTextureCache = BaseTextureCache; -exports.CanvasRenderTarget = CanvasRenderTarget; -exports.DATA_URI = DATA_URI; -exports.ProgramCache = ProgramCache; -exports.TextureCache = TextureCache; -exports.clearTextureCache = clearTextureCache; -exports.correctBlendMode = correctBlendMode; -exports.createIndicesForQuads = createIndicesForQuads; -exports.decomposeDataUri = decomposeDataUri; -exports.deprecation = deprecation; -exports.destroyTextureCache = destroyTextureCache; -exports.determineCrossOrigin = determineCrossOrigin; -exports.getResolutionOfUrl = getResolutionOfUrl; -exports.hex2rgb = hex2rgb; -exports.hex2string = hex2string; -exports.isPow2 = isPow2; -exports.isWebGLSupported = isWebGLSupported; -exports.log2 = log2; -exports.nextPow2 = nextPow2; -exports.premultiplyBlendMode = premultiplyBlendMode; -exports.premultiplyRgba = premultiplyRgba; -exports.premultiplyTint = premultiplyTint; -exports.premultiplyTintToRgba = premultiplyTintToRgba; -exports.removeItems = removeItems; -exports.rgb2hex = rgb2hex; -exports.sayHello = sayHello; -exports.sign = sign; -exports.skipHello = skipHello; -exports.string2hex = string2hex; -exports.trimCanvas = trimCanvas; -exports.uid = uid; - - -},{"@pixi/constants":16,"@pixi/settings":39,"earcut":48,"eventemitter3":50,"url":8}],48:[function(require,module,exports){ -'use strict'; - -module.exports = earcut; -module.exports.default = earcut; - -function earcut(data, holeIndices, dim) { - - dim = dim || 2; - - var hasHoles = holeIndices && holeIndices.length, - outerLen = hasHoles ? holeIndices[0] * dim : data.length, - outerNode = linkedList(data, 0, outerLen, dim, true), - triangles = []; - - if (!outerNode || outerNode.next === outerNode.prev) return triangles; - - var minX, minY, maxX, maxY, x, y, invSize; - - if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); - - // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - if (data.length > 80 * dim) { - minX = maxX = data[0]; - minY = maxY = data[1]; - - for (var i = dim; i < outerLen; i += dim) { - x = data[i]; - y = data[i + 1]; - if (x < minX) minX = x; - if (y < minY) minY = y; - if (x > maxX) maxX = x; - if (y > maxY) maxY = y; - } - - // minX, minY and invSize are later used to transform coords into integers for z-order calculation - invSize = Math.max(maxX - minX, maxY - minY); - invSize = invSize !== 0 ? 1 / invSize : 0; - } - - earcutLinked(outerNode, triangles, dim, minX, minY, invSize); - - return triangles; -} - -// create a circular doubly linked list from polygon points in the specified winding order -function linkedList(data, start, end, dim, clockwise) { - var i, last; - - if (clockwise === (signedArea(data, start, end, dim) > 0)) { - for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); - } else { - for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); - } - - if (last && equals(last, last.next)) { - removeNode(last); - last = last.next; - } - - return last; -} - -// eliminate colinear or duplicate points -function filterPoints(start, end) { - if (!start) return start; - if (!end) end = start; - - var p = start, - again; - do { - again = false; - - if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { - removeNode(p); - p = end = p.prev; - if (p === p.next) break; - again = true; - - } else { - p = p.next; - } - } while (again || p !== end); - - return end; -} - -// main ear slicing loop which triangulates a polygon (given as a linked list) -function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { - if (!ear) return; - - // interlink polygon nodes in z-order - if (!pass && invSize) indexCurve(ear, minX, minY, invSize); - - var stop = ear, - prev, next; - - // iterate through ears, slicing them one by one - while (ear.prev !== ear.next) { - prev = ear.prev; - next = ear.next; - - if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { - // cut off the triangle - triangles.push(prev.i / dim); - triangles.push(ear.i / dim); - triangles.push(next.i / dim); - - removeNode(ear); - - // skipping the next vertex leads to less sliver triangles - ear = next.next; - stop = next.next; - - continue; - } - - ear = next; - - // if we looped through the whole remaining polygon and can't find any more ears - if (ear === stop) { - // try filtering points and slicing again - if (!pass) { - earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); - - // if this didn't work, try curing all small self-intersections locally - } else if (pass === 1) { - ear = cureLocalIntersections(filterPoints(ear), triangles, dim); - earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); - - // as a last resort, try splitting the remaining polygon into two - } else if (pass === 2) { - splitEarcut(ear, triangles, dim, minX, minY, invSize); - } - - break; - } - } -} - -// check whether a polygon node forms a valid ear with adjacent nodes -function isEar(ear) { - var a = ear.prev, - b = ear, - c = ear.next; - - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear - - // now make sure we don't have other points inside the potential ear - var p = ear.next.next; - - while (p !== ear.prev) { - if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) return false; - p = p.next; - } - - return true; -} - -function isEarHashed(ear, minX, minY, invSize) { - var a = ear.prev, - b = ear, - c = ear.next; - - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear - - // triangle bbox; min & max are calculated like this for speed - var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), - minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), - maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), - maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); - - // z-order range for the current triangle bbox; - var minZ = zOrder(minTX, minTY, minX, minY, invSize), - maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); - - var p = ear.prevZ, - n = ear.nextZ; - - // look for points inside the triangle in both directions - while (p && p.z >= minZ && n && n.z <= maxZ) { - if (p !== ear.prev && p !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) return false; - p = p.prevZ; - - if (n !== ear.prev && n !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && - area(n.prev, n, n.next) >= 0) return false; - n = n.nextZ; - } - - // look for remaining points in decreasing z-order - while (p && p.z >= minZ) { - if (p !== ear.prev && p !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) return false; - p = p.prevZ; - } - - // look for remaining points in increasing z-order - while (n && n.z <= maxZ) { - if (n !== ear.prev && n !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && - area(n.prev, n, n.next) >= 0) return false; - n = n.nextZ; - } - - return true; -} - -// go through all polygon nodes and cure small local self-intersections -function cureLocalIntersections(start, triangles, dim) { - var p = start; - do { - var a = p.prev, - b = p.next.next; - - if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { - - triangles.push(a.i / dim); - triangles.push(p.i / dim); - triangles.push(b.i / dim); - - // remove two nodes involved - removeNode(p); - removeNode(p.next); - - p = start = b; - } - p = p.next; - } while (p !== start); - - return filterPoints(p); -} - -// try splitting polygon into two and triangulate them independently -function splitEarcut(start, triangles, dim, minX, minY, invSize) { - // look for a valid diagonal that divides the polygon into two - var a = start; - do { - var b = a.next.next; - while (b !== a.prev) { - if (a.i !== b.i && isValidDiagonal(a, b)) { - // split the polygon in two by the diagonal - var c = splitPolygon(a, b); - - // filter colinear points around the cuts - a = filterPoints(a, a.next); - c = filterPoints(c, c.next); - - // run earcut on each half - earcutLinked(a, triangles, dim, minX, minY, invSize); - earcutLinked(c, triangles, dim, minX, minY, invSize); - return; - } - b = b.next; - } - a = a.next; - } while (a !== start); -} - -// link every hole into the outer loop, producing a single-ring polygon without holes -function eliminateHoles(data, holeIndices, outerNode, dim) { - var queue = [], - i, len, start, end, list; - - for (i = 0, len = holeIndices.length; i < len; i++) { - start = holeIndices[i] * dim; - end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - list = linkedList(data, start, end, dim, false); - if (list === list.next) list.steiner = true; - queue.push(getLeftmost(list)); - } - - queue.sort(compareX); - - // process holes from left to right - for (i = 0; i < queue.length; i++) { - eliminateHole(queue[i], outerNode); - outerNode = filterPoints(outerNode, outerNode.next); - } - - return outerNode; -} - -function compareX(a, b) { - return a.x - b.x; -} - -// find a bridge between vertices that connects hole with an outer ring and and link it -function eliminateHole(hole, outerNode) { - outerNode = findHoleBridge(hole, outerNode); - if (outerNode) { - var b = splitPolygon(outerNode, hole); - filterPoints(b, b.next); - } -} - -// David Eberly's algorithm for finding a bridge between hole and outer polygon -function findHoleBridge(hole, outerNode) { - var p = outerNode, - hx = hole.x, - hy = hole.y, - qx = -Infinity, - m; - - // find a segment intersected by a ray from the hole's leftmost point to the left; - // segment's endpoint with lesser x will be potential connection point - do { - if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { - var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); - if (x <= hx && x > qx) { - qx = x; - if (x === hx) { - if (hy === p.y) return p; - if (hy === p.next.y) return p.next; - } - m = p.x < p.next.x ? p : p.next; - } - } - p = p.next; - } while (p !== outerNode); - - if (!m) return null; - - if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint - - // look for points inside the triangle of hole point, segment intersection and endpoint; - // if there are no points found, we have a valid connection; - // otherwise choose the point of the minimum angle with the ray as connection point - - var stop = m, - mx = m.x, - my = m.y, - tanMin = Infinity, - tan; - - p = m; - - do { - if (hx >= p.x && p.x >= mx && hx !== p.x && - pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { - - tan = Math.abs(hy - p.y) / (hx - p.x); // tangential - - if (locallyInside(p, hole) && - (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { - m = p; - tanMin = tan; - } - } - - p = p.next; - } while (p !== stop); - - return m; -} - -// whether sector in vertex m contains sector in vertex p in the same coordinates -function sectorContainsSector(m, p) { - return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; -} - -// interlink polygon nodes in z-order -function indexCurve(start, minX, minY, invSize) { - var p = start; - do { - if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; - } while (p !== start); - - p.prevZ.nextZ = null; - p.prevZ = null; - - sortLinked(p); -} - -// Simon Tatham's linked list merge sort algorithm -// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html -function sortLinked(list) { - var i, p, q, e, tail, numMerges, pSize, qSize, - inSize = 1; - - do { - p = list; - list = null; - tail = null; - numMerges = 0; - - while (p) { - numMerges++; - q = p; - pSize = 0; - for (i = 0; i < inSize; i++) { - pSize++; - q = q.nextZ; - if (!q) break; - } - qSize = inSize; - - while (pSize > 0 || (qSize > 0 && q)) { - - if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { - e = p; - p = p.nextZ; - pSize--; - } else { - e = q; - q = q.nextZ; - qSize--; - } - - if (tail) tail.nextZ = e; - else list = e; - - e.prevZ = tail; - tail = e; - } - - p = q; - } - - tail.nextZ = null; - inSize *= 2; - - } while (numMerges > 1); - - return list; -} - -// z-order of a point given coords and inverse of the longer side of data bbox -function zOrder(x, y, minX, minY, invSize) { - // coords are transformed into non-negative 15-bit integer range - x = 32767 * (x - minX) * invSize; - y = 32767 * (y - minY) * invSize; - - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; - - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; - - return x | (y << 1); -} - -// find the leftmost node of a polygon ring -function getLeftmost(start) { - var p = start, - leftmost = start; - do { - if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; - p = p.next; - } while (p !== start); - - return leftmost; -} - -// check if a point lies within a convex triangle -function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { - return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && - (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && - (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; -} - -// check if a diagonal between two polygon nodes is valid (lies in polygon interior) -function isValidDiagonal(a, b) { - return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges - (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible - (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors - equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case -} - -// signed area of a triangle -function area(p, q, r) { - return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); -} - -// check if two points are equal -function equals(p1, p2) { - return p1.x === p2.x && p1.y === p2.y; -} - -// check if two segments intersect -function intersects(p1, q1, p2, q2) { - var o1 = sign(area(p1, q1, p2)); - var o2 = sign(area(p1, q1, q2)); - var o3 = sign(area(p2, q2, p1)); - var o4 = sign(area(p2, q2, q1)); - - if (o1 !== o2 && o3 !== o4) return true; // general case - - if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 - if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 - if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 - if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 - - return false; -} - -// for collinear points p, q, r, check if point q lies on segment pr -function onSegment(p, q, r) { - return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); -} - -function sign(num) { - return num > 0 ? 1 : num < 0 ? -1 : 0; -} - -// check if a polygon diagonal intersects any polygon segments -function intersectsPolygon(a, b) { - var p = a; - do { - if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && - intersects(p, p.next, a, b)) return true; - p = p.next; - } while (p !== a); - - return false; -} - -// check if a polygon diagonal is locally inside the polygon -function locallyInside(a, b) { - return area(a.prev, a, a.next) < 0 ? - area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : - area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; -} - -// check if the middle point of a polygon diagonal is inside the polygon -function middleInside(a, b) { - var p = a, - inside = false, - px = (a.x + b.x) / 2, - py = (a.y + b.y) / 2; - do { - if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && - (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) - inside = !inside; - p = p.next; - } while (p !== a); - - return inside; -} - -// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; -// if one belongs to the outer ring and another to a hole, it merges it into a single ring -function splitPolygon(a, b) { - var a2 = new Node(a.i, a.x, a.y), - b2 = new Node(b.i, b.x, b.y), - an = a.next, - bp = b.prev; - - a.next = b; - b.prev = a; - - a2.next = an; - an.prev = a2; - - b2.next = a2; - a2.prev = b2; - - bp.next = b2; - b2.prev = bp; - - return b2; -} - -// create a node and optionally link it with previous one (in a circular doubly linked list) -function insertNode(i, x, y, last) { - var p = new Node(i, x, y); - - if (!last) { - p.prev = p; - p.next = p; - - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; -} - -function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; - - if (p.prevZ) p.prevZ.nextZ = p.nextZ; - if (p.nextZ) p.nextZ.prevZ = p.prevZ; -} - -function Node(i, x, y) { - // vertex index in coordinates array - this.i = i; - - // vertex coordinates - this.x = x; - this.y = y; - - // previous and next vertex nodes in a polygon ring - this.prev = null; - this.next = null; - - // z-order curve value - this.z = null; - - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; - - // indicates whether this is a steiner point - this.steiner = false; -} - -// return a percentage difference between the polygon area and its triangulation area; -// used to verify correctness of triangulation -earcut.deviation = function (data, holeIndices, dim, triangles) { - var hasHoles = holeIndices && holeIndices.length; - var outerLen = hasHoles ? holeIndices[0] * dim : data.length; - - var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); - if (hasHoles) { - for (var i = 0, len = holeIndices.length; i < len; i++) { - var start = holeIndices[i] * dim; - var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - polygonArea -= Math.abs(signedArea(data, start, end, dim)); - } - } - - var trianglesArea = 0; - for (i = 0; i < triangles.length; i += 3) { - var a = triangles[i] * dim; - var b = triangles[i + 1] * dim; - var c = triangles[i + 2] * dim; - trianglesArea += Math.abs( - (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); - } - - return polygonArea === 0 && trianglesArea === 0 ? 0 : - Math.abs((trianglesArea - polygonArea) / polygonArea); -}; - -function signedArea(data, start, end, dim) { - var sum = 0; - for (var i = start, j = end - dim; i < end; i += dim) { - sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); - j = i; - } - return sum; -} - -// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts -earcut.flatten = function (data) { - var dim = data[0][0].length, - result = {vertices: [], holes: [], dimensions: dim}, - holeIndex = 0; - - for (var i = 0; i < data.length; i++) { - for (var j = 0; j < data[i].length; j++) { - for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); - } - if (i > 0) { - holeIndex += data[i - 1].length; - result.holes.push(holeIndex); - } - } - return result; -}; - -},{}],49:[function(require,module,exports){ -(function (global,setImmediate){ -(function(global){ - -// -// Check for native Promise and it has correct interface -// - -var NativePromise = global['Promise']; -var nativePromiseSupported = - NativePromise && - // Some of these methods are missing from - // Firefox/Chrome experimental implementations - 'resolve' in NativePromise && - 'reject' in NativePromise && - 'all' in NativePromise && - 'race' in NativePromise && - // Older version of the spec had a resolver object - // as the arg rather than a function - (function(){ - var resolve; - new NativePromise(function(r){ resolve = r; }); - return typeof resolve === 'function'; - })(); - - -// -// export if necessary -// - -if (typeof exports !== 'undefined' && exports) -{ - // node.js - exports.Promise = nativePromiseSupported ? NativePromise : Promise; - exports.Polyfill = Promise; -} -else -{ - // AMD - if (typeof define == 'function' && define.amd) - { - define(function(){ - return nativePromiseSupported ? NativePromise : Promise; + Object.defineProperty(PIXI.extract, 'WebGLExtract', { + get: function () { + utils.deprecation(v5, 'PIXI.extract.WebGLExtract method has moved to PIXI.Extract'); + return PIXI.Extract; + }, }); - } - else - { - // in browser add to global - if (!nativePromiseSupported) - global['Promise'] = Promise; - } -} - - -// -// Polyfill -// - -var PENDING = 'pending'; -var SEALED = 'sealed'; -var FULFILLED = 'fulfilled'; -var REJECTED = 'rejected'; -var NOOP = function(){}; - -function isArray(value) { - return Object.prototype.toString.call(value) === '[object Array]'; -} - -// async calls -var asyncSetTimer = typeof setImmediate !== 'undefined' ? setImmediate : setTimeout; -var asyncQueue = []; -var asyncTimer; - -function asyncFlush(){ - // run promise callbacks - for (var i = 0; i < asyncQueue.length; i++) - asyncQueue[i][0](asyncQueue[i][1]); - - // reset async asyncQueue - asyncQueue = []; - asyncTimer = false; -} - -function asyncCall(callback, arg){ - asyncQueue.push([callback, arg]); - - if (!asyncTimer) - { - asyncTimer = true; - asyncSetTimer(asyncFlush, 0); - } -} - - -function invokeResolver(resolver, promise) { - function resolvePromise(value) { - resolve(promise, value); - } - - function rejectPromise(reason) { - reject(promise, reason); - } - - try { - resolver(resolvePromise, rejectPromise); - } catch(e) { - rejectPromise(e); - } -} - -function invokeCallback(subscriber){ - var owner = subscriber.owner; - var settled = owner.state_; - var value = owner.data_; - var callback = subscriber[settled]; - var promise = subscriber.then; - - if (typeof callback === 'function') - { - settled = FULFILLED; - try { - value = callback(value); - } catch(e) { - reject(promise, e); - } - } - - if (!handleThenable(promise, value)) - { - if (settled === FULFILLED) - resolve(promise, value); - - if (settled === REJECTED) - reject(promise, value); - } -} - -function handleThenable(promise, value) { - var resolved; - - try { - if (promise === value) - throw new TypeError('A promises callback cannot return that same promise.'); - - if (value && (typeof value === 'function' || typeof value === 'object')) - { - var then = value.then; // then should be retrived only once - - if (typeof then === 'function') - { - then.call(value, function(val){ - if (!resolved) - { - resolved = true; - - if (value !== val) - resolve(promise, val); - else - fulfill(promise, val); - } - }, function(reason){ - if (!resolved) - { - resolved = true; - - reject(promise, reason); - } - }); - - return true; - } - } - } catch (e) { - if (!resolved) - reject(promise, e); - - return true; - } - - return false; -} - -function resolve(promise, value){ - if (promise === value || !handleThenable(promise, value)) - fulfill(promise, value); -} - -function fulfill(promise, value){ - if (promise.state_ === PENDING) - { - promise.state_ = SEALED; - promise.data_ = value; - - asyncCall(publishFulfillment, promise); - } -} - -function reject(promise, reason){ - if (promise.state_ === PENDING) - { - promise.state_ = SEALED; - promise.data_ = reason; - - asyncCall(publishRejection, promise); - } -} - -function publish(promise) { - var callbacks = promise.then_; - promise.then_ = undefined; - - for (var i = 0; i < callbacks.length; i++) { - invokeCallback(callbacks[i]); - } -} - -function publishFulfillment(promise){ - promise.state_ = FULFILLED; - publish(promise); -} - -function publishRejection(promise){ - promise.state_ = REJECTED; - publish(promise); -} - -/** -* @class -*/ -function Promise(resolver){ - if (typeof resolver !== 'function') - throw new TypeError('Promise constructor takes a function argument'); - - if (this instanceof Promise === false) - throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); - - this.then_ = []; - - invokeResolver(resolver, this); -} - -Promise.prototype = { - constructor: Promise, - - state_: PENDING, - then_: null, - data_: undefined, - - then: function(onFulfillment, onRejection){ - var subscriber = { - owner: this, - then: new this.constructor(NOOP), - fulfilled: onFulfillment, - rejected: onRejection + /** + * @class PIXI.prepare.WebGLPrepare + * @deprecated since 5.0.0 + * @see PIXI.Prepare + */ + Object.defineProperty(PIXI.prepare, 'WebGLPrepare', { + get: function () { + utils.deprecation(v5, 'PIXI.prepare.WebGLPrepare class has moved to PIXI.Prepare'); + return PIXI.Prepare; + }, + }); + /** + * @method PIXI.Container#_renderWebGL + * @private + * @deprecated since 5.0.0 + * @see PIXI.Container#render + * @param {PIXI.Renderer} renderer Instance of renderer + */ + PIXI.Container.prototype._renderWebGL = function _renderWebGL(renderer) { + utils.deprecation(v5, 'PIXI.Container._renderWebGL method has moved to PIXI.Container._render'); + this._render(renderer); }; - - if (this.state_ === FULFILLED || this.state_ === REJECTED) - { - // already resolved, call callback async - asyncCall(invokeCallback, subscriber); - } - else - { - // subscribe - this.then_.push(subscriber); - } - - return subscriber.then; - }, - - 'catch': function(onRejection) { - return this.then(null, onRejection); - } -}; - -Promise.all = function(promises){ - var Class = this; - - if (!isArray(promises)) - throw new TypeError('You must pass an array to Promise.all().'); - - return new Class(function(resolve, reject){ - var results = []; - var remaining = 0; - - function resolver(index){ - remaining++; - return function(value){ - results[index] = value; - if (!--remaining) - resolve(results); - }; - } - - for (var i = 0, promise; i < promises.length; i++) - { - promise = promises[i]; - - if (promise && typeof promise.then === 'function') - promise.then(resolver(i), reject); - else - results[i] = promise; - } - - if (!remaining) - resolve(results); - }); -}; - -Promise.race = function(promises){ - var Class = this; - - if (!isArray(promises)) - throw new TypeError('You must pass an array to Promise.race().'); - - return new Class(function(resolve, reject) { - for (var i = 0, promise; i < promises.length; i++) - { - promise = promises[i]; - - if (promise && typeof promise.then === 'function') - promise.then(resolve, reject); - else - resolve(promise); - } - }); -}; - -Promise.resolve = function(value){ - var Class = this; - - if (value && typeof value === 'object' && value.constructor === Class) - return value; - - return new Class(function(resolve){ - resolve(value); - }); -}; - -Promise.reject = function(reason){ - var Class = this; - - return new Class(function(resolve, reject){ - reject(reason); - }); -}; - -})(typeof window != 'undefined' ? window : typeof global != 'undefined' ? global : typeof self != 'undefined' ? self : this); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) -},{"timers":7}],50:[function(require,module,exports){ -'use strict'; - -var has = Object.prototype.hasOwnProperty - , prefix = '~'; - -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} - -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); - - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; -} - -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; -} - -/** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } - - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; - - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; - - return emitter; -} - -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; -} - -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; -} - -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; - - if (this._eventsCount === 0) return names; - - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } - - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } - - return names; -}; - -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; - - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; - - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } - - return ee; -}; - -/** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; - - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; - -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return false; - - var listeners = this._events[evt] - , len = arguments.length - , args - , i; - - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + /** + * @method PIXI.Container#renderWebGL + * @deprecated since 5.0.0 + * @see PIXI.Container#render + * @param {PIXI.Renderer} renderer Instance of renderer + */ + PIXI.Container.prototype.renderWebGL = function renderWebGL(renderer) { + utils.deprecation(v5, 'PIXI.Container.renderWebGL method has moved to PIXI.Container.render'); + this.render(renderer); + }; + /** + * @method PIXI.DisplayObject#renderWebGL + * @deprecated since 5.0.0 + * @see PIXI.DisplayObject#render + * @param {PIXI.Renderer} renderer Instance of renderer + */ + PIXI.DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) { + utils.deprecation(v5, 'PIXI.DisplayObject.renderWebGL method has moved to PIXI.DisplayObject.render'); + this.render(renderer); + }; + /** + * @method PIXI.Container#renderAdvancedWebGL + * @deprecated since 5.0.0 + * @see PIXI.Container#renderAdvanced + * @param {PIXI.Renderer} renderer Instance of renderer + */ + PIXI.Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + utils.deprecation(v5, 'PIXI.Container.renderAdvancedWebGL method has moved to PIXI.Container.renderAdvanced'); + this.renderAdvanced(renderer); + }; + Object.defineProperties(PIXI.settings, { + /** + * Default transform type. + * + * @static + * @deprecated since 5.0.0 + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: { + get: function () { + utils.deprecation(v5, 'PIXI.settings.TRANSFORM_MODE property has been removed'); + return 0; + }, + set: function () { + utils.deprecation(v5, 'PIXI.settings.TRANSFORM_MODE property has been removed'); + }, + }, + }); + var BaseTextureAny = PIXI.BaseTexture; + /** + * @method loadSource + * @memberof PIXI.BaseTexture# + * @deprecated since 5.0.0 + */ + BaseTextureAny.prototype.loadSource = function loadSource(image) { + utils.deprecation(v5, 'PIXI.BaseTexture.loadSource method has been deprecated'); + var resource = PIXI.resources.autoDetectResource(image); + resource.internal = true; + this.setResource(resource); + this.update(); + }; + var baseTextureIdDeprecation = false; + Object.defineProperties(BaseTextureAny.prototype, { + /** + * @name PIXI.BaseTexture#hasLoaded + * @type {boolean} + * @deprecated since 5.0.0 + * @readonly + * @see PIXI.BaseTexture#valid + */ + hasLoaded: { + get: function () { + utils.deprecation(v5, 'PIXI.BaseTexture.hasLoaded property has been removed, use PIXI.BaseTexture.valid'); + return this.valid; + }, + }, + /** + * @name PIXI.BaseTexture#imageUrl + * @type {string} + * @deprecated since 5.0.0 + * @see PIXI.resources.ImageResource#url + */ + imageUrl: { + get: function () { + var _a; + utils.deprecation(v5, 'PIXI.BaseTexture.imageUrl property has been removed, use PIXI.BaseTexture.resource.url'); + return (_a = this.resource) === null || _a === void 0 ? void 0 : _a.url; + }, + set: function (imageUrl) { + utils.deprecation(v5, 'PIXI.BaseTexture.imageUrl property has been removed, use PIXI.BaseTexture.resource.url'); + if (this.resource) { + this.resource.url = imageUrl; + } + }, + }, + /** + * @name PIXI.BaseTexture#source + * @type {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} + * @deprecated since 5.0.0 + * @readonly + * @see PIXI.resources.BaseImageResource#source + */ + source: { + get: function () { + utils.deprecation(v5, 'PIXI.BaseTexture.source property has been moved, use `PIXI.BaseTexture.resource.source`'); + return this.resource.source; + }, + set: function (source) { + utils.deprecation(v5, 'PIXI.BaseTexture.source property has been moved, use `PIXI.BaseTexture.resource.source` ' + + 'if you want to set HTMLCanvasElement. Otherwise, create new BaseTexture.'); + if (this.resource) { + this.resource.source = source; + } + }, + }, + /** + * @name PIXI.BaseTexture#premultiplyAlpha + * @type {boolean} + * @deprecated since 5.2.0 + * @readonly + * @see PIXI.BaseTexture#alphaMode + */ + premultiplyAlpha: { + get: function () { + utils.deprecation('5.2.0', 'PIXI.BaseTexture.premultiplyAlpha property has been changed to `alphaMode`' + + ', see `PIXI.ALPHA_MODES`'); + return this.alphaMode !== 0; + }, + set: function (value) { + utils.deprecation('5.2.0', 'PIXI.BaseTexture.premultiplyAlpha property has been changed to `alphaMode`' + + ', see `PIXI.ALPHA_MODES`'); + this.alphaMode = Number(value); + }, + }, + /** + * Batch local field, stores current texture location + * + * @name PIXI.BaseTexture#_id + * @deprecated since 5.2.0 + * @type {number} + * @see PIXI.BaseTexture#_batchLocation + */ + _id: { + get: function () { + if (!baseTextureIdDeprecation) { + // #popelyshev: That property was a hot place, I don't want to call deprecation method on it if possible + utils.deprecation('5.2.0', 'PIXI.BaseTexture._id batch local field has been changed to `_batchLocation`'); + baseTextureIdDeprecation = true; + } + return this._batchLocation; + }, + set: function (value) { + this._batchLocation = value; + }, + }, + }); + /** + * @method fromImage + * @static + * @memberof PIXI.BaseTexture + * @deprecated since 5.0.0 + * @see PIXI.BaseTexture.from + */ + BaseTextureAny.fromImage = function fromImage(canvas, crossorigin, scaleMode, scale) { + utils.deprecation(v5, 'PIXI.BaseTexture.fromImage method has been replaced with PIXI.BaseTexture.from'); + var resourceOptions = { scale: scale, crossorigin: crossorigin }; + return BaseTextureAny.from(canvas, { scaleMode: scaleMode, resourceOptions: resourceOptions }); + }; + /** + * @method fromCanvas + * @static + * @memberof PIXI.BaseTexture + * @deprecated since 5.0.0 + * @see PIXI.BaseTexture.from + */ + BaseTextureAny.fromCanvas = function fromCanvas(canvas, scaleMode) { + utils.deprecation(v5, 'PIXI.BaseTexture.fromCanvas method has been replaced with PIXI.BaseTexture.from'); + return BaseTextureAny.from(canvas, { scaleMode: scaleMode }); + }; + /** + * @method fromSVG + * @static + * @memberof PIXI.BaseTexture + * @deprecated since 5.0.0 + * @see PIXI.BaseTexture.from + */ + BaseTextureAny.fromSVG = function fromSVG(canvas, crossorigin, scaleMode, scale) { + utils.deprecation(v5, 'PIXI.BaseTexture.fromSVG method has been replaced with PIXI.BaseTexture.from'); + var resourceOptions = { scale: scale, crossorigin: crossorigin }; + return BaseTextureAny.from(canvas, { scaleMode: scaleMode, resourceOptions: resourceOptions }); + }; + Object.defineProperties(PIXI.resources.ImageResource.prototype, { + /** + * @name PIXI.resources.ImageResource#premultiplyAlpha + * @type {boolean} + * @deprecated since 5.2.0 + * @readonly + * @see PIXI.resources.ImageResource#alphaMode + */ + premultiplyAlpha: { + get: function () { + utils.deprecation('5.2.0', 'PIXI.resources.ImageResource.premultiplyAlpha property ' + + 'has been changed to `alphaMode`, see `PIXI.ALPHA_MODES`'); + return this.alphaMode !== 0; + }, + set: function (value) { + utils.deprecation('5.2.0', 'PIXI.resources.ImageResource.premultiplyAlpha property ' + + 'has been changed to `alphaMode`, see `PIXI.ALPHA_MODES`'); + this.alphaMode = Number(value); + }, + }, + }); + /** + * @method PIXI.Point#copy + * @deprecated since 5.0.0 + * @see PIXI.Point#copyFrom + */ + PIXI.Point.prototype.copy = function copy(p) { + utils.deprecation(v5, 'PIXI.Point.copy method has been replaced with PIXI.Point.copyFrom'); + return this.copyFrom(p); + }; + /** + * @method PIXI.ObservablePoint#copy + * @deprecated since 5.0.0 + * @see PIXI.ObservablePoint#copyFrom + */ + PIXI.ObservablePoint.prototype.copy = function copy(p) { + utils.deprecation(v5, 'PIXI.ObservablePoint.copy method has been replaced with PIXI.ObservablePoint.copyFrom'); + return this.copyFrom(p); + }; + /** + * @method PIXI.Rectangle#copy + * @deprecated since 5.0.0 + * @see PIXI.Rectangle#copyFrom + */ + PIXI.Rectangle.prototype.copy = function copy(p) { + utils.deprecation(v5, 'PIXI.Rectangle.copy method has been replaced with PIXI.Rectangle.copyFrom'); + return this.copyFrom(p); + }; + /** + * @method PIXI.Matrix#copy + * @deprecated since 5.0.0 + * @see PIXI.Matrix#copyTo + */ + PIXI.Matrix.prototype.copy = function copy(p) { + utils.deprecation(v5, 'PIXI.Matrix.copy method has been replaced with PIXI.Matrix.copyTo'); + return this.copyTo(p); + }; + /** + * @method PIXI.systems.StateSystem#setState + * @deprecated since 5.1.0 + * @see PIXI.systems.StateSystem#set + */ + PIXI.systems.StateSystem.prototype.setState = function setState(s) { + utils.deprecation('v5.1.0', 'StateSystem.setState has been renamed to StateSystem.set'); + return this.set(s); + }; + Object.assign(PIXI.systems.FilterSystem.prototype, { + /** + * @method PIXI.FilterManager#getRenderTarget + * @deprecated since 5.0.0 + * @see PIXI.systems.FilterSystem#getFilterTexture + */ + getRenderTarget: function (_clear, resolution) { + utils.deprecation(v5, 'PIXI.FilterManager.getRenderTarget method has been replaced with PIXI.systems.FilterSystem#getFilterTexture'); + return this.getFilterTexture(null, resolution); + }, + /** + * @method PIXI.FilterManager#returnRenderTarget + * @deprecated since 5.0.0 + * @see PIXI.systems.FilterSystem#returnFilterTexture + */ + returnRenderTarget: function (renderTexture) { + utils.deprecation(v5, 'PIXI.FilterManager.returnRenderTarget method has been replaced with ' + + 'PIXI.systems.FilterSystem.returnFilterTexture'); + this.returnFilterTexture(renderTexture); + }, + /** + * @method PIXI.systems.FilterSystem#calculateScreenSpaceMatrix + * @deprecated since 5.0.0 + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + calculateScreenSpaceMatrix: function (outputMatrix) { + utils.deprecation(v5, 'PIXI.systems.FilterSystem.calculateScreenSpaceMatrix method is removed, ' + + 'use `(vTextureCoord * inputSize.xy) + outputFrame.xy` instead'); + var mappedMatrix = outputMatrix.identity(); + var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; + mappedMatrix.translate(sourceFrame.x / destinationFrame.width, sourceFrame.y / destinationFrame.height); + mappedMatrix.scale(destinationFrame.width, destinationFrame.height); + return mappedMatrix; + }, + /** + * @method PIXI.systems.FilterSystem#calculateNormalizedScreenSpaceMatrix + * @deprecated since 5.0.0 + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + calculateNormalizedScreenSpaceMatrix: function (outputMatrix) { + utils.deprecation(v5, 'PIXI.systems.FilterManager.calculateNormalizedScreenSpaceMatrix method is removed, ' + + 'use `((vTextureCoord * inputSize.xy) + outputFrame.xy) / outputFrame.zw` instead.'); + var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; + var mappedMatrix = outputMatrix.identity(); + mappedMatrix.translate(sourceFrame.x / destinationFrame.width, sourceFrame.y / destinationFrame.height); + var translateScaleX = (destinationFrame.width / sourceFrame.width); + var translateScaleY = (destinationFrame.height / sourceFrame.height); + mappedMatrix.scale(translateScaleX, translateScaleY); + return mappedMatrix; + }, + }); + Object.defineProperties(PIXI.RenderTexture.prototype, { + /** + * @name PIXI.RenderTexture#sourceFrame + * @type {PIXI.Rectangle} + * @deprecated since 5.0.0 + * @readonly + */ + sourceFrame: { + get: function () { + utils.deprecation(v5, 'PIXI.RenderTexture.sourceFrame property has been removed'); + return this.filterFrame; + }, + }, + /** + * @name PIXI.RenderTexture#size + * @type {PIXI.Rectangle} + * @deprecated since 5.0.0 + * @readonly + */ + size: { + get: function () { + utils.deprecation(v5, 'PIXI.RenderTexture.size property has been removed'); + return this._frame; + }, + }, + }); + /** + * @class BlurXFilter + * @memberof PIXI.filters + * @deprecated since 5.0.0 + * @see PIXI.filters.BlurFilterPass + */ + var BlurXFilter = /** @class */ (function (_super) { + __extends(BlurXFilter, _super); + function BlurXFilter(strength, quality, resolution, kernelSize) { + var _this = this; + utils.deprecation(v5, 'PIXI.filters.BlurXFilter class is deprecated, use PIXI.filters.BlurFilterPass'); + _this = _super.call(this, true, strength, quality, resolution, kernelSize) || this; + return _this; + } + return BlurXFilter; + }(PIXI.filters.BlurFilterPass)); + /** + * @class BlurYFilter + * @memberof PIXI.filters + * @deprecated since 5.0.0 + * @see PIXI.filters.BlurFilterPass + */ + var BlurYFilter = /** @class */ (function (_super) { + __extends(BlurYFilter, _super); + function BlurYFilter(strength, quality, resolution, kernelSize) { + var _this = this; + utils.deprecation(v5, 'PIXI.filters.BlurYFilter class is deprecated, use PIXI.filters.BlurFilterPass'); + _this = _super.call(this, false, strength, quality, resolution, kernelSize) || this; + return _this; + } + return BlurYFilter; + }(PIXI.filters.BlurFilterPass)); + Object.assign(PIXI.filters, { + BlurXFilter: BlurXFilter, + BlurYFilter: BlurYFilter, + }); + var SpriteAny = PIXI.Sprite, TextureAny = PIXI.Texture, GraphicsAny = PIXI.Graphics; + // Support for pixi.js-legacy bifurcation + // give users a friendly assist to use legacy + if (!GraphicsAny.prototype.generateCanvasTexture) { + GraphicsAny.prototype.generateCanvasTexture = function generateCanvasTexture() { + utils.deprecation(v5, 'PIXI.Graphics.generateCanvasTexture method is only available in "pixi.js-legacy"'); + }; } - - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; + /** + * @deprecated since 5.0.0 + * @member {PIXI.Graphics} PIXI.Graphics#graphicsData + * @see PIXI.Graphics#geometry + * @readonly + */ + Object.defineProperty(GraphicsAny.prototype, 'graphicsData', { + get: function () { + utils.deprecation(v5, 'PIXI.Graphics.graphicsData property is deprecated, use PIXI.Graphics.geometry.graphicsData'); + return this.geometry.graphicsData; + }, + }); + // Use these to deprecate all the Sprite from* methods + function spriteFrom(name, source, crossorigin, scaleMode) { + utils.deprecation(v5, "PIXI.Sprite." + name + " method is deprecated, use PIXI.Sprite.from"); + return SpriteAny.from(source, { + resourceOptions: { + scale: scaleMode, + crossorigin: crossorigin, + }, + }); } - - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; - - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } - - listeners[i].fn.apply(listeners[i].context, args); - } + /** + * @deprecated since 5.0.0 + * @see PIXI.Sprite.from + * @method PIXI.Sprite.fromImage + * @return {PIXI.Sprite} + */ + SpriteAny.fromImage = spriteFrom.bind(null, 'fromImage'); + /** + * @deprecated since 5.0.0 + * @method PIXI.Sprite.fromSVG + * @see PIXI.Sprite.from + * @return {PIXI.Sprite} + */ + SpriteAny.fromSVG = spriteFrom.bind(null, 'fromSVG'); + /** + * @deprecated since 5.0.0 + * @method PIXI.Sprite.fromCanvas + * @see PIXI.Sprite.from + * @return {PIXI.Sprite} + */ + SpriteAny.fromCanvas = spriteFrom.bind(null, 'fromCanvas'); + /** + * @deprecated since 5.0.0 + * @method PIXI.Sprite.fromVideo + * @see PIXI.Sprite.from + * @return {PIXI.Sprite} + */ + SpriteAny.fromVideo = spriteFrom.bind(null, 'fromVideo'); + /** + * @deprecated since 5.0.0 + * @method PIXI.Sprite.fromFrame + * @see PIXI.Sprite.from + * @return {PIXI.Sprite} + */ + SpriteAny.fromFrame = spriteFrom.bind(null, 'fromFrame'); + // Use these to deprecate all the Texture from* methods + function textureFrom(name, source, crossorigin, scaleMode) { + utils.deprecation(v5, "PIXI.Texture." + name + " method is deprecated, use PIXI.Texture.from"); + return TextureAny.from(source, { + resourceOptions: { + scale: scaleMode, + crossorigin: crossorigin, + }, + }); } - } - - return true; -}; - -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); -}; + /** + * @deprecated since 5.0.0 + * @method PIXI.Texture.fromImage + * @see PIXI.Texture.from + * @return {PIXI.Texture} + */ + TextureAny.fromImage = textureFrom.bind(null, 'fromImage'); + /** + * @deprecated since 5.0.0 + * @method PIXI.Texture.fromSVG + * @see PIXI.Texture.from + * @return {PIXI.Texture} + */ + TextureAny.fromSVG = textureFrom.bind(null, 'fromSVG'); + /** + * @deprecated since 5.0.0 + * @method PIXI.Texture.fromCanvas + * @see PIXI.Texture.from + * @return {PIXI.Texture} + */ + TextureAny.fromCanvas = textureFrom.bind(null, 'fromCanvas'); + /** + * @deprecated since 5.0.0 + * @method PIXI.Texture.fromVideo + * @see PIXI.Texture.from + * @return {PIXI.Texture} + */ + TextureAny.fromVideo = textureFrom.bind(null, 'fromVideo'); + /** + * @deprecated since 5.0.0 + * @method PIXI.Texture.fromFrame + * @see PIXI.Texture.from + * @return {PIXI.Texture} + */ + TextureAny.fromFrame = textureFrom.bind(null, 'fromFrame'); + /** + * @deprecated since 5.0.0 + * @member {boolean} PIXI.AbstractRenderer#autoResize + * @see PIXI.AbstractRenderer#autoDensity + */ + Object.defineProperty(PIXI.AbstractRenderer.prototype, 'autoResize', { + get: function () { + utils.deprecation(v5, 'PIXI.AbstractRenderer.autoResize property is deprecated, ' + + 'use PIXI.AbstractRenderer.autoDensity'); + return this.autoDensity; + }, + set: function (value) { + utils.deprecation(v5, 'PIXI.AbstractRenderer.autoResize property is deprecated, ' + + 'use PIXI.AbstractRenderer.autoDensity'); + this.autoDensity = value; + }, + }); + /** + * @deprecated since 5.0.0 + * @member {PIXI.systems.TextureSystem} PIXI.Renderer#textureManager + * @see PIXI.Renderer#texture + */ + Object.defineProperty(PIXI.Renderer.prototype, 'textureManager', { + get: function () { + utils.deprecation(v5, 'PIXI.Renderer.textureManager property is deprecated, use PIXI.Renderer.texture'); + return this.texture; + }, + }); + /** + * @namespace PIXI.utils.mixins + * @deprecated since 5.0.0 + */ + PIXI.utils.mixins = { + /** + * @memberof PIXI.utils.mixins + * @function mixin + * @deprecated since 5.0.0 + */ + mixin: function () { + utils.deprecation(v5, 'PIXI.utils.mixins.mixin function is no longer available'); + }, + /** + * @memberof PIXI.utils.mixins + * @function delayMixin + * @deprecated since 5.0.0 + */ + delayMixin: function () { + utils.deprecation(v5, 'PIXI.utils.mixins.delayMixin function is no longer available'); + }, + /** + * @memberof PIXI.utils.mixins + * @function performMixins + * @deprecated since 5.0.0 + */ + performMixins: function () { + utils.deprecation(v5, 'PIXI.utils.mixins.performMixins function is no longer available'); + }, + }; + /** + * @memberof PIXI.BitmapText + * @member {object} font + * @deprecated since 5.3.0 + */ + Object.defineProperty(PIXI.BitmapText.prototype, 'font', { + get: function () { + utils.deprecation('5.3.0', 'PIXI.BitmapText.font property is deprecated, ' + + 'use fontName, fontSize, tint or align properties'); + return { + name: this._fontName, + size: this._fontSize, + tint: this._tint, + align: this._align, + }; + }, + set: function (value) { + utils.deprecation('5.3.0', 'PIXI.BitmapText.font property is deprecated, ' + + 'use fontName, fontSize, tint or align properties'); + if (!value) { + return; + } + var style = { font: value }; + this._upgradeStyle(style); + style.fontSize = style.fontSize || PIXI.BitmapFont.available[style.fontName].size; + this._fontName = style.fontName; + this._fontSize = style.fontSize; + this.dirty = true; + }, + }); +} +// Install renderer plugins +core.Renderer.registerPlugin('accessibility', accessibility.AccessibilityManager); +core.Renderer.registerPlugin('extract', extract.Extract); +core.Renderer.registerPlugin('interaction', interaction.InteractionManager); +core.Renderer.registerPlugin('particle', particles.ParticleRenderer); +core.Renderer.registerPlugin('prepare', prepare.Prepare); +core.Renderer.registerPlugin('batch', core.BatchRenderer); +core.Renderer.registerPlugin('tilingSprite', spriteTiling.TilingSpriteRenderer); +loaders.Loader.registerPlugin(textBitmap.BitmapFontLoader); +loaders.Loader.registerPlugin(spritesheet.SpritesheetLoader); +app.Application.registerPlugin(ticker.TickerPlugin); +app.Application.registerPlugin(loaders.AppLoaderPlugin); /** - * Add a one-time listener for a given event. + * String of the current PIXI version. * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); -}; - +var VERSION = '5.3.3'; /** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public + * @namespace PIXI */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } - - var listeners = this._events[evt]; - - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } - - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } - - return this; -}; - /** - * Remove all listeners, or those of the specified event. + * This namespace contains WebGL-only display filters that can be applied + * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property. * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public + * Since PixiJS only had a handful of built-in filters, additional filters + * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the + * PixiJS Filters repository. + * + * All filters must extend {@link PIXI.Filter}. + * + * @example + * // Create a new application + * const app = new PIXI.Application(); + * + * // Draw a green rectangle + * const rect = new PIXI.Graphics() + * .beginFill(0x00ff00) + * .drawRect(40, 40, 200, 200); + * + * // Add a blur filter + * rect.filters = [new PIXI.filters.BlurFilter()]; + * + * // Display rectangle + * app.stage.addChild(rect); + * document.body.appendChild(app.view); + * @namespace PIXI.filters */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } - - return this; -}; - -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; - -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; - -// -// Expose the module. -// -if ('undefined' !== typeof module) { - module.exports = EventEmitter; -} - -},{}],51:[function(require,module,exports){ -'use strict'; - -// Programatically add fork me on github ribbon from javascript without making changes to CSS, HTML, or adding image files -// by David Figatner -// copyright 2018 YOPEY YOPEY LLC -// MIT license -// based on https://github.com/simonwhitaker/github-fork-ribbon-css (MIT license) - -var RIBBON = { - width: '12.1em', - height: '12.1em', - overflow: 'hidden', - top: 0, - right: 0, - zIndex: 9999, - pointerEvents: 'none', - fontSize: '13px', - textDecoration: 'none', - textIndent: '-999999px' +var filters = { + AlphaFilter: filterAlpha.AlphaFilter, + BlurFilter: filterBlur.BlurFilter, + BlurFilterPass: filterBlur.BlurFilterPass, + ColorMatrixFilter: filterColorMatrix.ColorMatrixFilter, + DisplacementFilter: filterDisplacement.DisplacementFilter, + FXAAFilter: filterFxaa.FXAAFilter, + NoiseFilter: filterNoise.NoiseFilter, }; -var BEFORE_AFTER = [['position', 'absolute'], ['display', 'block'], ['width', '15.38em'], ['height', '1.54em'], ['top', '3.23em'], ['right', '-3.23em'], ['-webkit-box-sizing', 'content-box'], ['-moz-box-sizing', 'content-box'], ['box-sizing', 'content-box'], ['-webkit-transform', 'rotate(45deg)'], ['-moz-transform', 'rotate(45deg)'], ['-ms-Transform', 'rotate(45deg)'], ['-o-transform', 'rotate(45deg)'], ['transform', 'rotate(45deg)']]; - -var BEFORE = [['content', '""'], ['padding', '.38em 0'], ['background-color', '#a00'], ['background-image', '-webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0)), to(rgba(0, 0, 0, 0.15)))'], ['background-image', '-webkit-linear-gradient(top, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['background-image', '-moz-linear-gradient(top, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['background-image', '-ms-linear-gradient(top, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['background-image', '-o-linear-gradient(top, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['background-image', 'linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15))'], ['box-shadow', '0 .15em .23em 0 rgba(0, 0, 0, 0.5)'], ['pointer-events', 'auto']]; - -var AFTER = [['content', 'attr(data-ribbon)'], ['color', '#fff'], ['font', '700 1em "Helvetica Neue", Helvetica, Arial, sans-serif'], ['line-height', '1.54em'], ['text-decoration', 'none'], ['text-shadow', '0 -.08em rgba(0, 0, 0, 0.5)'], ['text-align', 'center'], ['text-indent', '0'], ['padding', '.15em 0'], ['margin', '.15em 0'], ['border-width', '.08em 0'], ['border-style', 'dotted'], ['border-color', '#fff'], ['border-color', 'rgba(255, 255, 255, 0.7)']]; - -/** - * Programmatically add "Fork me Github" Ribbon using inline CSS - * Based on CSS from https,//github.com/simonwhitaker/github-fork-ribbon-css - * @param {string} [url] - do not need to include if URL is called from https://username.github.io/project/html - * @param {object} [options] - * @param {HTMLElement} [options.parent=document.body] - * @param {boolean} [options.fixed] - * @param {string} [options.corner=topright] some combination of top/bottom, and left/right - * @param {string} [options.text=fork me on github] text to show - * @param {string} [options.background=#a00] color for ribbon - */ -module.exports = function forkMe(url, options) { - options = options || {}; - var a = document.createElement('a'); - if (url) { - a.href = url; - } else { - var username = window.location.hostname.split('.')[0]; - var project = window.location.pathname.split('/')[1]; - a.href = 'https://github.com/' + username + '/' + project; - } - - a.title = a.innerText = options.text || 'fork me on github'; - a.setAttribute('data-ribbon', options.text || 'fork me on github'); - a.className = 'github-fork-ribbon-' + Math.round(Math.random() * 100000); - if (options.parent) { - options.parent.appendChild(a); - } else { - document.body.appendChild(a); - } - a.style.position = options.fixed ? 'fixed' : 'absolute'; - if (options.background) { - BEFORE[2][1] = options.background; - } - if (options.color) { - AFTER[1][1] = options.color; - } - for (var _style in RIBBON) { - a.style[_style] = RIBBON[_style]; - } - var beforeAfter = '{'; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = BEFORE_AFTER[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var _style2 = _step.value; - - beforeAfter += _style2[0] + ':' + _style2[1] + ';'; +Object.keys(accessibility).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return accessibility[key]; } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } + }); +}); +Object.keys(interaction).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return interaction[key]; } - } - - var before = beforeAfter; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = BEFORE[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var _style3 = _step2.value; - - before += _style3[0] + ':' + _style3[1] + ';'; + }); +}); +Object.keys(app).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return app[key]; } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } + }); +}); +Object.keys(core).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return core[key]; } - } - - var after = beforeAfter; - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - - try { - for (var _iterator3 = AFTER[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var _style4 = _step3.value; - - after += _style4[0] + ':' + _style4[1] + ';'; + }); +}); +Object.keys(extract).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return extract[key]; } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } + }); +}); +Object.keys(loaders).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return loaders[key]; } - } - - var bottom = void 0, - left = void 0; - if (options.side) { - bottom = options.side.toLowerCase().indexOf('bottom') !== -1; - left = options.side.toLowerCase().indexOf('left') !== -1; - } - if (bottom) { - a.style.top = 'auto'; - a.style.bottom = 0; - before += 'top:auto;bottom:3.23em;'; - after += 'top:auto;bottom:3.23em;'; - } - if (left) { - a.style.right = 'auto'; - a.style.left = 0; - before += 'right:auto;left:-3.23em;'; - after += 'right:auto;left:-3.23em;'; - } - if (left && !bottom || !left && bottom) { - before += 'transform:rotate(-45deg);'; - after += 'transform:rotate(-45deg);'; - } - var style = document.createElement('style'); - document.head.appendChild(style); - var sheet = style.sheet; - sheet.insertRule('.' + a.className + '::before' + before + '}'); - sheet.insertRule('.' + a.className + '::after' + after + '}'); -}; - -},{}],52:[function(require,module,exports){ -!function(e){var n=/iPhone/i,t=/iPod/i,r=/iPad/i,a=/\bAndroid(?:.+)Mobile\b/i,p=/Android/i,l=/\bAndroid(?:.+)SD4930UR\b/i,b=/\bAndroid(?:.+)(?:KF[A-Z]{2,4})\b/i,f=/Windows Phone/i,u=/\bWindows(?:.+)ARM\b/i,c=/BlackBerry/i,s=/BB10/i,v=/Opera Mini/i,h=/\b(CriOS|Chrome)(?:.+)Mobile/i,w=/\Mobile(?:.+)Firefox\b/i;function m(e,i){return e.test(i)}function i(e){var i=e||("undefined"!=typeof navigator?navigator.userAgent:""),o=i.split("[FBAN");void 0!==o[1]&&(i=o[0]),void 0!==(o=i.split("Twitter"))[1]&&(i=o[0]);var d={apple:{phone:m(n,i)&&!m(f,i),ipod:m(t,i),tablet:!m(n,i)&&m(r,i)&&!m(f,i),device:(m(n,i)||m(t,i)||m(r,i))&&!m(f,i)},amazon:{phone:m(l,i),tablet:!m(l,i)&&m(b,i),device:m(l,i)||m(b,i)},android:{phone:!m(f,i)&&m(l,i)||!m(f,i)&&m(a,i),tablet:!m(f,i)&&!m(l,i)&&!m(a,i)&&(m(b,i)||m(p,i)),device:!m(f,i)&&(m(l,i)||m(b,i)||m(a,i)||m(p,i))},windows:{phone:m(f,i),tablet:m(u,i),device:m(f,i)||m(u,i)},other:{blackberry:m(c,i),blackberry10:m(s,i),opera:m(v,i),firefox:m(w,i),chrome:m(h,i),device:m(c,i)||m(s,i)||m(v,i)||m(w,i)||m(h,i)}};return d.any=d.apple.device||d.android.device||d.windows.device||d.other.device,d.phone=d.apple.phone||d.android.phone||d.windows.phone,d.tablet=d.apple.tablet||d.android.tablet||d.windows.tablet,d}"undefined"!=typeof module&&module.exports&&"undefined"==typeof window?module.exports=i:"undefined"!=typeof module&&module.exports&&"undefined"!=typeof window?module.exports=i():"function"==typeof define&&define.amd?define([],e.isMobile=i()):e.isMobile=i()}(this); -},{}],53:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, '__esModule', { - value: true + }); }); - -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - -var MiniSignalBinding = (function () { - function MiniSignalBinding(fn, once, thisArg) { - if (once === undefined) once = false; - - _classCallCheck(this, MiniSignalBinding); - - this._fn = fn; - this._once = once; - this._thisArg = thisArg; - this._next = this._prev = this._owner = null; - } - - _createClass(MiniSignalBinding, [{ - key: 'detach', - value: function detach() { - if (this._owner === null) return false; - this._owner.detach(this); - return true; - } - }]); - - return MiniSignalBinding; -})(); - -function _addMiniSignalBinding(self, node) { - if (!self._head) { - self._head = node; - self._tail = node; - } else { - self._tail._next = node; - node._prev = self._tail; - self._tail = node; - } - - node._owner = self; - - return node; -} - -var MiniSignal = (function () { - function MiniSignal() { - _classCallCheck(this, MiniSignal); - - this._head = this._tail = undefined; - } - - _createClass(MiniSignal, [{ - key: 'handlers', - value: function handlers() { - var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; - - var node = this._head; - - if (exists) return !!node; - - var ee = []; - - while (node) { - ee.push(node); - node = node._next; - } - - return ee; - } - }, { - key: 'has', - value: function has(node) { - if (!(node instanceof MiniSignalBinding)) { - throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); - } - - return node._owner === this; - } - }, { - key: 'dispatch', - value: function dispatch() { - var node = this._head; - - if (!node) return false; - - while (node) { - if (node._once) this.detach(node); - node._fn.apply(node._thisArg, arguments); - node = node._next; - } - - return true; - } - }, { - key: 'add', - value: function add(fn) { - var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; - - if (typeof fn !== 'function') { - throw new Error('MiniSignal#add(): First arg must be a Function.'); - } - return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); - } - }, { - key: 'once', - value: function once(fn) { - var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; - - if (typeof fn !== 'function') { - throw new Error('MiniSignal#once(): First arg must be a Function.'); - } - return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); - } - }, { - key: 'detach', - value: function detach(node) { - if (!(node instanceof MiniSignalBinding)) { - throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); - } - if (node._owner !== this) return this; - - if (node._prev) node._prev._next = node._next; - if (node._next) node._next._prev = node._prev; - - if (node === this._head) { - this._head = node._next; - if (node._next === null) { - this._tail = null; +Object.keys(particles).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return particles[key]; + } + }); +}); +Object.keys(prepare).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return prepare[key]; + } + }); +}); +Object.keys(spritesheet).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return spritesheet[key]; + } + }); +}); +Object.keys(spriteTiling).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return spriteTiling[key]; } - } else if (node === this._tail) { - this._tail = node._prev; - this._tail._next = null; - } - - node._owner = null; - return this; - } - }, { - key: 'detachAll', - value: function detachAll() { - var node = this._head; - if (!node) return this; - - this._head = this._tail = null; - - while (node) { - node._owner = null; - node = node._next; - } - return this; - } - }]); - - return MiniSignal; -})(); - -MiniSignal.MiniSignalBinding = MiniSignalBinding; - -exports['default'] = MiniSignal; -module.exports = exports['default']; + }); +}); +Object.keys(textBitmap).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return textBitmap[key]; + } + }); +}); +Object.keys(ticker).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return ticker[key]; + } + }); +}); +Object.keys(constants).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return constants[key]; + } + }); +}); +Object.keys(display).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return display[key]; + } + }); +}); +Object.keys(graphics).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return graphics[key]; + } + }); +}); +Object.keys(math).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return math[key]; + } + }); +}); +Object.keys(mesh).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return mesh[key]; + } + }); +}); +Object.keys(meshExtras).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return meshExtras[key]; + } + }); +}); +Object.keys(runner).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return runner[key]; + } + }); +}); +Object.keys(sprite).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return sprite[key]; + } + }); +}); +Object.keys(spriteAnimated).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return spriteAnimated[key]; + } + }); +}); +Object.keys(text).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return text[key]; + } + }); +}); +Object.keys(settings).forEach(function (key) { + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return settings[key]; + } + }); +}); +exports.utils = utils; +exports.VERSION = VERSION; +exports.filters = filters; +exports.useDeprecated = useDeprecated; -},{}],54:[function(require,module,exports){ -/* -object-assign -(c) Sindre Sorhus -@license MIT -*/ +},{"@pixi/accessibility":5,"@pixi/app":6,"@pixi/constants":7,"@pixi/core":8,"@pixi/display":9,"@pixi/extract":10,"@pixi/filter-alpha":11,"@pixi/filter-blur":12,"@pixi/filter-color-matrix":13,"@pixi/filter-displacement":14,"@pixi/filter-fxaa":15,"@pixi/filter-noise":16,"@pixi/graphics":17,"@pixi/interaction":18,"@pixi/loaders":19,"@pixi/math":20,"@pixi/mesh":22,"@pixi/mesh-extras":21,"@pixi/mixin-cache-as-bitmap":23,"@pixi/mixin-get-child-by-name":24,"@pixi/mixin-get-global-position":25,"@pixi/particles":26,"@pixi/polyfill":27,"@pixi/prepare":28,"@pixi/runner":29,"@pixi/settings":30,"@pixi/sprite":33,"@pixi/sprite-animated":31,"@pixi/sprite-tiling":32,"@pixi/spritesheet":34,"@pixi/text":36,"@pixi/text-bitmap":35,"@pixi/ticker":37,"@pixi/utils":38}],50:[function(require,module,exports){ +/*! + * resource-loader - v3.0.1 + * https://github.com/pixijs/pixi-sound + * Compiled Tue, 02 Jul 2019 14:06:18 UTC + * + * resource-loader is licensed under the MIT license. + * http://www.opensource.org/licenses/mit-license + */ 'use strict'; -/* eslint-disable no-unused-vars */ -var getOwnPropertySymbols = Object.getOwnPropertySymbols; -var hasOwnProperty = Object.prototype.hasOwnProperty; -var propIsEnumerable = Object.prototype.propertyIsEnumerable; - -function toObject(val) { - if (val === null || val === undefined) { - throw new TypeError('Object.assign cannot be called with null or undefined'); - } - - return Object(val); -} - -function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - - // Detect buggy property enumeration order in older V8 versions. - - // https://bugs.chromium.org/p/v8/issues/detail?id=4118 - var test1 = new String('abc'); // eslint-disable-line no-new-wrappers - test1[5] = 'de'; - if (Object.getOwnPropertyNames(test1)[0] === '5') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2['_' + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function (n) { - return test2[n]; - }); - if (order2.join('') !== '0123456789') { - return false; - } - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test3 = {}; - 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join('') !== - 'abcdefghijklmnopqrst') { - return false; - } +Object.defineProperty(exports, '__esModule', { value: true }); - return true; - } catch (err) { - // We don't expect any of the above to throw, but better to be safe. - return false; - } -} +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -module.exports = shouldUseNative() ? Object.assign : function (target, source) { - var from; - var to = toObject(target); - var symbols; +var parseUri = _interopDefault(require('parse-uri')); +var Signal = _interopDefault(require('mini-signals')); - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments[s]); +/** + * Smaller version of the async library constructs. + * + * @namespace async + */ - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } +/** + * Noop function + * + * @ignore + * @function + * @memberof async + */ +function _noop() {} +/* empty */ - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]]; - } - } - } - } +/** + * Iterates an array in series. + * + * @memberof async + * @function eachSeries + * @param {Array.<*>} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ - return to; -}; -},{}],55:[function(require,module,exports){ -'use strict' +function eachSeries(array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; -module.exports = function parseURI (str, opts) { - opts = opts || {} + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } - var o = { - key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], - q: { - name: 'queryKey', - parser: /(?:^|&)([^&=]*)=?([^&]*)/g - }, - parser: { - strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, - loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + return; } - } - - var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) - var uri = {} - var i = 14 - while (i--) uri[o.key[i]] = m[i] || '' - - uri[o.q.name] = {} - uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { - if ($1) uri[o.q.name][$1] = $2 - }) - - return uri + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } else { + iterator(array[i++], next); + } + })(); } - -},{}],56:[function(require,module,exports){ -(function (global){ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pixi.js")):"function"==typeof define&&define.amd?define(["exports","pixi.js"],e):e((t=t||self).Viewport={},t.PIXI)}(this,function(t,e){"use strict";class i{constructor(t){this.viewport=t,this.touches=[],this.addListeners()}addListeners(){this.viewport.interactive=!0,this.viewport.forceHitArea||(this.viewport.hitArea=new e.Rectangle(0,0,this.viewport.worldWidth,this.viewport.worldHeight)),this.viewport.on("pointerdown",this.down,this),this.viewport.on("pointermove",this.move,this),this.viewport.on("pointerup",this.up,this),this.viewport.on("pointerupoutside",this.up,this),this.viewport.on("pointercancel",this.up,this),this.viewport.on("pointerout",this.up,this),this.wheelFunction=t=>this.handleWheel(t),this.viewport.options.divWheel.addEventListener("wheel",this.wheelFunction,{passive:this.viewport.options.passiveWheel}),this.isMouseDown=!1}destroy(){this.viewport.options.divWheel.removeEventListener("wheel",this.wheelFunction)}down(t){if(this.viewport.pause||!this.viewport.worldVisible)return;if("mouse"===t.data.pointerType?this.isMouseDown=!0:this.get(t.data.pointerId)||this.touches.push({id:t.data.pointerId,last:null}),1===this.count()){this.last=t.data.global.clone();const e=this.viewport.plugins.get("decelerate"),i=this.viewport.plugins.get("bounce");e&&e.isActive()||i&&i.isActive()?this.clickedAvailable=!1:this.clickedAvailable=!0}else this.clickedAvailable=!1;this.viewport.plugins.down(t)&&this.viewport.options.stopPropagation&&t.stopPropagation()}checkThreshold(t){return Math.abs(t)>=this.viewport.threshold}move(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.plugins.move(t);if(this.clickedAvailable){const e=t.data.global.x-this.last.x,i=t.data.global.y-this.last.y;(this.checkThreshold(e)||this.checkThreshold(i))&&(this.clickedAvailable=!1)}e&&this.viewport.options.stopPropagation&&t.stopPropagation()}up(t){if(this.viewport.pause||!this.viewport.worldVisible)return;"mouse"===t.data.pointerType&&(this.isMouseDown=!1),"mouse"!==t.data.pointerType&&this.remove(t.data.pointerId);const e=this.viewport.plugins.up(t);this.clickedAvailable&&0===this.count()&&(this.viewport.emit("clicked",{screen:this.last,world:this.viewport.toWorld(this.last),viewport:this}),this.clickedAvailable=!1),e&&this.viewport.options.stopPropagation&&t.stopPropagation()}getPointerPosition(t){let i=new e.Point;return this.viewport.options.interaction?this.viewport.options.interaction.mapPositionToPoint(i,t.clientX,t.clientY):(i.x=t.clientX,i.y=t.clientY),i}handleWheel(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.toLocal(this.getPointerPosition(t));if(this.viewport.left<=e.x&&e.x<=this.viewport.right&&this.viewport.top<=e.y&&e.y<=this.viewport.bottom){this.viewport.plugins.wheel(t)&&t.preventDefault()}}pause(){this.touches=[],this.isMouseDown=!1}get(t){for(let e of this.touches)if(e.id===t)return e;return null}remove(t){for(let e=0;e{t.includes(e.code)&&(this.keyIsPressed=!0)}),parent.addEventListener("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)})}mouseButtons(t){this.mouse=t&&"all"!==t?[-1!==t.indexOf("left"),-1!==t.indexOf("middle"),-1!==t.indexOf("right")]:[!0,!0,!0]}parseUnderflow(){const t=this.options.underflow.toLowerCase();"center"===t?(this.underflowX=0,this.underflowY=0):(this.underflowX=-1!==t.indexOf("left")?-1:-1!==t.indexOf("right")?1:0,this.underflowY=-1!==t.indexOf("top")?-1:-1!==t.indexOf("bottom")?1:0)}checkButtons(t){const e="mouse"===t.data.pointerType,i=this.parent.input.count();return!(!(1===i||i>1&&!this.parent.plugins.get("pinch"))||e&&!this.mouse[t.data.button])}checkKeyPress(t){return!!(!this.options.keyToPress||this.keyIsPressed||this.options.ignoreKeyToPressOnTouch&&"touch"===t.data.pointerType)}down(t){if(!this.paused)return this.checkButtons(t)&&this.checkKeyPress(t)?(this.last={x:t.data.global.x,y:t.data.global.y},this.current=t.data.pointerId,!0):void(this.last=null)}get active(){return this.moved}move(t){if(!this.paused&&this.last&&this.current===t.data.pointerId){const i=t.data.global.x,s=t.data.global.y,n=this.parent.input.count();if(1===n||n>1&&!this.parent.plugins.get("pinch")){const t=i-this.last.x,n=s-this.last.y;if(this.moved||this.xDirection&&this.parent.input.checkThreshold(t)||this.yDirection&&this.parent.input.checkThreshold(n)){const t={x:i,y:s};return this.xDirection&&(this.parent.x+=(t.x-this.last.x)*this.options.factor),this.yDirection&&(this.parent.y+=(t.y-this.last.y)*this.options.factor),this.last=t,this.moved||this.parent.emit("drag-start",{screen:new e.Point(this.last.x,this.last.y),world:this.parent.toWorld(new e.Point(this.last.x,this.last.y)),viewport:this.parent}),this.moved=!0,this.parent.emit("moved",{viewport:this.parent,type:"drag"}),!0}}else this.moved=!1}}up(){if(this.paused)return;const t=this.parent.input.touches;if(1===t.length){const e=t[0];return e.last&&(this.last={x:e.last.x,y:e.last.y},this.current=e.id),this.moved=!1,!0}if(this.last&&this.moved){const t=new e.Point(this.last.x,this.last.y);return this.parent.emit("drag-end",{screen:t,world:this.parent.toWorld(t),viewport:this.parent}),this.last=null,this.moved=!1,!0}}wheel(t){if(!this.paused&&this.options.wheel){if(!this.parent.plugins.get("wheel"))return this.xDirection&&(this.parent.x+=t.deltaX*this.options.wheelScroll*this.reverse),this.yDirection&&(this.parent.y+=t.deltaY*this.options.wheelScroll*this.reverse),this.options.clampWheel&&this.clamp(),this.parent.emit("wheel-scroll",this.parent),this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.options.passiveWheel||t.preventDefault(),!0}}resume(){this.last=null,this.paused=!1}clamp(){const t=this.parent.plugins.get("decelerate")||{};if("y"!==this.options.clampWheel)if(this.parent.screenWorldWidththis.parent.worldWidth&&(this.parent.x=-this.parent.worldWidth*this.parent.scale.x+this.parent.screenWidth,t.x=0);if("x"!==this.options.clampWheel)if(this.parent.screenWorldHeightthis.parent.worldHeight&&(this.parent.y=-this.parent.worldHeight*this.parent.scale.y+this.parent.screenHeight,t.y=0)}}const a={noDrag:!1,percent:1,center:null};class p extends h{constructor(t,e={}){super(t),this.options=Object.assign({},a,e)}down(){if(this.parent.input.count()>=2)return this.active=!0,!0}move(t){if(this.paused||!this.active)return;const e=t.data.global.x,i=t.data.global.y,s=this.parent.input.touches;if(s.length>=2){const n=s[0],h=s[1],o=n.last&&h.last?Math.sqrt(Math.pow(h.last.x-n.last.x,2)+Math.pow(h.last.y-n.last.y,2)):null;if(n.id===t.data.pointerId?n.last={x:e,y:i,data:t.data}:h.id===t.data.pointerId&&(h.last={x:e,y:i,data:t.data}),o){let t;const e={x:n.last.x+(h.last.x-n.last.x)/2,y:n.last.y+(h.last.y-n.last.y)/2};this.options.center||(t=this.parent.toLocal(e));const i=(Math.sqrt(Math.pow(h.last.x-n.last.x,2)+Math.pow(h.last.y-n.last.y,2))-o)/this.parent.screenWidth*this.parent.scale.x*this.options.percent;this.parent.scale.x+=i,this.parent.scale.y+=i,this.parent.emit("zoomed",{viewport:this.parent,type:"pinch"});const s=this.parent.plugins.get("clamp-zoom");if(s&&s.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=e.x-i.x,this.parent.y+=e.y-i.y,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})}!this.options.noDrag&&this.lastCenter&&(this.parent.x+=e.x-this.lastCenter.x,this.parent.y+=e.y-this.lastCenter.y,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})),this.lastCenter=e,this.moved=!0}else this.pinching||(this.parent.emit("pinch-start",this.parent),this.pinching=!0);return!0}}up(){if(this.pinching&&this.parent.input.touches.length<=1)return this.active=!1,this.lastCenter=null,this.pinching=!1,this.moved=!1,this.parent.emit("pinch-end",this.parent),!0}}const l={left:!1,right:!1,top:!1,bottom:!1,direction:null,underflow:"center"};class c extends h{constructor(t,e={}){super(t),this.options=Object.assign({},l,e),this.options.direction&&(this.options.left="x"===this.options.direction||"all"===this.options.direction||null,this.options.right="x"===this.options.direction||"all"===this.options.direction||null,this.options.top="y"===this.options.direction||"all"===this.options.direction||null,this.options.bottom="y"===this.options.direction||"all"===this.options.direction||null),this.parseUnderflow(),this.last={x:null,y:null,scaleX:null,scaleY:null},this.update()}parseUnderflow(){const t=this.options.underflow.toLowerCase();"none"===t?this.noUnderflow=!0:"center"===t?(this.underflowX=this.underflowY=0,this.noUnderflow=!1):(this.underflowX=-1!==t.indexOf("left")?-1:-1!==t.indexOf("right")?1:0,this.underflowY=-1!==t.indexOf("top")?-1:-1!==t.indexOf("bottom")?1:0,this.noUnderflow=!1)}move(){return this.update(),!1}update(){if(this.paused)return;if(this.parent.x===this.last.x&&this.parent.y===this.last.y&&this.parent.scale.x===this.last.scaleX&&this.parent.scale.y===this.last.scaleY)return;const t={x:this.parent.x,y:this.parent.y},e=this.parent.plugins.decelerate||{};if(null!==this.options.left||null!==this.options.right){let i=!1;if(this.parent.screenWorldWidth(!0===this.options.right?this.parent.worldWidth:this.options.right)&&(this.parent.x=-(!0===this.options.right?this.parent.worldWidth:this.options.right)*this.parent.scale.x+this.parent.screenWidth,e.x=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-x"})}if(null!==this.options.top||null!==this.options.bottom){let i=!1;if(this.parent.screenWorldHeight(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)&&(this.parent.y=-(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)*this.parent.scale.y+this.parent.screenHeight,e.y=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-y"})}this.last.x=this.parent.x,this.last.y=this.parent.y,this.last.scaleX=this.parent.scale.x,this.last.scaleY=this.parent.scale.y}reset(){this.update()}}const d={minWidth:null,minHeight:null,maxWidth:null,maxHeight:null};class u extends h{constructor(t,e={}){super(t),this.options=Object.assign({},d,e),this.clamp()}resize(){this.clamp()}clamp(){if(this.paused)return;let t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight;if(null!==this.options.minWidth&&tthis.options.maxWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.maxWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.minHeight&&ethis.options.maxHeight){const t=this.parent.scale.y;this.parent.fitHeight(this.options.maxHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/t,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}}reset(){this.clamp()}}const g={friction:.95,bounce:.8,minSpeed:.01};class m extends h{constructor(t,e={}){super(t),this.options=Object.assign({},g,e),this.saved=[],this.reset(),this.parent.on("moved",t=>this.moved(t))}destroy(){this.parent}down(){this.saved=[],this.x=this.y=!1}isActive(){return this.x||this.y}move(){if(this.paused)return;const t=this.parent.input.count();(1===t||t>1&&!this.parent.plugins.get("pinch"))&&(this.saved.push({x:this.parent.x,y:this.parent.y,time:performance.now()}),this.saved.length>60&&this.saved.splice(0,30))}moved(t){if(this.saved.length){const e=this.saved[this.saved.length-1];"clamp-x"===t.type?e.x===t.original.x&&(e.x=this.parent.x):"clamp-y"===t.type&&e.y===t.original.y&&(e.y=this.parent.y)}}up(){if(0===this.parent.input.count()&&this.saved.length){const t=performance.now();for(let e of this.saved)if(e.time>=t-100){const i=t-e.time;this.x=(this.parent.x-e.x)/i,this.y=(this.parent.y-e.y)/i,this.percentChangeX=this.percentChangeY=this.options.friction;break}}}activate(t){void 0!==(t=t||{}).x&&(this.x=t.x,this.percentChangeX=this.options.friction),void 0!==t.y&&(this.y=t.y,this.percentChangeY=this.options.friction)}update(t){if(this.paused)return;let e;this.x&&(this.parent.x+=this.x*t,this.x*=this.percentChangeX,Math.abs(this.x)=this.options.time?(this.parent.x=e.end,this.toX=null,this.parent.emit("bounce-x-end",this.parent)):this.parent.x=this.ease(e.time,e.start,e.delta,this.options.time)}if(this.toY){const e=this.toY;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-y"}),e.time>=this.options.time?(this.parent.y=e.end,this.toY=null,this.parent.emit("bounce-y-end",this.parent)):this.parent.y=this.ease(e.time,e.start,e.delta,this.options.time)}}}calcUnderflowX(){let t;switch(this.underflowX){case-1:t=0;break;case 1:t=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:t=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}return t}calcUnderflowY(){let t;switch(this.underflowY){case-1:t=0;break;case 1:t=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:t=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}return t}oob(){const t=this.options.bounceBox;if(t){const i=void 0===t.x?0:t.x,s=void 0===t.y?0:t.y,n=void 0===t.width?this.parent.worldWidth:t.width,h=void 0===t.height?this.parent.worldHeight:t.height;return{left:this.parent.leftn,top:this.parent.toph,topLeft:new e.Point(i*this.parent.scale.x,s*this.parent.scale.y),bottomRight:new e.Point(n*this.parent.scale.x-this.parent.screenWidth,h*this.parent.scale.y-this.parent.screenHeight)}}return{left:this.parent.left<0,right:this.parent.right>this.parent.worldWidth,top:this.parent.top<0,bottom:this.parent.bottom>this.parent.worldHeight,topLeft:new e.Point(0,0),bottomRight:new e.Point(this.parent.worldWidth*this.parent.scale.x-this.parent.screenWidth,this.parent.worldHeight*this.parent.scale.y-this.parent.screenHeight)}}bounce(){if(this.paused)return;let t,e=this.parent.plugins.get("decelerate");e&&(e.x||e.y)&&(e.x&&e.percentChangeX===e.options.friction||e.y&&e.percentChangeY===e.options.friction)&&(((t=this.oob()).left&&this.left||t.right&&this.right)&&(e.percentChangeX=this.options.friction),(t.top&&this.top||t.bottom&&this.bottom)&&(e.percentChangeY=this.options.friction));const i=this.parent.plugins.get("drag")||{},s=this.parent.plugins.get("pinch")||{};if(e=e||{},!(i.active||s.active||this.toX&&this.toY||e.x&&e.y)){const i=(t=t||this.oob()).topLeft,s=t.bottomRight;if(!this.toX&&!e.x){let e=null;t.left&&this.left?e=this.parent.screenWorldWidththis.options.time)i=!0,s=this.startX+this.deltaX,n=this.startY+this.deltaY;else{const t=this.ease(e.time,0,1,this.options.time);s=this.startX+this.deltaX*t,n=this.startY+this.deltaY*t}this.options.topLeft?this.parent.moveCorner(s,n):this.parent.moveCenter(s,n),this.parent.emit("moved",{viewport:this.parent,type:"snap"}),i&&(this.options.removeOnComplete&&this.parent.plugins.remove("snap"),this.parent.emit("snap-end",this.parent),this.snapping=null)}else{const t=this.options.topLeft?this.parent.corner:this.parent.center;t.x===this.x&&t.y===this.y||this.snapStart()}}}const H={width:0,height:0,time:1e3,ease:"easeInOutSine",center:null,interrupt:!0,removeOnComplete:!1,removeOnInterrupts:!1,forceStart:!1,noMove:!1};class M extends h{constructor(t,e={}){super(t),this.options=Object.assign({},H,e),this.ease=y(this.options.ease),this.options.width>0&&(this.xScale=t.screenWidth/this.options.width),this.options.height>0&&(this.yScale=t.screenHeight/this.options.height),this.xIndependent=!!this.xScale,this.yIndependent=!!this.yScale,this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale,0===this.options.time?(t.container.scale.x=this.xScale,t.container.scale.y=this.yScale,this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom")):e.forceStart&&this.createSnapping()}createSnapping(){const t=this.parent.scale;this.snapping={time:0,startX:t.x,startY:t.y,deltaX:this.xScale-t.x,deltaY:this.yScale-t.y},this.parent.emit("snap-zoom-start",this.parent)}resize(){this.snapping=null,this.options.width>0&&(this.xScale=this.parent.screenWidth/this.options.width),this.options.height>0&&(this.yScale=this.parent.screenHeight/this.options.height),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale}wheel(){this.options.removeOnInterrupt&&this.parent.plugins.remove("snap-zoom")}down(){this.options.removeOnInterrupt?this.parent.plugins.remove("snap-zoom"):this.options.interrupt&&(this.snapping=null)}update(t){if(this.paused)return;if(this.options.interrupt&&0!==this.parent.input.count())return;let e;if(this.options.center||this.options.noMove||(e=this.parent.center),this.snapping){if(this.snapping){const i=this.snapping;if(i.time+=t,i.time>=this.options.time)this.parent.scale.set(this.xScale,this.yScale),this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom"),this.parent.emit("snap-zoom-end",this.parent),this.snapping=null;else{const t=this.snapping;this.parent.scale.x=this.ease(t.time,t.startX,t.deltaX,this.options.time),this.parent.scale.y=this.ease(t.time,t.startY,t.deltaY,this.options.time)}const s=this.parent.plugins.get("clamp-zoom");s&&s.clamp(),this.options.noMove||(this.options.center?this.parent.moveCenter(this.options.center):this.parent.moveCenter(e))}}else this.parent.scale.x===this.xScale&&this.parent.scale.y===this.yScale||this.createSnapping()}resume(){this.snapping=null,super.resume()}}const S={speed:0,acceleration:null,radius:null};class O extends h{constructor(t,e,i={}){super(t),this.target=e,this.options=Object.assign({},S,i),this.velocity={x:0,y:0}}update(t){if(this.paused)return;const e=this.parent.center;let i=this.target.x,s=this.target.y;if(this.options.radius){if(!(Math.sqrt(Math.pow(this.target.y-e.y,2)+Math.pow(this.target.x-e.x,2))>this.options.radius))return;{const t=Math.atan2(this.target.y-e.y,this.target.x-e.x);i=this.target.x-Math.cos(t)*this.options.radius,s=this.target.y-Math.sin(t)*this.options.radius}}const n=i-e.x,h=s-e.y;if(n||h)if(this.options.speed)if(this.options.acceleration){const o=Math.atan2(s-e.y,i-e.x),r=Math.sqrt(Math.pow(n,2)+Math.pow(h,2));if(r){const a=(Math.pow(this.velocity.x,2)+Math.pow(this.velocity.y,2))/(2*this.options.acceleration);this.velocity=r>a?{x:Math.min(this.velocity.x+this.options.acceleration*t,this.options.speed),y:Math.min(this.velocity.y+this.options.acceleration*t,this.options.speed)}:{x:Math.max(this.velocity.x-this.options.acceleration*this.options.speed,0),y:Math.max(this.velocity.y-this.options.acceleration*this.options.speed,0)};const p=Math.cos(o)*this.velocity.x,l=Math.sin(o)*this.velocity.y,c=Math.abs(p)>Math.abs(n)?i:e.x+p,d=Math.abs(l)>Math.abs(h)?s:e.y+l;this.parent.moveCenter(c,d),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}else{const t=Math.atan2(s-e.y,i-e.x),o=Math.cos(t)*this.options.speed,r=Math.sin(t)*this.options.speed,a=Math.abs(o)>Math.abs(n)?i:e.x+o,p=Math.abs(r)>Math.abs(h)?s:e.y+r;this.parent.moveCenter(a,p),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}else this.parent.moveCenter(i,s),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}const z={percent:.1,smooth:!1,interrupt:!0,reverse:!1,center:null};class I extends h{constructor(t,e={}){super(t),this.options=Object.assign({},z,e)}down(){this.options.interrupt&&(this.smoothing=null)}update(){if(this.smoothing){const t=this.smoothingCenter,e=this.smoothing;let i;this.options.center||(i=this.parent.toLocal(t)),this.parent.scale.x+=e.x,this.parent.scale.y+=e.y,this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const s=this.parent.plugins.get("clamp-zoom");if(s&&s.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const e=this.parent.toGlobal(i);this.parent.x+=t.x-e.x,this.parent.y+=t.y-e.y}this.smoothingCount++,this.smoothingCount>=this.options.smooth&&(this.smoothing=null)}}wheel(t){if(this.paused)return;let e=this.parent.input.getPointerPosition(t);const i=(this.options.reverse?-1:1)*-t.deltaY*(t.deltaMode?120:1)/500,s=Math.pow(2,(1+this.options.percent)*i);if(this.options.smooth){const t={x:this.smoothing?this.smoothing.x*(this.options.smooth-this.smoothingCount):0,y:this.smoothing?this.smoothing.y*(this.options.smooth-this.smoothingCount):0};this.smoothing={x:((this.parent.scale.x+t.x)*s-this.parent.scale.x)/this.options.smooth,y:((this.parent.scale.y+t.y)*s-this.parent.scale.y)/this.options.smooth},this.smoothingCount=0,this.smoothingCenter=e}else{let t;this.options.center||(t=this.parent.toLocal(e)),this.parent.scale.x*=s,this.parent.scale.y*=s,this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const i=this.parent.plugins.get("clamp-zoom");if(i&&i.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=e.x-i.x,this.parent.y+=e.y-i.y}}return this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel",{wheel:{dx:t.deltaX,dy:t.deltaY,dz:t.deltaZ},event:t,viewport:this.parent}),!this.parent.options.passiveWheel||void 0}}const C={radius:null,distance:null,top:null,bottom:null,left:null,right:null,speed:8,reverse:!1,noDecelerate:!1,linear:!1,allowButtons:!1};class k extends h{constructor(t,e={}){super(t),this.options=Object.assign({},C,e),this.reverse=this.options.reverse?1:-1,this.radiusSquared=Math.pow(this.options.radius,2),this.resize()}resize(){const t=this.options.distance;null!==t?(this.left=t,this.top=t,this.right=this.parent.worldScreenWidth-t,this.bottom=this.parent.worldScreenHeight-t):this.radius||(this.left=this.options.left,this.top=this.options.top,this.right=null===this.options.right?null:this.parent.worldScreenWidth-this.options.right,this.bottom=null===this.options.bottom?null:this.parent.worldScreenHeight-this.options.bottom)}down(){this.options.allowButtons||(this.horizontal=this.vertical=null)}move(t){if("mouse"!==t.data.pointerType&&1!==t.data.identifier||!this.options.allowButtons&&0!==t.data.buttons)return;const e=t.data.global.x,i=t.data.global.y;if(this.radiusSquared){const t=this.parent.toScreen(this.parent.center);if(Math.pow(t.x-e,2)+Math.pow(t.y-i,2)>=this.radiusSquared){const s=Math.atan2(t.y-i,t.x-e);this.options.linear?(this.horizontal=Math.round(Math.cos(s))*this.options.speed*this.reverse*.06,this.vertical=Math.round(Math.sin(s))*this.options.speed*this.reverse*.06):(this.horizontal=Math.cos(s)*this.options.speed*this.reverse*.06,this.vertical=Math.sin(s)*this.options.speed*this.reverse*.06)}else this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=0}else null!==this.left&&ethis.right?this.horizontal=-1*this.reverse*this.options.speed*.06:(this.decelerateHorizontal(),this.horizontal=0),null!==this.top&&ithis.bottom?this.vertical=-1*this.reverse*this.options.speed*.06:(this.decelerateVertical(),this.vertical=0)}decelerateHorizontal(){const t=this.parent.plugins.get("decelerate");this.horizontal&&t&&!this.options.noDecelerate&&t.activate({x:this.horizontal*this.options.speed*this.reverse/(1e3/60)})}decelerateVertical(){const t=this.parent.plugins.get("decelerate");this.vertical&&t&&!this.options.noDecelerate&&t.activate({y:this.vertical*this.options.speed*this.reverse/(1e3/60)})}up(){this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=null}update(){if(!this.paused&&(this.horizontal||this.vertical)){const t=this.parent.center;this.horizontal&&(t.x+=this.horizontal*this.options.speed),this.vertical&&(t.y+=this.vertical*this.options.speed),this.parent.moveCenter(t),this.parent.emit("moved",{viewport:this.parent,type:"mouse-edges"})}}}const P={screenWidth:window.innerWidth,screenHeight:window.innerHeight,worldWidth:null,worldHeight:null,threshold:5,passiveWheel:!0,stopPropagation:!1,forceHitArea:null,noTicker:!1,interaction:null,disableOnContextMenu:!1};t.Plugin=h,t.Viewport=class extends e.Container{constructor(t={}){if(super(),this.options=Object.assign({},P,t),t.ticker)this.options.ticker=t.ticker;else{let i;const s=e;i=parseInt(/^(\d+)\./.exec(e.VERSION)[1])<5?s.ticker.shared:s.Ticker.shared,this.options.ticker=t.ticker||i}this.screenWidth=this.options.screenWidth,this.screenHeight=this.options.screenHeight,this._worldWidth=this.options.worldWidth,this._worldHeight=this.options.worldHeight,this.forceHitArea=this.options.forceHitArea,this.threshold=this.options.threshold,this.options.divWheel=this.options.divWheel||document.body,this.options.disableOnContextMenu&&(this.options.divWheel.oncontextmenu=t=>t.preventDefault()),this.options.noTicker||(this.tickerFunction=()=>this.update(this.options.ticker.elapsedMS),this.options.ticker.add(this.tickerFunction)),this.input=new i(this),this.plugins=new n(this)}destroy(t){this.options.noTicker||this.options.ticker.remove(this.tickerFunction),this.input.destroy(),super.destroy(t)}update(t){this.pause||(this.plugins.update(t),this.lastViewport&&(this.lastViewport.x!==this.x||this.lastViewport.y!==this.y?this.moving=!0:this.moving&&(this.emit("moved-end",this),this.moving=!1),this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y?this.zooming=!0:this.zooming&&(this.emit("zoomed-end",this),this.zooming=!1)),this.forceHitArea||(this._hitAreaDefault=new e.Rectangle(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight),this.hitArea=this._hitAreaDefault),this._dirty=this._dirty||!this.lastViewport||this.lastViewport.x!==this.x||this.lastViewport.y!==this.y||this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y,this.lastViewport={x:this.x,y:this.y,scaleX:this.scale.x,scaleY:this.scale.y},this.emit("frame-end",this))}resize(t=window.innerWidth,e=window.innerHeight,i,s){this.screenWidth=t,this.screenHeight=e,void 0!==i&&(this._worldWidth=i),void 0!==s&&(this._worldHeight=s),this.plugins.resize()}get worldWidth(){return this._worldWidth?this._worldWidth:this.width/this.scale.x}set worldWidth(t){this._worldWidth=t,this.plugins.resize()}get worldHeight(){return this._worldHeight?this._worldHeight:this.height/this.scale.y}set worldHeight(t){this._worldHeight=t,this.plugins.resize()}getVisibleBounds(){return new e.Rectangle(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight)}toWorld(t,i){return 2===arguments.length?this.toLocal(new e.Point(t,i)):this.toLocal(t)}toScreen(t,i){return 2===arguments.length?this.toGlobal(new e.Point(t,i)):this.toGlobal(t)}get worldScreenWidth(){return this.screenWidth/this.scale.x}get worldScreenHeight(){return this.screenHeight/this.scale.y}get screenWorldWidth(){return this.worldWidth*this.scale.x}get screenWorldHeight(){return this.worldHeight*this.scale.y}get center(){return new e.Point(this.worldScreenWidth/2-this.x/this.scale.x,this.worldScreenHeight/2-this.y/this.scale.y)}set center(t){this.moveCenter(t)}moveCenter(){let t,e;return isNaN(arguments[0])?(t=arguments[0].x,e=arguments[0].y):(t=arguments[0],e=arguments[1]),this.position.set((this.worldScreenWidth/2-t)*this.scale.x,(this.worldScreenHeight/2-e)*this.scale.y),this.plugins.reset(),this.dirty=!0,this}get corner(){return new e.Point(-this.x/this.scale.x,-this.y/this.scale.y)}set corner(t){this.moveCorner(t)}moveCorner(t,e){return 1===arguments.length?this.position.set(-t.x*this.scale.x,-t.y*this.scale.y):this.position.set(-t*this.scale.x,-e*this.scale.y),this.plugins.reset(),this}fitWidth(t,e,i=!0,s){let n;e&&(n=this.center),this.scale.x=this.screenWidth/t,i&&(this.scale.y=this.scale.x);const h=this.plugins.get("clamp-zoom");return!s&&h&&h.clamp(),e&&this.moveCenter(n),this}fitHeight(t,e,i=!0,s){let n;e&&(n=this.center),this.scale.y=this.screenHeight/t,i&&(this.scale.x=this.scale.y);const h=this.plugins.get("clamp-zoom");return!s&&h&&h.clamp(),e&&this.moveCenter(n),this}fitWorld(t){let e;t&&(e=this.center),this.scale.x=this.screenWidth/this.worldWidth,this.scale.y=this.screenHeight/this.worldHeight,this.scale.xthis.worldWidth,top:this.top<0,bottom:this.bottom>this._worldHeight,cornerPoint:new e.Point(this.worldWidth*this.scale.x-this.screenWidth,this.worldHeight*this.scale.y-this.screenHeight)}}get right(){return-this.x/this.scale.x+this.worldScreenWidth}set right(t){this.x=-t*this.scale.x+this.screenWidth,this.plugins.reset()}get left(){return-this.x/this.scale.x}set left(t){this.x=-t*this.scale.x,this.plugins.reset()}get top(){return-this.y/this.scale.y}set top(t){this.y=-t*this.scale.y,this.plugins.reset()}get bottom(){return-this.y/this.scale.y+this.worldScreenHeight}set bottom(t){this.y=-t*this.scale.y+this.screenHeight,this.plugins.reset()}get dirty(){return this._dirty}set dirty(t){this._dirty=t}get forceHitArea(){return this._forceHitArea}set forceHitArea(t){t?(this._forceHitArea=t,this.hitArea=t):(this._forceHitArea=null,this.hitArea=new e.Rectangle(0,0,this.worldWidth,this.worldHeight))}drag(t){return this.plugins.add("drag",new r(this,t)),this}clamp(t){return this.plugins.add("clamp",new c(this,t)),this}decelerate(t){return this.plugins.add("decelerate",new m(this,t)),this}bounce(t){return this.plugins.add("bounce",new v(this,t)),this}pinch(t){return this.plugins.add("pinch",new p(this,t)),this}snap(t,e,i){return this.plugins.add("snap",new W(this,t,e,i)),this}follow(t,e){return this.plugins.add("follow",new O(this,t,e)),this}wheel(t){return this.plugins.add("wheel",new I(this,t)),this}clampZoom(t){return this.plugins.add("clamp-zoom",new u(this,t)),this}mouseEdges(t){return this.plugins.add("mouse-edges",new k(this,t)),this}get pause(){return this._pause}set pause(t){this._pause=t,this.lastViewport=null,this.moving=!1,this.zooming=!1,t&&this.input.pause()}ensureVisible(t,e,i,s){tthis.right&&(this.right=t+i),ethis.bottom&&(this.bottom=e+s)}},Object.defineProperty(t,"__esModule",{value:!0})}); - - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"pixi.js":57}],57:[function(require,module,exports){ -/*! - * pixi.js - v5.2.0 - * Compiled Wed, 06 Nov 2019 02:32:43 UTC +/** + * Ensures a function is only called once. * - * pixi.js is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license + * @ignore + * @memberof async + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. */ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); - -require('@pixi/polyfill'); -var accessibility = require('@pixi/accessibility'); -var extract = require('@pixi/extract'); -var interaction = require('@pixi/interaction'); -var prepare = require('@pixi/prepare'); -var utils = require('@pixi/utils'); -var app = require('@pixi/app'); -var core = require('@pixi/core'); -var loaders = require('@pixi/loaders'); -var particles = require('@pixi/particles'); -var spritesheet = require('@pixi/spritesheet'); -var spriteTiling = require('@pixi/sprite-tiling'); -var textBitmap = require('@pixi/text-bitmap'); -var ticker = require('@pixi/ticker'); -var filterAlpha = require('@pixi/filter-alpha'); -var filterBlur = require('@pixi/filter-blur'); -var filterColorMatrix = require('@pixi/filter-color-matrix'); -var filterDisplacement = require('@pixi/filter-displacement'); -var filterFxaa = require('@pixi/filter-fxaa'); -var filterNoise = require('@pixi/filter-noise'); -require('@pixi/mixin-cache-as-bitmap'); -require('@pixi/mixin-get-child-by-name'); -require('@pixi/mixin-get-global-position'); -var constants = require('@pixi/constants'); -var display = require('@pixi/display'); -var graphics = require('@pixi/graphics'); -var math = require('@pixi/math'); -var mesh = require('@pixi/mesh'); -var meshExtras = require('@pixi/mesh-extras'); -var runner = require('@pixi/runner'); -var sprite = require('@pixi/sprite'); -var spriteAnimated = require('@pixi/sprite-animated'); -var text = require('@pixi/text'); -var settings = require('@pixi/settings'); - -var v5 = '5.0.0'; +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; +} /** - * Deprecations (backward compatibilities) are automatically applied for browser bundles - * in the UMD module format. If using Webpack or Rollup, you'll need to apply these - * deprecations manually by doing something like this: - * @example - * import * as PIXI from 'pixi.js'; - * PIXI.useDeprecated(); // MUST be bound to namespace - * @memberof PIXI - * @function useDeprecated + * Async queue implementation, + * + * @memberof async + * @function queue + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. */ -function useDeprecated() -{ - var PIXI = this; - - Object.defineProperties(PIXI, { - /** - * @constant {RegExp|string} SVG_SIZE - * @memberof PIXI - * @see PIXI.resources.SVGResource.SVG_SIZE - * @deprecated since 5.0.0 - */ - SVG_SIZE: { - get: function get() - { - utils.deprecation(v5, 'PIXI.utils.SVG_SIZE property has moved to PIXI.resources.SVGResource.SVG_SIZE'); - - return PIXI.SVGResource.SVG_SIZE; - }, - }, - /** - * @class PIXI.TransformStatic - * @deprecated since 5.0.0 - * @see PIXI.Transform - */ - TransformStatic: { - get: function get() - { - utils.deprecation(v5, 'PIXI.TransformStatic class has been removed, use PIXI.Transform'); - - return PIXI.Transform; - }, - }, - - /** - * @class PIXI.TransformBase - * @deprecated since 5.0.0 - * @see PIXI.Transform - */ - TransformBase: { - get: function get() - { - utils.deprecation(v5, 'PIXI.TransformBase class has been removed, use PIXI.Transform'); - return PIXI.Transform; - }, - }, +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } - /** - * Constants that specify the transform type. - * - * @static - * @constant - * @name TRANSFORM_MODE - * @memberof PIXI - * @enum {number} - * @deprecated since 5.0.0 - * @property {number} STATIC - * @property {number} DYNAMIC - */ - TRANSFORM_MODE: { - get: function get() - { - utils.deprecation(v5, 'PIXI.TRANSFORM_MODE property has been removed'); + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); - return { STATIC: 0, DYNAMIC: 1 }; - }, - }, + if (q._tasks.length === 0) { + q.empty(); + } - /** - * @class PIXI.WebGLRenderer - * @see PIXI.Renderer - * @deprecated since 5.0.0 - */ - WebGLRenderer: { - get: function get() - { - utils.deprecation(v5, 'PIXI.WebGLRenderer class has moved to PIXI.Renderer'); + workers += 1; - return PIXI.Renderer; - }, - }, + if (workers === q.concurrency) { + q.saturated(); + } - /** - * @class PIXI.CanvasRenderTarget - * @see PIXI.utils.CanvasRenderTarget - * @deprecated since 5.0.0 - */ - CanvasRenderTarget: { - get: function get() - { - utils.deprecation(v5, 'PIXI.CanvasRenderTarget class has moved to PIXI.utils.CanvasRenderTarget'); + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } - return PIXI.utils.CanvasRenderTarget; - }, - }, + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } - /** - * @memberof PIXI - * @name loader - * @type {PIXI.Loader} - * @see PIXI.Loader.shared - * @deprecated since 5.0.0 - */ - loader: { - get: function get() - { - utils.deprecation(v5, 'PIXI.loader instance has moved to PIXI.Loader.shared'); + q.paused = false; // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause - return PIXI.Loader.shared; - }, - }, + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; - /** - * @class PIXI.FilterManager - * @see PIXI.systems.FilterSystem - * @deprecated since 5.0.0 - */ - FilterManager: { - get: function get() - { - utils.deprecation(v5, 'PIXI.FilterManager class has moved to PIXI.systems.FilterSystem'); + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } - return PIXI.systems.FilterSystem; - }, - }, + q.started = true; - /** - * @namespace PIXI.CanvasTinter - * @see PIXI.canvasUtils - * @deprecated since 5.2.0 - */ - CanvasTinter: { - get: function get() - { - utils.deprecation('5.2.0', 'PIXI.CanvasTinter namespace has moved to PIXI.canvasUtils'); + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + return; + } - return PIXI.canvasUtils; - }, - }, + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; - /** - * @namespace PIXI.GroupD8 - * @see PIXI.groupD8 - * @deprecated since 5.2.0 - */ - GroupD8: { - get: function get() - { - utils.deprecation('5.2.0', 'PIXI.GroupD8 namespace has moved to PIXI.groupD8'); + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } - return PIXI.groupD8; - }, - }, - }); + setTimeout(function () { + return q.process(); + }, 1); + } - /** - * This namespace has been removed. All classes previous nested - * under this namespace have been moved to the top-level `PIXI` object. - * @namespace PIXI.extras - * @deprecated since 5.0.0 - */ - PIXI.extras = {}; + function _next(task) { + return function next() { + workers -= 1; + task.callback.apply(task, arguments); - Object.defineProperties(PIXI.extras, { - /** - * @class PIXI.extras.TilingSprite - * @see PIXI.TilingSprite - * @deprecated since 5.0.0 - */ - TilingSprite: { - get: function get() - { - utils.deprecation(v5, 'PIXI.extras.TilingSprite class has moved to PIXI.TilingSprite'); + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } - return PIXI.TilingSprite; - }, - }, - /** - * @class PIXI.extras.TilingSpriteRenderer - * @see PIXI.TilingSpriteRenderer - * @deprecated since 5.0.0 - */ - TilingSpriteRenderer: { - get: function get() - { - utils.deprecation(v5, 'PIXI.extras.TilingSpriteRenderer class has moved to PIXI.TilingSpriteRenderer'); + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } - return PIXI.TilingSpriteRenderer; - }, - }, - /** - * @class PIXI.extras.AnimatedSprite - * @see PIXI.AnimatedSprite - * @deprecated since 5.0.0 - */ - AnimatedSprite: { - get: function get() - { - utils.deprecation(v5, 'PIXI.extras.AnimatedSprite class has moved to PIXI.AnimatedSprite'); + if (q.idle()) { + q.drain(); + } - return PIXI.AnimatedSprite; - }, - }, - /** - * @class PIXI.extras.BitmapText - * @see PIXI.BitmapText - * @deprecated since 5.0.0 - */ - BitmapText: { - get: function get() - { - utils.deprecation(v5, 'PIXI.extras.BitmapText class has moved to PIXI.BitmapText'); + q.process(); + }; + } - return PIXI.BitmapText; - }, - }, - }); + return q; +} - Object.defineProperties(PIXI.utils, { - /** - * @function PIXI.utils.getSvgSize - * @see PIXI.resources.SVGResource.getSize - * @deprecated since 5.0.0 - */ - getSvgSize: { - get: function get() - { - utils.deprecation(v5, 'PIXI.utils.getSvgSize function has moved to PIXI.resources.SVGResource.getSize'); +var async = ({ + eachSeries: eachSeries, + queue: queue +}); - return PIXI.SVGResource.getSize; - }, - }, - }); +// a simple in-memory cache for resources +var cache = {}; +/** + * A simple in-memory cache for resource. + * + * @memberof middleware + * @function caching + * @example + * import { Loader, middleware } from 'resource-loader'; + * const loader = new Loader(); + * loader.use(middleware.caching); + * @param {Resource} resource - Current Resource + * @param {function} next - Callback when complete + */ - /** - * All classes on this namespace have moved to the high-level `PIXI` object. - * @namespace PIXI.mesh - * @deprecated since 5.0.0 - */ - PIXI.mesh = {}; +function caching(resource, next) { + var _this = this; - Object.defineProperties(PIXI.mesh, { - /** - * @class PIXI.mesh.Mesh - * @see PIXI.SimpleMesh - * @deprecated since 5.0.0 - */ - Mesh: { - get: function get() - { - utils.deprecation(v5, 'PIXI.mesh.Mesh class has moved to PIXI.SimpleMesh'); + // if cached, then set data and complete the resource + if (cache[resource.url]) { + resource.data = cache[resource.url]; + resource.complete(); // marks resource load complete and stops processing before middlewares + } // if not cached, wait for complete and store it in the cache. + else { + resource.onComplete.once(function () { + return cache[_this.url] = _this.data; + }); + } - return PIXI.SimpleMesh; - }, - }, - /** - * @class PIXI.mesh.NineSlicePlane - * @see PIXI.NineSlicePlane - * @deprecated since 5.0.0 - */ - NineSlicePlane: { - get: function get() - { - utils.deprecation(v5, 'PIXI.mesh.NineSlicePlane class has moved to PIXI.NineSlicePlane'); + next(); +} - return PIXI.NineSlicePlane; - }, - }, - /** - * @class PIXI.mesh.Plane - * @see PIXI.SimplePlane - * @deprecated since 5.0.0 - */ - Plane: { - get: function get() - { - utils.deprecation(v5, 'PIXI.mesh.Plane class has moved to PIXI.SimplePlane'); +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} - return PIXI.SimplePlane; - }, - }, - /** - * @class PIXI.mesh.Rope - * @see PIXI.SimpleRope - * @deprecated since 5.0.0 - */ - Rope: { - get: function get() - { - utils.deprecation(v5, 'PIXI.mesh.Rope class has moved to PIXI.SimpleRope'); +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} - return PIXI.SimpleRope; - }, - }, - /** - * @class PIXI.mesh.RawMesh - * @see PIXI.Mesh - * @deprecated since 5.0.0 - */ - RawMesh: { - get: function get() - { - utils.deprecation(v5, 'PIXI.mesh.RawMesh class has moved to PIXI.Mesh'); +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; // some status constants - return PIXI.Mesh; - }, - }, - /** - * @class PIXI.mesh.CanvasMeshRenderer - * @see PIXI.CanvasMeshRenderer - * @deprecated since 5.0.0 - */ - CanvasMeshRenderer: { - get: function get() - { - utils.deprecation(v5, 'PIXI.mesh.CanvasMeshRenderer class has moved to PIXI.CanvasMeshRenderer'); +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; +var STATUS_IE_BUG_EMPTY = 1223; +var STATUS_TYPE_OK = 2; // noop - return PIXI.CanvasMeshRenderer; - }, - }, - /** - * @class PIXI.mesh.MeshRenderer - * @see PIXI.MeshRenderer - * @deprecated since 5.0.0 - */ - MeshRenderer: { - get: function get() - { - utils.deprecation(v5, 'PIXI.mesh.MeshRenderer class has moved to PIXI.MeshRenderer'); +function _noop$1() {} +/* empty */ - return PIXI.MeshRenderer; - }, - }, - }); +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ - /** - * This namespace has been removed and items have been moved to - * the top-level `PIXI` object. - * @namespace PIXI.particles - * @deprecated since 5.0.0 - */ - PIXI.particles = {}; - Object.defineProperties(PIXI.particles, { - /** - * @class PIXI.particles.ParticleContainer - * @deprecated since 5.0.0 - * @see PIXI.ParticleContainer - */ - ParticleContainer: { - get: function get() - { - utils.deprecation(v5, 'PIXI.particles.ParticleContainer class has moved to PIXI.ParticleContainer'); +var Resource = +/*#__PURE__*/ +function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + } + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + ; - return PIXI.ParticleContainer; - }, - }, - /** - * @class PIXI.particles.ParticleRenderer - * @deprecated since 5.0.0 - * @see PIXI.ParticleRenderer - */ - ParticleRenderer: { - get: function get() - { - utils.deprecation(v5, 'PIXI.particles.ParticleRenderer class has moved to PIXI.ParticleRenderer'); + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + } + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes + * longer than this time it is cancelled and the load is considered a failure. If this value is + * set to `0` then there is no explicit timeout. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {Resource.IMetadata} [options.metadata] - Extra configuration for middleware and the Resource object. + */ + ; - return PIXI.ParticleRenderer; - }, - }, - }); + function Resource(name, url, options) { + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + options = options || {}; /** - * This namespace has been removed and items have been moved to - * the top-level `PIXI` object. - * @namespace PIXI.ticker - * @deprecated since 5.0.0 + * The state flags of this resource. + * + * @private + * @member {number} */ - PIXI.ticker = {}; - Object.defineProperties(PIXI.ticker, { - /** - * @class PIXI.ticker.Ticker - * @deprecated since 5.0.0 - * @see PIXI.Ticker - */ - Ticker: { - get: function get() - { - utils.deprecation(v5, 'PIXI.ticker.Ticker class has moved to PIXI.Ticker'); + this._flags = 0; // set data url flag, needs to be set early for some _determineX checks to work. - return PIXI.Ticker; - }, - }, - /** - * @name PIXI.ticker.shared - * @type {PIXI.Ticker} - * @deprecated since 5.0.0 - * @see PIXI.Ticker.shared - */ - shared: { - get: function get() - { - utils.deprecation(v5, 'PIXI.ticker.shared instance has moved to PIXI.Ticker.shared'); + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + /** + * The name of this resource. + * + * @readonly + * @member {string} + */ - return PIXI.Ticker.shared; - }, - }, - }); + this.name = name; /** - * All classes on this namespace have moved to the high-level `PIXI` object. - * @namespace PIXI.loaders - * @deprecated since 5.0.0 + * The url used to load this resource. + * + * @readonly + * @member {string} */ - PIXI.loaders = {}; - - Object.defineProperties(PIXI.loaders, { - /** - * @class PIXI.loaders.Loader - * @see PIXI.Loader - * @deprecated since 5.0.0 - */ - Loader: { - get: function get() - { - utils.deprecation(v5, 'PIXI.loaders.Loader class has moved to PIXI.Loader'); - return PIXI.Loader; - }, - }, - /** - * @class PIXI.loaders.Resource - * @see PIXI.LoaderResource - * @deprecated since 5.0.0 - */ - Resource: { - get: function get() - { - utils.deprecation(v5, 'PIXI.loaders.Resource class has moved to PIXI.LoaderResource'); + this.url = url; + /** + * The extension used to load this resource. + * + * @readonly + * @member {string} + */ - return PIXI.LoaderResource; - }, - }, - /** - * @function PIXI.loaders.bitmapFontParser - * @see PIXI.BitmapFontLoader.use - * @deprecated since 5.0.0 - */ - bitmapFontParser: { - get: function get() - { - utils.deprecation(v5, 'PIXI.loaders.bitmapFontParser function has moved to PIXI.BitmapFontLoader.use'); + this.extension = this._getExtension(); + /** + * The data that was loaded by the resource. + * + * @member {any} + */ - return PIXI.BitmapFontLoader.use; - }, - }, - /** - * @function PIXI.loaders.parseBitmapFontData - * @see PIXI.BitmapFontLoader.parse - * @deprecated since 5.0.0 - */ - parseBitmapFontData: { - get: function get() - { - utils.deprecation(v5, 'PIXI.loaders.parseBitmapFontData function has moved to PIXI.BitmapFontLoader.parse'); + this.data = null; + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ - return PIXI.BitmapFontLoader.parse; - }, - }, - /** - * @function PIXI.loaders.spritesheetParser - * @see PIXI.SpritesheetLoader.use - * @deprecated since 5.0.0 - */ - spritesheetParser: { - get: function get() - { - utils.deprecation(v5, 'PIXI.loaders.spritesheetParser function has moved to PIXI.SpritesheetLoader.use'); + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + /** + * A timeout in milliseconds for the load. If the load takes longer than this time + * it is cancelled and the load is considered a failure. If this value is set to `0` + * then there is no explicit timeout. + * + * @member {number} + */ - return PIXI.SpritesheetLoader.use; - }, - }, - /** - * @function PIXI.loaders.getResourcePath - * @see PIXI.SpritesheetLoader.getResourcePath - * @deprecated since 5.0.0 - */ - getResourcePath: { - get: function get() - { - utils.deprecation(v5, 'PIXI.loaders.getResourcePath property has moved to PIXI.SpritesheetLoader.getResourcePath'); + this.timeout = options.timeout || 0; + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ - return PIXI.SpritesheetLoader.getResourcePath; - }, - }, - }); + this.loadType = options.loadType || this._determineLoadType(); + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; /** - * @function PIXI.loaders.Loader.addPixiMiddleware - * @see PIXI.Loader.registerPlugin - * @deprecated since 5.0.0 - * @param {function} middleware + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {Resource.IMetadata} */ - PIXI.Loader.addPixiMiddleware = function addPixiMiddleware(middleware) - { - utils.deprecation(v5, - 'PIXI.loaders.Loader.addPixiMiddleware function is deprecated, use PIXI.loaders.Loader.registerPlugin' - ); - return PIXI.loaders.Loader.registerPlugin({ use: middleware() }); - }; + this.metadata = options.metadata || {}; + /** + * The error that occurred while loading (if any). + * + * @readonly + * @member {Error} + */ + this.error = null; /** - * @class PIXI.extract.WebGLExtract - * @deprecated since 5.0.0 - * @see PIXI.extract.Extract + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @readonly + * @member {XMLHttpRequest} */ - Object.defineProperty(PIXI.extract, 'WebGLExtract', { - get: function get() - { - utils.deprecation(v5, 'PIXI.extract.WebGLExtract method has moved to PIXI.extract.Extract'); - return PIXI.extract.Extract; - }, - }); + this.xhr = null; + /** + * The child resources this resource owns. + * + * @readonly + * @member {Resource[]} + */ + this.children = []; /** - * @class PIXI.prepare.WebGLPrepare - * @deprecated since 5.0.0 - * @see PIXI.prepare.Prepare + * The resource type. + * + * @readonly + * @member {Resource.TYPE} */ - Object.defineProperty(PIXI.prepare, 'WebGLPrepare', { - get: function get() - { - utils.deprecation(v5, 'PIXI.prepare.WebGLPrepare class has moved to PIXI.prepare.Prepare'); - return PIXI.prepare.Prepare; - }, - }); + this.type = Resource.TYPE.UNKNOWN; + /** + * The progress chunk owned by this resource. + * + * @readonly + * @member {number} + */ + this.progressChunk = 0; /** - * @method PIXI.Container#_renderWebGL + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * * @private - * @deprecated since 5.0.0 - * @see PIXI.Container#render - * @param {PIXI.Renderer} renderer Instance of renderer + * @member {function} */ - PIXI.Container.prototype._renderWebGL = function _renderWebGL(renderer) - { - utils.deprecation(v5, 'PIXI.Container._renderWebGL method has moved to PIXI.Container._render'); - this._render(renderer); - }; + this._dequeue = _noop$1; + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; /** - * @method PIXI.Container#renderWebGL - * @deprecated since 5.0.0 - * @see PIXI.Container#render - * @param {PIXI.Renderer} renderer Instance of renderer + * The timer for element loads to check if they timeout. + * + * @private + * @member {number} */ - PIXI.Container.prototype.renderWebGL = function renderWebGL(renderer) - { - utils.deprecation(v5, 'PIXI.Container.renderWebGL method has moved to PIXI.Container.render'); - this.render(renderer); - }; + this._elementTimer = 0; + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); /** - * @method PIXI.DisplayObject#renderWebGL - * @deprecated since 5.0.0 - * @see PIXI.DisplayObject#render - * @param {PIXI.Renderer} renderer Instance of renderer + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} */ - PIXI.DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) - { - utils.deprecation(v5, 'PIXI.DisplayObject.renderWebGL method has moved to PIXI.DisplayObject.render'); - this.render(renderer); - }; + this._boundOnError = this._onError.bind(this); + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); /** - * @method PIXI.Container#renderAdvancedWebGL - * @deprecated since 5.0.0 - * @see PIXI.Container#renderAdvanced - * @param {PIXI.Renderer} renderer Instance of renderer + * The `_onTimeout` function bound to this resource's context. + * + * @private + * @member {function} */ - PIXI.Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) - { - utils.deprecation(v5, 'PIXI.Container.renderAdvancedWebGL method has moved to PIXI.Container.renderAdvanced'); - this.renderAdvanced(renderer); - }; + this._boundOnTimeout = this._onTimeout.bind(this); // xhr callbacks - Object.defineProperties(PIXI.settings, { - /** - * Default transform type. - * - * @static - * @deprecated since 5.0.0 - * @memberof PIXI.settings - * @type {PIXI.TRANSFORM_MODE} - * @default PIXI.TRANSFORM_MODE.STATIC - */ - TRANSFORM_MODE: { - get: function get() - { - utils.deprecation(v5, 'PIXI.settings.TRANSFORM_MODE property has been removed'); + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ - return 0; - }, - set: function set() - { - utils.deprecation(v5, 'PIXI.settings.TRANSFORM_MODE property has been removed'); - }, - }, - }); + this.onStart = new Signal(); + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ - var BaseTexture = PIXI.BaseTexture; + this.onProgress = new Signal(); + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new Signal(); /** - * @method loadSource - * @memberof PIXI.BaseTexture# - * @deprecated since 5.0.0 + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} */ - BaseTexture.prototype.loadSource = function loadSource(image) - { - utils.deprecation(v5, 'PIXI.BaseTexture.loadSource method has been deprecated'); - var resource = PIXI.resources.autoDetectResource(image); + this.onAfterMiddleware = new Signal(); + } + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ - resource.internal = true; + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ - this.setResource(resource); - this.update(); - }; + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ - var baseTextureIdDeprecation = false; + /** + * @memberof Resource + * @typedef {object} IMetadata + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @property {string|string[]} [mimeType] - The mime type to use for the source element + * of a video/audio elment. If the urls are an array, you can pass this as an array as well + * where each index is the mime type to use for the corresponding url index. + */ - Object.defineProperties(BaseTexture.prototype, { - /** - * @name PIXI.BaseTexture#hasLoaded - * @type {boolean} - * @deprecated since 5.0.0 - * @readonly - * @see PIXI.BaseTexture#valid - */ - hasLoaded: { - get: function get() - { - utils.deprecation(v5, 'PIXI.BaseTexture.hasLoaded property has been removed, use PIXI.BaseTexture.valid'); + /** + * Stores whether or not this url is a data url. + * + * @readonly + * @member {boolean} + */ - return this.valid; - }, - }, - /** - * @name PIXI.BaseTexture#imageUrl - * @type {string} - * @deprecated since 5.0.0 - * @see PIXI.resource.ImageResource#url - */ - imageUrl: { - get: function get() - { - utils.deprecation(v5, 'PIXI.BaseTexture.imageUrl property has been removed, use PIXI.BaseTexture.resource.url'); - return this.resource && this.resource.url; - }, + var _proto = Resource.prototype; - set: function set(imageUrl) - { - utils.deprecation(v5, 'PIXI.BaseTexture.imageUrl property has been removed, use PIXI.BaseTexture.resource.url'); + /** + * Marks the resource as complete. + * + */ + _proto.complete = function complete() { + this._clearEvents(); - if (this.resource) - { - this.resource.url = imageUrl; - } - }, - }, - /** - * @name PIXI.BaseTexture#source - * @type {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} - * @deprecated since 5.0.0 - * @readonly - * @see PIXI.resources.BaseImageResource#source - */ - source: { - get: function get() - { - utils.deprecation(v5, 'PIXI.BaseTexture.source property has been moved, use `PIXI.BaseTexture.resource.source`'); + this._finish(); + } + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + ; - return this.resource && this.resource.source; - }, - set: function set(source) - { - utils.deprecation(v5, 'PIXI.BaseTexture.source property has been moved, use `PIXI.BaseTexture.resource.source` ' - + 'if you want to set HTMLCanvasElement. Otherwise, create new BaseTexture.'); + _proto.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } // store error - if (this.resource) - { - this.resource.source = source; - } - }, - }, - /** - * @name PIXI.BaseTexture#premultiplyAlpha - * @type {boolean} - * @deprecated since 5.2.0 - * @readonly - * @see PIXI.BaseTexture#alphaMode - */ - premultiplyAlpha: { - get: function get() - { - utils.deprecation('5.2.0', 'PIXI.BaseTexture.premultiplyAlpha property has been changed to `alphaMode`' - + ', see `PIXI.ALPHA_MODES`'); + this.error = new Error(message); // clear events before calling aborts - return this.alphaMode !== 0; - }, - set: function set(value) - { - utils.deprecation('5.2.0', 'PIXI.BaseTexture.premultiplyAlpha property has been changed to `alphaMode`' - + ', see `PIXI.ALPHA_MODES`'); + this._clearEvents(); // abort the actual loading - this.alphaMode = Number(value); - }, - }, - /** - * Batch local field, stores current texture location - * - * @name PIXI.BaseTexture#_id - * @deprecated since 5.2.0 - * @type {number} - * @see PIXI.BaseTexture#_batchLocation - */ - _id: { - get: function get() - { - if (!baseTextureIdDeprecation) - { - // #popelyshev: That property was a hot place, I don't want to call deprecation method on it if possible - utils.deprecation('5.2.0', 'PIXI.BaseTexture._id batch local field has been changed to `_batchLocation`'); - baseTextureIdDeprecation = true; - } - return this._batchLocation; - }, - set: function set(value) - { - this._batchLocation = value; - }, - }, - }); + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } // done now. + + + this._finish(); + } + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {Resource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded. + */ + ; + + _proto.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); // if unset, determine the value + + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + + this._loadElement('image'); + + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + + this._loadSourceElement('audio'); + + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + + this._loadSourceElement('video'); + + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + + break; + } + } + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + ; + + _proto._hasFlag = function _hasFlag(flag) { + return (this._flags & flag) !== 0; + } + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + ; + + _proto._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + } + /** + * Clears all the events from the underlying loading source. + * + * @private + */ + ; + + _proto._clearEvents = function _clearEvents() { + clearTimeout(this._elementTimer); + + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } - /** - * @method fromImage - * @static - * @memberof PIXI.BaseTexture - * @deprecated since 5.0.0 - * @see PIXI.BaseTexture.from - */ - BaseTexture.fromImage = function fromImage(canvas, crossorigin, scaleMode, scale) - { - utils.deprecation(v5, 'PIXI.BaseTexture.fromImage method has been replaced with PIXI.BaseTexture.from'); + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + } + /** + * Finalizes the load. + * + * @private + */ + ; - var resourceOptions = { scale: scale, crossorigin: crossorigin }; + _proto._finish = function _finish() { + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } - return BaseTexture.from(canvas, { scaleMode: scaleMode, resourceOptions: resourceOptions }); - }; + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); - /** - * @method fromCanvas - * @static - * @memberof PIXI.BaseTexture - * @deprecated since 5.0.0 - * @see PIXI.BaseTexture.from - */ - BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) - { - utils.deprecation(v5, 'PIXI.BaseTexture.fromCanvas method has been replaced with PIXI.BaseTexture.from'); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); - return BaseTexture.from(canvas, { scaleMode: scaleMode }); - }; + this.onComplete.dispatch(this); + } + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + ; - /** - * @method fromSVG - * @static - * @memberof PIXI.BaseTexture - * @deprecated since 5.0.0 - * @see PIXI.BaseTexture.from - */ - BaseTexture.fromSVG = function fromSVG(canvas, crossorigin, scaleMode, scale) - { - utils.deprecation(v5, 'PIXI.BaseTexture.fromSVG method has been replaced with PIXI.BaseTexture.from'); + _proto._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } - var resourceOptions = { scale: scale, crossorigin: crossorigin }; + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } - return BaseTexture.from(canvas, { scaleMode: scaleMode, resourceOptions: resourceOptions }); - }; + if (!this.metadata.skipSource) { + this.data.src = this.url; + } - Object.defineProperties(PIXI.resources.ImageResource.prototype, { - /** - * @name PIXI.resources.ImageResource#premultiplyAlpha - * @type {boolean} - * @deprecated since 5.2.0 - * @readonly - * @see PIXI.resources.ImageResource#alphaMode - */ - premultiplyAlpha: { - get: function get() - { - utils.deprecation('5.2.0', 'PIXI.resources.ImageResource.premultiplyAlpha property ' - + 'has been changed to `alphaMode`, see `PIXI.ALPHA_MODES`'); + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); - return this.alphaMode !== 0; - }, - set: function set(value) - { - utils.deprecation('5.2.0', 'PIXI.resources.ImageResource.premultiplyAlpha property ' - + 'has been changed to `alphaMode`, see `PIXI.ALPHA_MODES`'); - this.alphaMode = Number(value); - }, - }, - }); + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + } + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + ; - /** - * @method PIXI.Point#copy - * @deprecated since 5.0.0 - * @see PIXI.Point#copyFrom - */ - PIXI.Point.prototype.copy = function copy(p) - { - utils.deprecation(v5, 'PIXI.Point.copy method has been replaced with PIXI.Point.copyFrom'); + _proto._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } - return this.copyFrom(p); - }; + if (this.data === null) { + this.abort("Unsupported element: " + type); + return; + } - /** - * @method PIXI.ObservablePoint#copy - * @deprecated since 5.0.0 - * @see PIXI.ObservablePoint#copyFrom - */ - PIXI.ObservablePoint.prototype.copy = function copy(p) - { - utils.deprecation(v5, 'PIXI.ObservablePoint.copy method has been replaced with PIXI.ObservablePoint.copyFrom'); + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } - return this.copyFrom(p); - }; + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; - /** - * @method PIXI.Rectangle#copy - * @deprecated since 5.0.0 - * @see PIXI.Rectangle#copyFrom - */ - PIXI.Rectangle.prototype.copy = function copy(p) - { - utils.deprecation(v5, 'PIXI.Rectangle.copy method has been replaced with PIXI.Rectangle.copyFrom'); + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } else { + var _mimeTypes = this.metadata.mimeType; + this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); + } + } - return this.copyFrom(p); - }; + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + this.data.load(); - /** - * @method PIXI.Matrix#copy - * @deprecated since 5.0.0 - * @see PIXI.Matrix#copyTo - */ - PIXI.Matrix.prototype.copy = function copy(p) - { - utils.deprecation(v5, 'PIXI.Matrix.copy method has been replaced with PIXI.Matrix.copyTo'); + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + } + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + ; - return this.copyTo(p); - }; + _proto._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } - /** - * @method PIXI.systems.StateSystem#setState - * @deprecated since 5.1.0 - * @see PIXI.systems.StateSystem#set - */ - PIXI.systems.StateSystem.prototype.setState = function setState(s) - { - utils.deprecation('v5.1.0', 'StateSystem.setState has been renamed to StateSystem.set'); + var xhr = this.xhr = new XMLHttpRequest(); // set the request type and url - return this.set(s); - }; + xhr.open('GET', this.url, true); + xhr.timeout = this.timeout; // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. - Object.assign(PIXI.systems.FilterSystem.prototype, { - /** - * @method PIXI.FilterManager#getRenderTarget - * @deprecated since 5.0.0 - * @see PIXI.systems.FilterSystem#getFilterTexture - */ - getRenderTarget: function getRenderTarget(clear, resolution) - { - utils.deprecation(v5, - 'PIXI.FilterManager.getRenderTarget method has been replaced with PIXI.systems.FilterSystem#getFilterTexture' - ); + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } - return this.getFilterTexture(resolution); - }, + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('timeout', this._boundXhrOnTimeout, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + xhr.send(); + } + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + ; - /** - * @method PIXI.FilterManager#returnRenderTarget - * @deprecated since 5.0.0 - * @see PIXI.systems.FilterSystem#returnFilterTexture - */ - returnRenderTarget: function returnRenderTarget(renderTexture) - { - utils.deprecation(v5, - 'PIXI.FilterManager.returnRenderTarget method has been replaced with ' - + 'PIXI.systems.FilterSystem.returnFilterTexture' - ); + _proto._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } - this.returnFilterTexture(renderTexture); - }, + var xdr = this.xhr = new XDomainRequest(); // eslint-disable-line no-undef + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 - /** - * @method PIXI.systems.FilterSystem#calculateScreenSpaceMatrix - * @deprecated since 5.0.0 - * @param {PIXI.Matrix} outputMatrix - the matrix to output to. - * @return {PIXI.Matrix} The mapped matrix. - */ - calculateScreenSpaceMatrix: function calculateScreenSpaceMatrix(outputMatrix) - { - utils.deprecation(v5, 'PIXI.systems.FilterSystem.calculateScreenSpaceMatrix method is removed, ' - + 'use `(vTextureCoord * inputSize.xy) + outputFrame.xy` instead'); + xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9 - var mappedMatrix = outputMatrix.identity(); - var ref = this.activeState; - var sourceFrame = ref.sourceFrame; - var destinationFrame = ref.destinationFrame; + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXhrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + xdr.open('GET', this.url, true); // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 - mappedMatrix.translate(sourceFrame.x / destinationFrame.width, sourceFrame.y / destinationFrame.height); - mappedMatrix.scale(destinationFrame.width, destinationFrame.height); + setTimeout(function () { + return xdr.send(); + }, 1); + } + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + ; - return mappedMatrix; - }, + _proto._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + "/" + this._getExtension(url); + } - /** - * @method PIXI.systems.FilterSystem#calculateNormalizedScreenSpaceMatrix - * @deprecated since 5.0.0 - * @param {PIXI.Matrix} outputMatrix - The matrix to output to. - * @return {PIXI.Matrix} The mapped matrix. - */ - calculateNormalizedScreenSpaceMatrix: function calculateNormalizedScreenSpaceMatrix(outputMatrix) - { - utils.deprecation(v5, 'PIXI.systems.FilterManager.calculateNormalizedScreenSpaceMatrix method is removed, ' - + 'use `((vTextureCoord * inputSize.xy) + outputFrame.xy) / outputFrame.zw` instead.'); + var source = document.createElement('source'); + source.src = url; + source.type = mime; + return source; + } + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + ; - var ref = this.activeState; - var sourceFrame = ref.sourceFrame; - var destinationFrame = ref.destinationFrame; - var mappedMatrix = outputMatrix.identity(); + _proto._onError = function _onError(event) { + this.abort("Failed to load element using: " + event.target.nodeName); + } + /** + * Called if a load progress event fires for an element or xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + ; - mappedMatrix.translate(sourceFrame.x / destinationFrame.width, sourceFrame.y / destinationFrame.height); + _proto._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + } + /** + * Called if a timeout event fires for an element. + * + * @private + */ + ; - var translateScaleX = (destinationFrame.width / sourceFrame.width); - var translateScaleY = (destinationFrame.height / sourceFrame.height); + _proto._onTimeout = function _onTimeout() { + this.abort("Load timed out."); + } + /** + * Called if an error event fires for xhr/xdr. + * + * @private + */ + ; - mappedMatrix.scale(translateScaleX, translateScaleY); + _proto._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request failed. Status: " + xhr.status + ", text: \"" + xhr.statusText + "\""); + } + /** + * Called if an error event fires for xhr/xdr. + * + * @private + */ + ; - return mappedMatrix; - }, - }); + _proto._xhrOnTimeout = function _xhrOnTimeout() { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request timed out."); + } + /** + * Called if an abort event fires for xhr/xdr. + * + * @private + */ + ; - Object.defineProperties(PIXI.RenderTexture.prototype, { - /** - * @name PIXI.RenderTexture#sourceFrame - * @type {PIXI.Rectangle} - * @deprecated since 5.0.0 - * @readonly - */ - sourceFrame: { - get: function get() - { - utils.deprecation(v5, 'PIXI.RenderTexture.sourceFrame property has been removed'); + _proto._xhrOnAbort = function _xhrOnAbort() { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request was aborted by the user."); + } + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + ; - return this.filterFrame; - }, - }, - /** - * @name PIXI.RenderTexture#size - * @type {PIXI.Rectangle} - * @deprecated since 5.0.0 - * @readonly - */ - size: { - get: function get() - { - utils.deprecation(v5, 'PIXI.RenderTexture.size property has been removed'); + _proto._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + // responseText is accessible only if responseType is '' or 'text' and on older browsers - return this._frame; - }, - }, - }); + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. - /** - * @class BlurXFilter - * @memberof PIXI.filters - * @deprecated since 5.0.0 - * @see PIXI.filters.BlurFilterPass - */ - var BlurXFilter = /*@__PURE__*/(function (superclass) { - function BlurXFilter(strength, quality, resolution, kernelSize) - { - utils.deprecation(v5, 'PIXI.filters.BlurXFilter class is deprecated, use PIXI.filters.BlurFilterPass'); - superclass.call(this, true, strength, quality, resolution, kernelSize); - } + if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) { + status = STATUS_OK; + } // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } - if ( superclass ) BlurXFilter.__proto__ = superclass; - BlurXFilter.prototype = Object.create( superclass && superclass.prototype ); - BlurXFilter.prototype.constructor = BlurXFilter; + var statusType = status / 100 | 0; - return BlurXFilter; - }(PIXI.filters.BlurFilterPass)); + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = Resource.TYPE.TEXT; + } // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort("Error trying to parse loaded json: " + e); + return; + } + } // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + this.data = domparser.parseFromString(text, 'text/xml'); + } else { + var div = document.createElement('div'); + div.innerHTML = text; + this.data = div; + } - /** - * @class BlurYFilter - * @memberof PIXI.filters - * @deprecated since 5.0.0 - * @see PIXI.filters.BlurFilterPass - */ - var BlurYFilter = /*@__PURE__*/(function (superclass) { - function BlurYFilter(strength, quality, resolution, kernelSize) - { - utils.deprecation(v5, 'PIXI.filters.BlurYFilter class is deprecated, use PIXI.filters.BlurFilterPass'); + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort("Error trying to parse loaded xml: " + e); + return; + } + } // other types just return the response + else { + this.data = xhr.response || text; + } + } else { + this.abort("[" + xhr.status + "] " + xhr.statusText + ": " + xhr.responseURL); + return; + } + + this.complete(); + } + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + ; - superclass.call(this, false, strength, quality, resolution, kernelSize); - } + _proto._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } // A sandboxed iframe without the 'allow-same-origin' attribute will have a special + // origin designed not to match window.location.origin, and will always require + // crossOrigin requests regardless of whether the location matches. - if ( superclass ) BlurYFilter.__proto__ = superclass; - BlurYFilter.prototype = Object.create( superclass && superclass.prototype ); - BlurYFilter.prototype.constructor = BlurYFilter; - return BlurYFilter; - }(PIXI.filters.BlurFilterPass)); + if (window.origin !== window.location.origin) { + return 'anonymous'; + } // default is window.location - Object.assign(PIXI.filters, { - BlurXFilter: BlurXFilter, - BlurYFilter: BlurYFilter, - }); - var Sprite = PIXI.Sprite; - var Texture = PIXI.Texture; - var Graphics = PIXI.Graphics; + loc = loc || window.location; - // Support for pixi.js-legacy bifurcation - // give users a friendly assist to use legacy - if (!Graphics.prototype.generateCanvasTexture) - { - Graphics.prototype.generateCanvasTexture = function generateCanvasTexture() - { - utils.deprecation(v5, 'PIXI.Graphics.generateCanvasTexture method is only available in "pixi.js-legacy"'); - }; - } + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( - /** - * @deprecated since 5.0.0 - * @member {PIXI.Graphics} PIXI.Graphics#graphicsData - * @see PIXI.Graphics#geometry - * @readonly - */ - Object.defineProperty(PIXI.Graphics.prototype, 'graphicsData', { - get: function get() - { - utils.deprecation(v5, 'PIXI.Graphics.graphicsData property is deprecated, use PIXI.Graphics.geometry.graphicsData'); - return this.geometry.graphicsData; - }, + tempAnchor.href = url; + url = parseUri(tempAnchor.href, { + strictMode: true }); + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ":" : ''; // if cross origin - // Use these to deprecate all the Sprite from* methods - function spriteFrom(name, source, crossorigin, scaleMode) - { - utils.deprecation(v5, ("PIXI.Sprite." + name + " method is deprecated, use PIXI.Sprite.from")); - - return Sprite.from(source, { - resourceOptions: { - scale: scaleMode, - crossorigin: crossorigin, - }, - }); + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; } - /** - * @deprecated since 5.0.0 - * @see PIXI.Sprite.from - * @method PIXI.Sprite.fromImage - * @return {PIXI.Sprite} - */ - Sprite.fromImage = spriteFrom.bind(null, 'fromImage'); - - /** - * @deprecated since 5.0.0 - * @method PIXI.Sprite.fromSVG - * @see PIXI.Sprite.from - * @return {PIXI.Sprite} - */ - Sprite.fromSVG = spriteFrom.bind(null, 'fromSVG'); - - /** - * @deprecated since 5.0.0 - * @method PIXI.Sprite.fromCanvas - * @see PIXI.Sprite.from - * @return {PIXI.Sprite} - */ - Sprite.fromCanvas = spriteFrom.bind(null, 'fromCanvas'); + return ''; + } + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + ; - /** - * @deprecated since 5.0.0 - * @method PIXI.Sprite.fromVideo - * @see PIXI.Sprite.from - * @return {PIXI.Sprite} - */ - Sprite.fromVideo = spriteFrom.bind(null, 'fromVideo'); + _proto._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + } + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + ; - /** - * @deprecated since 5.0.0 - * @method PIXI.Sprite.fromFrame - * @see PIXI.Sprite.from - * @return {PIXI.Sprite} - */ - Sprite.fromFrame = spriteFrom.bind(null, 'fromFrame'); + _proto._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + } + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + ; - // Use these to deprecate all the Texture from* methods - function textureFrom(name, source, crossorigin, scaleMode) - { - utils.deprecation(v5, ("PIXI.Texture." + name + " method is deprecated, use PIXI.Texture.from")); + _proto._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; - return Texture.from(source, { - resourceOptions: { - scale: scaleMode, - crossorigin: crossorigin, - }, - }); + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); } - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromImage - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - Texture.fromImage = textureFrom.bind(null, 'fromImage'); - - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromSVG - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - Texture.fromSVG = textureFrom.bind(null, 'fromSVG'); + return ext.toLowerCase(); + } + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + ; - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromCanvas - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - Texture.fromCanvas = textureFrom.bind(null, 'fromCanvas'); + _proto._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromVideo - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - Texture.fromVideo = textureFrom.bind(null, 'fromVideo'); + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromFrame - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - Texture.fromFrame = textureFrom.bind(null, 'fromFrame'); + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; - /** - * @deprecated since 5.0.0 - * @member {boolean} PIXI.AbstractRenderer#autoResize - * @see PIXI.AbstractRenderer#autoDensity - */ - Object.defineProperty(PIXI.AbstractRenderer.prototype, 'autoResize', { - get: function get() - { - utils.deprecation(v5, 'PIXI.AbstractRenderer.autoResize property is deprecated, ' - + 'use PIXI.AbstractRenderer.autoDensity'); + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; - return this.autoDensity; - }, - set: function set(value) - { - utils.deprecation(v5, 'PIXI.AbstractRenderer.autoResize property is deprecated, ' - + 'use PIXI.AbstractRenderer.autoDensity'); + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ - this.autoDensity = value; - }, - }); + default: + return 'text/plain'; + } + }; + _createClass(Resource, [{ + key: "isDataUrl", + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } /** - * @deprecated since 5.0.0 - * @member {PIXI.systems.TextureSystem} PIXI.Renderer#textureManager - * @see PIXI.Renderer#texture + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @readonly + * @member {boolean} */ - Object.defineProperty(PIXI.Renderer.prototype, 'textureManager', { - get: function get() - { - utils.deprecation(v5, 'PIXI.Renderer.textureManager property is deprecated, use PIXI.Renderer.texture'); - - return this.texture; - }, - }); + }, { + key: "isComplete", + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } /** - * @namespace PIXI.utils.mixins - * @deprecated since 5.0.0 + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @readonly + * @member {boolean} */ - PIXI.utils.mixins = { - /** - * @memberof PIXI.utils.mixins - * @function mixin - * @deprecated since 5.0.0 - */ - mixin: function mixin() - { - utils.deprecation(v5, 'PIXI.utils.mixins.mixin function is no longer available'); - }, - /** - * @memberof PIXI.utils.mixins - * @function delayMixin - * @deprecated since 5.0.0 - */ - delayMixin: function delayMixin() - { - utils.deprecation(v5, 'PIXI.utils.mixins.delayMixin function is no longer available'); - }, - /** - * @memberof PIXI.utils.mixins - * @function performMixins - * @deprecated since 5.0.0 - */ - performMixins: function performMixins() - { - utils.deprecation(v5, 'PIXI.utils.mixins.performMixins function is no longer available'); - }, - }; -} - -// Install renderer plugins -core.Renderer.registerPlugin('accessibility', accessibility.AccessibilityManager); -core.Renderer.registerPlugin('extract', extract.Extract); -core.Renderer.registerPlugin('interaction', interaction.InteractionManager); -core.Renderer.registerPlugin('particle', particles.ParticleRenderer); -core.Renderer.registerPlugin('prepare', prepare.Prepare); -core.Renderer.registerPlugin('batch', core.BatchRenderer); -core.Renderer.registerPlugin('tilingSprite', spriteTiling.TilingSpriteRenderer); - -loaders.Loader.registerPlugin(textBitmap.BitmapFontLoader); -loaders.Loader.registerPlugin(spritesheet.SpritesheetLoader); - -app.Application.registerPlugin(ticker.TickerPlugin); -app.Application.registerPlugin(loaders.AppLoaderPlugin); - -/** - * String of the current PIXI version. - * - * @static - * @constant - * @memberof PIXI - * @name VERSION - * @type {string} - */ -var VERSION = '5.2.0'; - -/** - * @namespace PIXI - */ - -/** - * This namespace contains WebGL-only display filters that can be applied - * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property. - * - * Since PixiJS only had a handful of built-in filters, additional filters - * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the - * PixiJS Filters repository. - * - * All filters must extend {@link PIXI.Filter}. - * - * @example - * // Create a new application - * const app = new PIXI.Application(); - * - * // Draw a green rectangle - * const rect = new PIXI.Graphics() - * .beginFill(0x00ff00) - * .drawRect(40, 40, 200, 200); - * - * // Add a blur filter - * rect.filters = [new PIXI.filters.BlurFilter()]; - * - * // Display rectangle - * app.stage.addChild(rect); - * document.body.appendChild(app.view); - * @namespace PIXI.filters - */ -var filters = { - AlphaFilter: filterAlpha.AlphaFilter, - BlurFilter: filterBlur.BlurFilter, - BlurFilterPass: filterBlur.BlurFilterPass, - ColorMatrixFilter: filterColorMatrix.ColorMatrixFilter, - DisplacementFilter: filterDisplacement.DisplacementFilter, - FXAAFilter: filterFxaa.FXAAFilter, - NoiseFilter: filterNoise.NoiseFilter, -}; - -Object.keys(app).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return app[key]; - } - }); -}); -Object.keys(core).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return core[key]; - } - }); -}); -Object.keys(loaders).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return loaders[key]; - } - }); -}); -Object.keys(particles).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return particles[key]; - } - }); -}); -Object.keys(spritesheet).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return spritesheet[key]; - } - }); -}); -Object.keys(spriteTiling).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return spriteTiling[key]; - } - }); -}); -Object.keys(textBitmap).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return textBitmap[key]; - } - }); -}); -Object.keys(ticker).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return ticker[key]; - } - }); -}); -Object.keys(constants).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return constants[key]; - } - }); -}); -Object.keys(display).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return display[key]; - } - }); -}); -Object.keys(graphics).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return graphics[key]; - } - }); -}); -Object.keys(math).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return math[key]; - } - }); -}); -Object.keys(mesh).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return mesh[key]; - } - }); -}); -Object.keys(meshExtras).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return meshExtras[key]; - } - }); -}); -Object.keys(runner).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return runner[key]; - } - }); -}); -Object.keys(sprite).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return sprite[key]; - } - }); -}); -Object.keys(spriteAnimated).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return spriteAnimated[key]; - } - }); -}); -Object.keys(text).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return text[key]; - } - }); -}); -Object.keys(settings).forEach(function (key) { - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return settings[key]; - } - }); -}); -exports.accessibility = accessibility; -exports.extract = extract; -exports.interaction = interaction; -exports.prepare = prepare; -exports.utils = utils; -exports.VERSION = VERSION; -exports.filters = filters; -exports.useDeprecated = useDeprecated; - -},{"@pixi/accessibility":14,"@pixi/app":15,"@pixi/constants":16,"@pixi/core":17,"@pixi/display":18,"@pixi/extract":19,"@pixi/filter-alpha":20,"@pixi/filter-blur":21,"@pixi/filter-color-matrix":22,"@pixi/filter-displacement":23,"@pixi/filter-fxaa":24,"@pixi/filter-noise":25,"@pixi/graphics":26,"@pixi/interaction":27,"@pixi/loaders":28,"@pixi/math":29,"@pixi/mesh":31,"@pixi/mesh-extras":30,"@pixi/mixin-cache-as-bitmap":32,"@pixi/mixin-get-child-by-name":33,"@pixi/mixin-get-global-position":34,"@pixi/particles":35,"@pixi/polyfill":36,"@pixi/prepare":37,"@pixi/runner":38,"@pixi/settings":39,"@pixi/sprite":42,"@pixi/sprite-animated":40,"@pixi/sprite-tiling":41,"@pixi/spritesheet":43,"@pixi/text":45,"@pixi/text-bitmap":44,"@pixi/ticker":46,"@pixi/utils":47}],58:[function(require,module,exports){ -/*! - * resource-loader - v3.0.1 - * https://github.com/pixijs/pixi-sound - * Compiled Tue, 02 Jul 2019 14:06:18 UTC + }, { + key: "isLoading", + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); +/** + * The types of resources a resource could represent. * - * resource-loader is licensed under the MIT license. - * http://www.opensource.org/licenses/mit-license + * @static + * @readonly + * @enum {number} */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var parseUri = _interopDefault(require('parse-uri')); -var Signal = _interopDefault(require('mini-signals')); +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; /** - * Smaller version of the async library constructs. + * The types of resources a resource could represent. * - * @namespace async + * @static + * @readonly + * @enum {number} */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; /** - * Noop function + * The types of loading a resource can use. * - * @ignore - * @function - * @memberof async + * @static + * @readonly + * @enum {number} */ -function _noop() {} -/* empty */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; /** - * Iterates an array in series. + * The XHR ready states, used internally. * - * @memberof async - * @function eachSeries - * @param {Array.<*>} array - Array to iterate. - * @param {function} iterator - Function to call for each element. - * @param {function} callback - Function to call when done, or on error. - * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + * @static + * @readonly + * @enum {string} */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', -function eachSeries(array, iterator, callback, deferNext) { - var i = 0; - var len = array.length; + /** ArrayBuffer */ + BUFFER: 'arraybuffer', - (function next(err) { - if (err || i === len) { - if (callback) { - callback(err); - } + /** Blob */ + BLOB: 'blob', - return; - } + /** Document */ + DOCUMENT: 'document', - if (deferNext) { - setTimeout(function () { - iterator(array[i++], next); - }, 1); - } else { - iterator(array[i++], next); - } - })(); -} + /** Object */ + JSON: 'json', + + /** String */ + TEXT: 'text' +}; +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, + // for SVG data urls + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif + +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; /** - * Ensures a function is only called once. + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. * * @ignore - * @memberof async - * @param {function} fn - The function to wrap. - * @return {function} The wrapping function. + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. */ -function onlyOnce(fn) { - return function onceWrapper() { - if (fn === null) { - throw new Error('Callback was already called.'); - } +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; + if (!extname) { + return; + } + + map[extname] = val; } /** - * Async queue implementation, + * Quick helper to get string xhr type. * - * @memberof async - * @function queue - * @param {function} worker - The worker function to call for each task. - * @param {number} concurrency - How many workers to run in parrallel. - * @return {*} The async queue object. + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. */ -function queue(worker, concurrency) { - if (concurrency == null) { - // eslint-disable-line no-eq-null,eqeqeq - concurrency = 1; - } else if (concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var workers = 0; - var q = { - _tasks: [], - concurrency: concurrency, - saturated: _noop, - unsaturated: _noop, - buffer: concurrency / 4, - empty: _noop, - drain: _noop, - error: _noop, - started: false, - paused: false, - push: function push(data, callback) { - _insert(data, false, callback); - }, - kill: function kill() { - workers = 0; - q.drain = _noop; - q.started = false; - q._tasks = []; - }, - unshift: function unshift(data, callback) { - _insert(data, true, callback); - }, - process: function process() { - while (!q.paused && workers < q.concurrency && q._tasks.length) { - var task = q._tasks.shift(); - - if (q._tasks.length === 0) { - q.empty(); - } - - workers += 1; - - if (workers === q.concurrency) { - q.saturated(); - } +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} - worker(task.data, onlyOnce(_next(task))); - } - }, - length: function length() { - return q._tasks.length; - }, - running: function running() { - return workers; - }, - idle: function idle() { - return q._tasks.length + workers === 0; - }, - pause: function pause() { - if (q.paused === true) { - return; - } +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +/** + * Encodes binary into base64. + * + * @function encodeBinary + * @param {string} input The input data to encode. + * @returns {string} The encoded base64 string + */ - q.paused = true; - }, - resume: function resume() { - if (q.paused === false) { - return; - } +function encodeBinary(input) { + var output = ''; + var inx = 0; - q.paused = false; // Need to call q.process once per concurrent - // worker to preserve full concurrency after pause + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; - for (var w = 1; w <= q.concurrency; w++) { - q.process(); + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; } - } - }; + } // Get each encoded character, 6 bits at a time + // index 1: first 6 bits - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - // eslint-disable-line no-eq-null,eqeqeq - throw new Error('task callback must be a function'); - } - q.started = true; + encodedCharIndexes[0] = bytebuffer[0] >> 2; // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) - if (data == null && q.idle()) { - // eslint-disable-line no-eq-null,eqeqeq - // call drain immediately if there are no tasks - setTimeout(function () { - return q.drain(); - }, 1); - return; - } + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) - var item = { - data: data, - callback: typeof callback === 'function' ? callback : _noop - }; + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; // index 3: forth 6 bits (6 least significant bits from input byte 3) - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; // Determine whether padding happened, and adjust accordingly - setTimeout(function () { - return q.process(); - }, 1); - } + var paddingBytes = inx - (input.length - 1); - function _next(task) { - return function next() { - workers -= 1; - task.callback.apply(task, arguments); + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; - if (arguments[0] != null) { - // eslint-disable-line no-eq-null,eqeqeq - q.error(arguments[0], task.data); - } + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; - if (workers <= q.concurrency - q.buffer) { - q.unsaturated(); - } + default: + break; + // No padding - proceed + } // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string - if (q.idle()) { - q.drain(); - } - q.process(); - }; + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } } - return q; + return output; } -var async = ({ - eachSeries: eachSeries, - queue: queue -}); - -// a simple in-memory cache for resources -var cache = {}; +var Url = window.URL || window.webkitURL; /** - * A simple in-memory cache for resource. + * A middleware for transforming XHR loaded Blobs into more useful objects * * @memberof middleware - * @function caching + * @function parsing * @example * import { Loader, middleware } from 'resource-loader'; * const loader = new Loader(); - * loader.use(middleware.caching); + * loader.use(middleware.parsing); * @param {Resource} resource - Current Resource * @param {function} next - Callback when complete */ -function caching(resource, next) { - var _this = this; - - // if cached, then set data and complete the resource - if (cache[resource.url]) { - resource.data = cache[resource.url]; - resource.complete(); // marks resource load complete and stops processing before middlewares - } // if not cached, wait for complete and store it in the cache. - else { - resource.onComplete.once(function () { - return cache[_this.url] = _this.data; - }); - } - - next(); -} +function parsing(resource, next) { + if (!resource.data) { + next(); + return; + } // if this was an XHR load of a blob -function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } -} -function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; -} + if (resource.xhr && resource.xhrType === Resource.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); // this is an image, convert the binary string into a data url -var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); -var tempAnchor = null; // some status constants + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = "data:" + type + ";base64," + encodeBinary(resource.xhr.responseText); + resource.type = Resource.TYPE.IMAGE; // wait until the image loads and then callback -var STATUS_NONE = 0; -var STATUS_OK = 200; -var STATUS_EMPTY = 204; -var STATUS_IE_BUG_EMPTY = 1223; -var STATUS_TYPE_OK = 2; // noop + resource.data.onload = function () { + resource.data.onload = null; + next(); + }; // next will be called on load -function _noop$1() {} -/* empty */ -/** - * Manages the state and loading of a resource and all child resources. - * - * @class - */ + return; + } + } // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var src = Url.createObjectURL(resource.data); + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + resource.type = Resource.TYPE.IMAGE; // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + next(); + }; // next will be called on load. -var Resource = -/*#__PURE__*/ -function () { - /** - * Sets the load type to be used for a specific extension. - * - * @static - * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" - * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. - */ - Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { - setExtMap(Resource._loadTypeMap, extname, loadType); - } - /** - * Sets the load type to be used for a specific extension. - * - * @static - * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" - * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. - */ - ; - Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { - setExtMap(Resource._xhrTypeMap, extname, xhrType); + return; + } } - /** - * @param {string} name - The name of the resource to load. - * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass - * an array of sources. - * @param {object} [options] - The options for the load. - * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to - * determine automatically. - * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes - * longer than this time it is cancelled and the load is considered a failure. If this value is - * set to `0` then there is no explicit timeout. - * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource - * be loaded? - * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How - * should the data being loaded be interpreted when using XHR? - * @param {Resource.IMetadata} [options.metadata] - Extra configuration for middleware and the Resource object. - */ - ; - - function Resource(name, url, options) { - if (typeof name !== 'string' || typeof url !== 'string') { - throw new Error('Both name and url are required for constructing a resource.'); - } - options = options || {}; - /** - * The state flags of this resource. - * - * @private - * @member {number} - */ + next(); +} - this._flags = 0; // set data url flag, needs to be set early for some _determineX checks to work. +/** + * @namespace middleware + */ - this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); - /** - * The name of this resource. - * - * @readonly - * @member {string} - */ +var index = ({ + caching: caching, + parsing: parsing +}); +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ - this.name = name; - /** - * The url used to load this resource. - * - * @readonly - * @member {string} - */ +var Loader = +/*#__PURE__*/ +function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + var _this = this; - this.url = url; - /** - * The extension used to load this resource. - * - * @readonly - * @member {string} - */ + if (baseUrl === void 0) { + baseUrl = ''; + } - this.extension = this._getExtension(); - /** - * The data that was loaded by the resource. - * - * @member {any} - */ + if (concurrency === void 0) { + concurrency = 10; + } - this.data = null; /** - * Is this request cross-origin? If unset, determined automatically. + * The base url for all resources loaded by this loader. * * @member {string} */ - - this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + this.baseUrl = baseUrl; /** - * A timeout in milliseconds for the load. If the load takes longer than this time - * it is cancelled and the load is considered a failure. If this value is set to `0` - * then there is no explicit timeout. + * The progress percent of the loader going through the queue. * * @member {number} + * @default 0 */ - this.timeout = options.timeout || 0; - /** - * The method of loading to use for this resource. - * - * @member {Resource.LOAD_TYPE} - */ - - this.loadType = options.loadType || this._determineLoadType(); + this.progress = 0; /** - * The type used to load the resource via XHR. If unset, determined automatically. + * Loading state of the loader, true if it is currently loading resources. * - * @member {string} + * @member {boolean} + * @default false */ - this.xhrType = options.xhrType; + this.loading = false; /** - * Extra info for middleware, and controlling specifics about how the resource loads. + * A querystring to append to every URL added to the loader. * - * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. - * Meaning it will modify it as it sees fit. + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. * - * @member {Resource.IMetadata} - */ - - this.metadata = options.metadata || {}; - /** - * The error that occurred while loading (if any). + * @example + * const loader = new Loader(); * - * @readonly - * @member {Error} - */ - - this.error = null; - /** - * The XHR object that was used to load this resource. This is only set - * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * loader.defaultQueryString = 'user=me&password=secret'; * - * @readonly - * @member {XMLHttpRequest} - */ - - this.xhr = null; - /** - * The child resources this resource owns. + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); * - * @readonly - * @member {Resource[]} - */ - - this.children = []; - /** - * The resource type. + * loader.reset(); * - * @readonly - * @member {Resource.TYPE} - */ - - this.type = Resource.TYPE.UNKNOWN; - /** - * The progress chunk owned by this resource. + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); * - * @readonly - * @member {number} + * @member {string} + * @default '' */ - this.progressChunk = 0; + this.defaultQueryString = ''; /** - * The `dequeue` method that will be used a storage place for the async queue dequeue method - * used privately by the loader. + * The middleware to run before loading each resource. * * @private - * @member {function} + * @member {function[]} */ - this._dequeue = _noop$1; + this._beforeMiddleware = []; /** - * Used a storage place for the on load binding used privately by the loader. + * The middleware to run after loading each resource. * * @private - * @member {function} + * @member {function[]} */ - this._onLoadBinding = null; + this._afterMiddleware = []; /** - * The timer for element loads to check if they timeout. + * The tracks the resources we are currently completing parsing for. * * @private - * @member {number} + * @member {Resource[]} */ - this._elementTimer = 0; + this._resourcesParsing = []; /** - * The `complete` function bound to this resource's context. + * The `_loadResource` function bound with this object context. * * @private * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} */ - this._boundComplete = this.complete.bind(this); + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; /** - * The `_onError` function bound to this resource's context. + * The resources waiting to be loaded. * * @private - * @member {function} + * @member {Resource[]} */ - this._boundOnError = this._onError.bind(this); + + this._queue = queue(this._boundLoadResource, concurrency); + + this._queue.pause(); /** - * The `_onProgress` function bound to this resource's context. + * All the resources for this loader keyed by name. * - * @private - * @member {function} + * @member {object} */ - this._boundOnProgress = this._onProgress.bind(this); + + this.resources = {}; /** - * The `_onTimeout` function bound to this resource's context. + * Dispatched once per loaded or errored resource. * - * @private - * @member {function} + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} */ - this._boundOnTimeout = this._onTimeout.bind(this); // xhr callbacks - - this._boundXhrOnError = this._xhrOnError.bind(this); - this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this); - this._boundXhrOnAbort = this._xhrOnAbort.bind(this); - this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this.onProgress = new Signal(); /** - * Dispatched when the resource beings to load. + * Dispatched once per errored resource. * - * The callback looks like {@link Resource.OnStartSignal}. + * The callback looks like {@link Loader.OnErrorSignal}. * - * @member {Signal} + * @member {Signal} */ - this.onStart = new Signal(); + this.onError = new Signal(); /** - * Dispatched each time progress of this resource load updates. - * Not all resources types and loader systems can support this event - * so sometimes it may not be available. If the resource - * is being loaded on a modern browser, using XHR, and the remote server - * properly sets Content-Length headers, then this will be available. + * Dispatched once per loaded resource. * - * The callback looks like {@link Resource.OnProgressSignal}. + * The callback looks like {@link Loader.OnLoadSignal}. * - * @member {Signal} + * @member {Signal} */ - this.onProgress = new Signal(); + this.onLoad = new Signal(); /** - * Dispatched once this resource has loaded, if there was an error it will - * be in the `error` property. + * Dispatched when the loader begins to process the queue. * - * The callback looks like {@link Resource.OnCompleteSignal}. + * The callback looks like {@link Loader.OnStartSignal}. * - * @member {Signal} + * @member {Signal} */ - this.onComplete = new Signal(); + this.onStart = new Signal(); /** - * Dispatched after this resource has had all the *after* middleware run on it. + * Dispatched when the queued resources all load. * - * The callback looks like {@link Resource.OnCompleteSignal}. + * The callback looks like {@link Loader.OnCompleteSignal}. * - * @member {Signal} + * @member {Signal} */ - this.onAfterMiddleware = new Signal(); + this.onComplete = new Signal(); // Add default before middleware + + for (var i = 0; i < Loader._defaultBeforeMiddleware.length; ++i) { + this.pre(Loader._defaultBeforeMiddleware[i]); + } // Add default after middleware + + + for (var _i = 0; _i < Loader._defaultAfterMiddleware.length; ++_i) { + this.use(Loader._defaultAfterMiddleware[_i]); + } } /** - * When the resource starts to load. + * When the progress changes the loader and resource are disaptched. * - * @memberof Resource - * @callback OnStartSignal - * @param {Resource} resource - The resource that the event happened on. + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. */ /** - * When the resource reports loading progress. + * When an error occurrs the loader and resource are disaptched. * - * @memberof Resource - * @callback OnProgressSignal - * @param {Resource} resource - The resource that the event happened on. - * @param {number} percentage - The progress of the load in the range [0, 1]. + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. */ /** - * When the resource finishes loading. + * When a load completes the loader and resource are disaptched. * - * @memberof Resource - * @callback OnCompleteSignal - * @param {Resource} resource - The resource that the event happened on. + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. */ /** - * @memberof Resource - * @typedef {object} IMetadata - * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The - * element to use for loading, instead of creating one. - * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This - * is useful if you want to pass in a `loadElement` that you already added load sources to. - * @property {string|string[]} [mimeType] - The mime type to use for the source element - * of a video/audio elment. If the urls are an array, you can pass this as an array as well - * where each index is the mime type to use for the corresponding url index. + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. */ /** - * Stores whether or not this url is a data url. + * When the loader completes loading resources it dispatches this callback. * - * @readonly - * @member {boolean} + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. */ - - var _proto = Resource.prototype; - /** - * Marks the resource as complete. + * Options for a call to `.add()`. * + * @see Loader#add + * + * @typedef {object} IAddOptions + * @property {string} [name] - The name of the resource to load, if not passed the url is used. + * @property {string} [key] - Alias for `name`. + * @property {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @property {string|boolean} [crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @property {number} [timeout=0] - A timeout in milliseconds for the load. If the load takes + * longer than this time it is cancelled and the load is considered a failure. If this value is + * set to `0` then there is no explicit timeout. + * @property {Resource.LOAD_TYPE} [loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @property {Resource.XHR_RESPONSE_TYPE} [xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @property {Resource.OnCompleteSignal} [onComplete] - Callback to add an an onComplete signal istener. + * @property {Resource.OnCompleteSignal} [callback] - Alias for `onComplete`. + * @property {Resource.IMetadata} [metadata] - Extra configuration for middleware and the Resource object. */ - _proto.complete = function complete() { - this._clearEvents(); - this._finish(); - } + /* eslint-disable require-jsdoc,valid-jsdoc */ + /** - * Aborts the loading of this resource, with an optional message. + * Adds a resource (or multiple resources) to the loader queue. * - * @param {string} message - The message to use for the error + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @function + * @variation 1 + * @param {string} name - The name of the resource to load. + * @param {string} url - The url for this resource, relative to the baseUrl of this loader. + * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. + * @return {this} Returns itself. */ - ; - _proto.abort = function abort(message) { - // abort can be called multiple times, ignore subsequent calls. - if (this.error) { - return; - } // store error + /** + * @function + * @variation 2 + * @param {string} name - The name of the resource to load. + * @param {string} url - The url for this resource, relative to the baseUrl of this loader. + * @param {IAddOptions} [options] - The options for the load. + * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. + * @return {this} Returns itself. + */ + /** + * @function + * @variation 3 + * @param {string} url - The url for this resource, relative to the baseUrl of this loader. + * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. + * @return {this} Returns itself. + */ - this.error = new Error(message); // clear events before calling aborts + /** + * @function + * @variation 4 + * @param {string} url - The url for this resource, relative to the baseUrl of this loader. + * @param {IAddOptions} [options] - The options for the load. + * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. + * @return {this} Returns itself. + */ - this._clearEvents(); // abort the actual loading + /** + * @function + * @variation 5 + * @param {IAddOptions} options - The options for the load. This object must contain a `url` property. + * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. + * @return {this} Returns itself. + */ + /** + * @function + * @variation 6 + * @param {Array} resources - An array of resources to load, where each is + * either an object with the options or a string url. If you pass an object, it must contain a `url` property. + * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. + * @return {this} Returns itself. + */ - if (this.xhr) { - this.xhr.abort(); - } else if (this.xdr) { - this.xdr.abort(); - } else if (this.data) { - // single source - if (this.data.src) { - this.data.src = Resource.EMPTY_GIF; - } // multi-source - else { - while (this.data.firstChild) { - this.data.removeChild(this.data.firstChild); - } - } - } // done now. + var _proto = Loader.prototype; - this._finish(); - } - /** - * Kicks off loading of this resource. This method is asynchronous. - * - * @param {Resource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded. - */ - ; + _proto.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } - _proto.load = function load(cb) { - var _this = this; + return this; + } // if an object is passed instead of params - if (this.isLoading) { - return; - } - if (this.isComplete) { - if (cb) { - setTimeout(function () { - return cb(_this); - }, 1); - } + if (typeof name === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } // case where no name is passed shift all args over by one. - return; - } else if (cb) { - this.onComplete.once(cb); - } - this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } // now that we shifted make sure we have a proper url. - this.onStart.dispatch(this); // if unset, determine the value - if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { - this.crossOrigin = this._determineCrossOrigin(this.url); - } + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } // options are optional so people might pass a function and no options - switch (this.loadType) { - case Resource.LOAD_TYPE.IMAGE: - this.type = Resource.TYPE.IMAGE; - this._loadElement('image'); + if (typeof options === 'function') { + cb = options; + options = null; + } // if loading already you can only add resources that have a parent. + + + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } // check if resource already exists. + + + if (this.resources[name]) { + throw new Error("Resource named \"" + name + "\" already exists."); + } // add base url if this isn't an absolute url + + + url = this._prepareUrl(url); // create the store the resource + + this.resources[name] = new Resource(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } // if actively loading, make sure to adjust progress chunks for that parent and its children - break; - case Resource.LOAD_TYPE.AUDIO: - this.type = Resource.TYPE.AUDIO; + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; - this._loadSourceElement('audio'); + for (var _i2 = 0; _i2 < parent.children.length; ++_i2) { + if (!parent.children[_i2].isComplete) { + incompleteChildren.push(parent.children[_i2]); + } + } - break; + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent - case Resource.LOAD_TYPE.VIDEO: - this.type = Resource.TYPE.VIDEO; + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child - this._loadSourceElement('video'); + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; - break; + for (var _i3 = 0; _i3 < incompleteChildren.length; ++_i3) { + incompleteChildren[_i3].progressChunk = eachChunk; + } - case Resource.LOAD_TYPE.XHR: - /* falls through */ + this.resources[name].progressChunk = eachChunk; + } // add the resource to the queue - default: - if (useXdr && this.crossOrigin) { - this._loadXdr(); - } else { - this._loadXhr(); - } - break; - } - } - /** - * Checks if the flag is set. - * - * @private - * @param {number} flag - The flag to check. - * @return {boolean} True if the flag is set. - */ - ; + this._queue.push(this.resources[name]); - _proto._hasFlag = function _hasFlag(flag) { - return (this._flags & flag) !== 0; + return this; } - /** - * (Un)Sets the flag. - * - * @private - * @param {number} flag - The flag to (un)set. - * @param {boolean} value - Whether to set or (un)set the flag. - */ - ; + /* eslint-enable require-jsdoc,valid-jsdoc */ - _proto._setFlag = function _setFlag(flag, value) { - this._flags = value ? this._flags | flag : this._flags & ~flag; - } /** - * Clears all the events from the underlying loading source. + * Sets up a middleware function that will run *before* the + * resource is loaded. * - * @private + * @param {function} fn - The middleware function to register. + * @return {this} Returns itself. */ ; - _proto._clearEvents = function _clearEvents() { - clearTimeout(this._elementTimer); - - if (this.data && this.data.removeEventListener) { - this.data.removeEventListener('error', this._boundOnError, false); - this.data.removeEventListener('load', this._boundComplete, false); - this.data.removeEventListener('progress', this._boundOnProgress, false); - this.data.removeEventListener('canplaythrough', this._boundComplete, false); - } + _proto.pre = function pre(fn) { + this._beforeMiddleware.push(fn); - if (this.xhr) { - if (this.xhr.removeEventListener) { - this.xhr.removeEventListener('error', this._boundXhrOnError, false); - this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false); - this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); - this.xhr.removeEventListener('progress', this._boundOnProgress, false); - this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); - } else { - this.xhr.onerror = null; - this.xhr.ontimeout = null; - this.xhr.onprogress = null; - this.xhr.onload = null; - } - } + return this; } /** - * Finalizes the load. + * Sets up a middleware function that will run *after* the + * resource is loaded. * - * @private + * @param {function} fn - The middleware function to register. + * @return {this} Returns itself. */ ; - _proto._finish = function _finish() { - if (this.isComplete) { - throw new Error('Complete called again for an already completed resource.'); - } - - this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); - - this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + _proto.use = function use(fn) { + this._afterMiddleware.push(fn); - this.onComplete.dispatch(this); + return this; } /** - * Loads this resources using an element that has a single source, - * like an HTMLImageElement. + * Resets the queue of the loader to prepare for a new load. * - * @private - * @param {string} type - The type of element to use. + * @return {this} Returns itself. */ ; - _proto._loadElement = function _loadElement(type) { - if (this.metadata.loadElement) { - this.data = this.metadata.loadElement; - } else if (type === 'image' && typeof window.Image !== 'undefined') { - this.data = new Image(); - } else { - this.data = document.createElement(type); - } - - if (this.crossOrigin) { - this.data.crossOrigin = this.crossOrigin; - } - - if (!this.metadata.skipSource) { - this.data.src = this.url; - } - - this.data.addEventListener('error', this._boundOnError, false); - this.data.addEventListener('load', this._boundComplete, false); - this.data.addEventListener('progress', this._boundOnProgress, false); + _proto.reset = function reset() { + this.progress = 0; + this.loading = false; - if (this.timeout) { - this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); - } - } - /** - * Loads this resources using an element that has multiple sources, - * like an HTMLAudioElement or HTMLVideoElement. - * - * @private - * @param {string} type - The type of element to use. - */ - ; + this._queue.kill(); - _proto._loadSourceElement = function _loadSourceElement(type) { - if (this.metadata.loadElement) { - this.data = this.metadata.loadElement; - } else if (type === 'audio' && typeof window.Audio !== 'undefined') { - this.data = new Audio(); - } else { - this.data = document.createElement(type); - } + this._queue.pause(); // abort all resource loads - if (this.data === null) { - this.abort("Unsupported element: " + type); - return; - } - if (this.crossOrigin) { - this.data.crossOrigin = this.crossOrigin; - } + for (var k in this.resources) { + var res = this.resources[k]; - if (!this.metadata.skipSource) { - // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') - if (navigator.isCocoonJS) { - this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; - } else if (Array.isArray(this.url)) { - var mimeTypes = this.metadata.mimeType; + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } - for (var i = 0; i < this.url.length; ++i) { - this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); - } - } else { - var _mimeTypes = this.metadata.mimeType; - this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); + if (res.isLoading) { + res.abort(); } } - this.data.addEventListener('error', this._boundOnError, false); - this.data.addEventListener('load', this._boundComplete, false); - this.data.addEventListener('progress', this._boundOnProgress, false); - this.data.addEventListener('canplaythrough', this._boundComplete, false); - this.data.load(); - - if (this.timeout) { - this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); - } + this.resources = {}; + return this; } /** - * Loads this resources using an XMLHttpRequest. + * Starts loading the queued resources. * - * @private + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {this} Returns itself. */ ; - _proto._loadXhr = function _loadXhr() { - // if unset, determine the value - if (typeof this.xhrType !== 'string') { - this.xhrType = this._determineXhrType(); - } - - var xhr = this.xhr = new XMLHttpRequest(); // set the request type and url - - xhr.open('GET', this.url, true); - xhr.timeout = this.timeout; // load json as text and parse it ourselves. We do this because some browsers - // *cough* safari *cough* can't deal with it. - - if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { - xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; - } else { - xhr.responseType = this.xhrType; - } + _proto.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } // if the queue has already started we are done here - xhr.addEventListener('error', this._boundXhrOnError, false); - xhr.addEventListener('timeout', this._boundXhrOnTimeout, false); - xhr.addEventListener('abort', this._boundXhrOnAbort, false); - xhr.addEventListener('progress', this._boundOnProgress, false); - xhr.addEventListener('load', this._boundXhrOnLoad, false); - xhr.send(); - } - /** - * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). - * - * @private - */ - ; - _proto._loadXdr = function _loadXdr() { - // if unset, determine the value - if (typeof this.xhrType !== 'string') { - this.xhrType = this._determineXhrType(); + if (this.loading) { + return this; } - var xdr = this.xhr = new XDomainRequest(); // eslint-disable-line no-undef - // XDomainRequest has a few quirks. Occasionally it will abort requests - // A way to avoid this is to make sure ALL callbacks are set even if not used - // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 - - xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9 + if (this._queue.idle()) { + this._onStart(); - xdr.onerror = this._boundXhrOnError; - xdr.ontimeout = this._boundXhrOnTimeout; - xdr.onprogress = this._boundOnProgress; - xdr.onload = this._boundXhrOnLoad; - xdr.open('GET', this.url, true); // Note: The xdr.send() call is wrapped in a timeout to prevent an - // issue with the interface where some requests are lost if multiple - // XDomainRequests are being sent at the same time. - // Some info here: https://github.com/photonstorm/phaser/issues/1248 + this._onComplete(); + } else { + // distribute progress chunks + var numTasks = this._queue._tasks.length; + var chunk = MAX_PROGRESS / numTasks; - setTimeout(function () { - return xdr.send(); - }, 1); - } - /** - * Creates a source used in loading via an element. - * - * @private - * @param {string} type - The element type (video or audio). - * @param {string} url - The source URL to load from. - * @param {string} [mime] - The mime type of the video - * @return {HTMLSourceElement} The source element. - */ - ; + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } // notify we are starting - _proto._createSource = function _createSource(type, url, mime) { - if (!mime) { - mime = type + "/" + this._getExtension(url); - } - var source = document.createElement('source'); - source.src = url; - source.type = mime; - return source; - } - /** - * Called if a load errors out. - * - * @param {Event} event - The error event from the element that emits it. - * @private - */ - ; + this._onStart(); // start loading - _proto._onError = function _onError(event) { - this.abort("Failed to load element using: " + event.target.nodeName); - } - /** - * Called if a load progress event fires for an element or xhr/xdr. - * - * @private - * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. - */ - ; - _proto._onProgress = function _onProgress(event) { - if (event && event.lengthComputable) { - this.onProgress.dispatch(this, event.loaded / event.total); + this._queue.resume(); } - } - /** - * Called if a timeout event fires for an element. - * - * @private - */ - ; - - _proto._onTimeout = function _onTimeout() { - this.abort("Load timed out."); - } - /** - * Called if an error event fires for xhr/xdr. - * - * @private - */ - ; - - _proto._xhrOnError = function _xhrOnError() { - var xhr = this.xhr; - this.abort(reqType(xhr) + " Request failed. Status: " + xhr.status + ", text: \"" + xhr.statusText + "\""); - } - /** - * Called if an error event fires for xhr/xdr. - * - * @private - */ - ; - _proto._xhrOnTimeout = function _xhrOnTimeout() { - var xhr = this.xhr; - this.abort(reqType(xhr) + " Request timed out."); + return this; } /** - * Called if an abort event fires for xhr/xdr. + * The number of resources to load concurrently. * - * @private + * @member {number} + * @default 10 */ ; - _proto._xhrOnAbort = function _xhrOnAbort() { - var xhr = this.xhr; - this.abort(reqType(xhr) + " Request was aborted by the user."); - } /** - * Called when data successfully loads from an xhr/xdr request. + * Prepares a url for usage based on the configuration of this object * * @private - * @param {XMLHttpRequestLoadEvent|Event} event - Load event + * @param {string} url - The url to prepare. + * @return {string} The prepared url. */ - ; + _proto._prepareUrl = function _prepareUrl(url) { + var parsedUrl = parseUri(url, { + strictMode: true + }); + var result; // absolute url, just use it as is. - _proto._xhrOnLoad = function _xhrOnLoad() { - var xhr = this.xhr; - var text = ''; - var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. - // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + "/" + url; + } else { + result = this.baseUrl + url; + } // if we need to add a default querystring, there is a bit more work - if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { - text = xhr.responseText; - } // status can be 0 when using the `file://` protocol so we also check if a response is set. - // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + result = result.substr(0, result.length - hash.length); - if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) { - status = STATUS_OK; - } // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request - else if (status === STATUS_IE_BUG_EMPTY) { - status = STATUS_EMPTY; + if (result.indexOf('?') !== -1) { + result += "&" + this.defaultQueryString; + } else { + result += "?" + this.defaultQueryString; } - var statusType = status / 100 | 0; - - if (statusType === STATUS_TYPE_OK) { - // if text, just return it - if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { - this.data = text; - this.type = Resource.TYPE.TEXT; - } // if json, parse into json object - else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { - try { - this.data = JSON.parse(text); - this.type = Resource.TYPE.JSON; - } catch (e) { - this.abort("Error trying to parse loaded json: " + e); - return; - } - } // if xml, parse into an xml document or div element - else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { - try { - if (window.DOMParser) { - var domparser = new DOMParser(); - this.data = domparser.parseFromString(text, 'text/xml'); - } else { - var div = document.createElement('div'); - div.innerHTML = text; - this.data = div; - } - - this.type = Resource.TYPE.XML; - } catch (e) { - this.abort("Error trying to parse loaded xml: " + e); - return; - } - } // other types just return the response - else { - this.data = xhr.response || text; - } - } else { - this.abort("[" + xhr.status + "] " + xhr.statusText + ": " + xhr.responseURL); - return; + result += hash; } - this.complete(); + return result; } /** - * Sets the `crossOrigin` property for this resource based on if the url - * for this resource is cross-origin. If crossOrigin was manually set, this - * function does nothing. + * Loads a single resource. * * @private - * @param {string} url - The url to test. - * @param {object} [loc=window.location] - The location object to test against. - * @return {string} The crossOrigin value to use (or empty string for none). + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. */ ; - _proto._determineCrossOrigin = function _determineCrossOrigin(url, loc) { - // data: and javascript: urls are considered same-origin - if (url.indexOf('data:') === 0) { - return ''; - } // A sandboxed iframe without the 'allow-same-origin' attribute will have a special - // origin designed not to match window.location.origin, and will always require - // crossOrigin requests regardless of whether the location matches. - - - if (window.origin !== window.location.origin) { - return 'anonymous'; - } // default is window.location - - - loc = loc || window.location; - - if (!tempAnchor) { - tempAnchor = document.createElement('a'); - } // let the browser determine the full href for the url of this resource and then - // parse with the node url lib, we can't use the properties of the anchor element - // because they don't work in IE9 :( - - - tempAnchor.href = url; - url = parseUri(tempAnchor.href, { - strictMode: true - }); - var samePort = !url.port && loc.port === '' || url.port === loc.port; - var protocol = url.protocol ? url.protocol + ":" : ''; // if cross origin + _proto._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; - if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { - return 'anonymous'; - } + resource._dequeue = dequeue; // run before middleware - return ''; + eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }, true); } /** - * Determines the responseType of an XHR request based on the extension of the - * resource being loaded. + * Called once loading has started. * * @private - * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. */ ; - _proto._determineXhrType = function _determineXhrType() { - return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + _proto._onStart = function _onStart() { + this.progress = 0; + this.loading = true; + this.onStart.dispatch(this); } /** - * Determines the loadType of a resource based on the extension of the - * resource being loaded. + * Called once each resource has loaded. * * @private - * @return {Resource.LOAD_TYPE} The loadType to use. */ ; - _proto._determineLoadType = function _determineLoadType() { - return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + _proto._onComplete = function _onComplete() { + this.progress = MAX_PROGRESS; + this.loading = false; + this.onComplete.dispatch(this, this.resources); } /** - * Extracts the extension (sans '.') of the file being loaded by the resource. + * Called each time a resources is loaded. * * @private - * @return {string} The extension. + * @param {Resource} resource - The resource that was loaded */ ; - _proto._getExtension = function _getExtension() { - var url = this.url; - var ext = ''; + _proto._onLoad = function _onLoad(resource) { + var _this3 = this; - if (this.isDataUrl) { - var slashIndex = url.indexOf('/'); - ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); - } else { - var queryStart = url.indexOf('?'); - var hashStart = url.indexOf('#'); - var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); - url = url.substring(0, index); - ext = url.substring(url.lastIndexOf('.') + 1); - } + resource._onLoadBinding = null; // remove this resource from the async queue, and add it to our list of resources that are being parsed - return ext.toLowerCase(); - } - /** - * Determines the mime type of an XHR request based on the responseType of - * resource being loaded. - * - * @private - * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. - * @return {string} The mime type to use. - */ - ; + this._resourcesParsing.push(resource); - _proto._getMimeFromXhrType = function _getMimeFromXhrType(type) { - switch (type) { - case Resource.XHR_RESPONSE_TYPE.BUFFER: - return 'application/octet-binary'; + resource._dequeue(); // run all the after middleware for this resource - case Resource.XHR_RESPONSE_TYPE.BLOB: - return 'application/blob'; - case Resource.XHR_RESPONSE_TYPE.DOCUMENT: - return 'application/xml'; + eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + _this3.progress = Math.min(MAX_PROGRESS, _this3.progress + resource.progressChunk); - case Resource.XHR_RESPONSE_TYPE.JSON: - return 'application/json'; + _this3.onProgress.dispatch(_this3, resource); - case Resource.XHR_RESPONSE_TYPE.DEFAULT: - case Resource.XHR_RESPONSE_TYPE.TEXT: - /* falls through */ + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } - default: - return 'text/plain'; - } - }; + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); // do completion check - _createClass(Resource, [{ - key: "isDataUrl", - get: function get() { - return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); - } - /** - * Describes if this resource has finished loading. Is true when the resource has completely - * loaded. - * - * @readonly - * @member {boolean} - */ - }, { - key: "isComplete", - get: function get() { - return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); - } - /** - * Describes if this resource is currently loading. Is true when the resource starts loading, - * and is false again when complete. - * - * @readonly - * @member {boolean} - */ + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3._onComplete(); + } + }, true); + }; - }, { - key: "isLoading", + _createClass(Loader, [{ + key: "concurrency", get: function get() { - return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + return this._queue.concurrency; + } // eslint-disable-next-line require-jsdoc + , + set: function set(concurrency) { + this._queue.concurrency = concurrency; } }]); - return Resource; + return Loader; }(); /** - * The types of resources a resource could represent. + * A default array of middleware to run before loading each resource. + * Each of these middlewares are added to any new Loader instances when they are created. * - * @static - * @readonly - * @enum {number} + * @private + * @member {function[]} */ -Resource.STATUS_FLAGS = { - NONE: 0, - DATA_URL: 1 << 0, - COMPLETE: 1 << 1, - LOADING: 1 << 2 -}; +Loader._defaultBeforeMiddleware = []; /** - * The types of resources a resource could represent. + * A default array of middleware to run after loading each resource. + * Each of these middlewares are added to any new Loader instances when they are created. * - * @static - * @readonly - * @enum {number} + * @private + * @member {function[]} */ -Resource.TYPE = { - UNKNOWN: 0, - JSON: 1, - XML: 2, - IMAGE: 3, - AUDIO: 4, - VIDEO: 5, - TEXT: 6 -}; +Loader._defaultAfterMiddleware = []; /** - * The types of loading a resource can use. + * Sets up a middleware function that will run *before* the + * resource is loaded. * * @static - * @readonly - * @enum {number} + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. */ -Resource.LOAD_TYPE = { - /** Uses XMLHttpRequest to load the resource. */ - XHR: 1, - - /** Uses an `Image` object to load the resource. */ - IMAGE: 2, - - /** Uses an `Audio` object to load the resource. */ - AUDIO: 3, +Loader.pre = function LoaderPreStatic(fn) { + Loader._defaultBeforeMiddleware.push(fn); - /** Uses a `Video` object to load the resource. */ - VIDEO: 4 + return Loader; }; /** - * The XHR ready states, used internally. + * Sets up a middleware function that will run *after* the + * resource is loaded. * * @static - * @readonly - * @enum {string} + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. */ -Resource.XHR_RESPONSE_TYPE = { - /** string */ - DEFAULT: 'text', - - /** ArrayBuffer */ - BUFFER: 'arraybuffer', - - /** Blob */ - BLOB: 'blob', - - /** Document */ - DOCUMENT: 'document', - /** Object */ - JSON: 'json', +Loader.use = function LoaderUseStatic(fn) { + Loader._defaultAfterMiddleware.push(fn); - /** String */ - TEXT: 'text' -}; -Resource._loadTypeMap = { - // images - gif: Resource.LOAD_TYPE.IMAGE, - png: Resource.LOAD_TYPE.IMAGE, - bmp: Resource.LOAD_TYPE.IMAGE, - jpg: Resource.LOAD_TYPE.IMAGE, - jpeg: Resource.LOAD_TYPE.IMAGE, - tif: Resource.LOAD_TYPE.IMAGE, - tiff: Resource.LOAD_TYPE.IMAGE, - webp: Resource.LOAD_TYPE.IMAGE, - tga: Resource.LOAD_TYPE.IMAGE, - svg: Resource.LOAD_TYPE.IMAGE, - 'svg+xml': Resource.LOAD_TYPE.IMAGE, - // for SVG data urls - // audio - mp3: Resource.LOAD_TYPE.AUDIO, - ogg: Resource.LOAD_TYPE.AUDIO, - wav: Resource.LOAD_TYPE.AUDIO, - // videos - mp4: Resource.LOAD_TYPE.VIDEO, - webm: Resource.LOAD_TYPE.VIDEO + return Loader; }; -Resource._xhrTypeMap = { - // xml - xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. - // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, - // this should probably be fine. - tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, - // images - gif: Resource.XHR_RESPONSE_TYPE.BLOB, - png: Resource.XHR_RESPONSE_TYPE.BLOB, - bmp: Resource.XHR_RESPONSE_TYPE.BLOB, - jpg: Resource.XHR_RESPONSE_TYPE.BLOB, - jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, - tif: Resource.XHR_RESPONSE_TYPE.BLOB, - tiff: Resource.XHR_RESPONSE_TYPE.BLOB, - webp: Resource.XHR_RESPONSE_TYPE.BLOB, - tga: Resource.XHR_RESPONSE_TYPE.BLOB, - // json - json: Resource.XHR_RESPONSE_TYPE.JSON, - // text - text: Resource.XHR_RESPONSE_TYPE.TEXT, - txt: Resource.XHR_RESPONSE_TYPE.TEXT, - // fonts - ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, - otf: Resource.XHR_RESPONSE_TYPE.BUFFER -}; // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif - -Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; -/** - * Quick helper to set a value on one of the extension maps. Ensures there is no - * dot at the start of the extension. - * - * @ignore - * @param {object} map - The map to set on. - * @param {string} extname - The extension (or key) to set. - * @param {number} val - The value to set. - */ - -function setExtMap(map, extname, val) { - if (extname && extname.indexOf('.') === 0) { - extname = extname.substring(1); - } - if (!extname) { - return; - } +exports.Loader = Loader; +exports.Resource = Resource; +exports.async = async; +exports.encodeBinary = encodeBinary; +exports.middleware = index; - map[extname] = val; -} -/** - * Quick helper to get string xhr type. - * - * @ignore - * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. - * @return {string} The type. - */ +},{"mini-signals":45,"parse-uri":47}],51:[function(require,module,exports){ +// A library of seedable RNGs implemented in Javascript. +// +// Usage: +// +// var seedrandom = require('seedrandom'); +// var random = seedrandom(1); // or any seed. +// var x = random(); // 0 <= x < 1. Every bit is random. +// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness. -function reqType(xhr) { - return xhr.toString().replace('object ', ''); -} +// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe. +// Period: ~2^116 +// Reported to pass all BigCrush tests. +var alea = require('./lib/alea'); -var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -/** - * Encodes binary into base64. - * - * @function encodeBinary - * @param {string} input The input data to encode. - * @returns {string} The encoded base64 string - */ +// xor128, a pure xor-shift generator by George Marsaglia. +// Period: 2^128-1. +// Reported to fail: MatrixRank and LinearComp. +var xor128 = require('./lib/xor128'); -function encodeBinary(input) { - var output = ''; - var inx = 0; +// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl. +// Period: 2^192-2^32 +// Reported to fail: CollisionOver, SimpPoker, and LinearComp. +var xorwow = require('./lib/xorwow'); - while (inx < input.length) { - // Fill byte buffer array - var bytebuffer = [0, 0, 0]; - var encodedCharIndexes = [0, 0, 0, 0]; +// xorshift7, by François Panneton and Pierre L'ecuyer, takes +// a different approach: it adds robustness by allowing more shifts +// than Marsaglia's original three. It is a 7-shift generator +// with 256 bits, that passes BigCrush with no systmatic failures. +// Period 2^256-1. +// No systematic BigCrush failures reported. +var xorshift7 = require('./lib/xorshift7'); - for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { - if (inx < input.length) { - // throw away high-order byte, as documented at: - // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data - bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; - } else { - bytebuffer[jnx] = 0; - } - } // Get each encoded character, 6 bits at a time - // index 1: first 6 bits +// xor4096, by Richard Brent, is a 4096-bit xor-shift with a +// very long period that also adds a Weyl generator. It also passes +// BigCrush with no systematic failures. Its long period may +// be useful if you have many generators and need to avoid +// collisions. +// Period: 2^4128-2^32. +// No systematic BigCrush failures reported. +var xor4096 = require('./lib/xor4096'); +// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random +// number generator derived from ChaCha, a modern stream cipher. +// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf +// Period: ~2^127 +// No systematic BigCrush failures reported. +var tychei = require('./lib/tychei'); - encodedCharIndexes[0] = bytebuffer[0] >> 2; // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) +// The original ARC4-based prng included in this library. +// Period: ~2^1600 +var sr = require('./seedrandom'); - encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) +sr.alea = alea; +sr.xor128 = xor128; +sr.xorwow = xorwow; +sr.xorshift7 = xorshift7; +sr.xor4096 = xor4096; +sr.tychei = tychei; - encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; // index 3: forth 6 bits (6 least significant bits from input byte 3) +module.exports = sr; - encodedCharIndexes[3] = bytebuffer[2] & 0x3f; // Determine whether padding happened, and adjust accordingly +},{"./lib/alea":52,"./lib/tychei":53,"./lib/xor128":54,"./lib/xor4096":55,"./lib/xorshift7":56,"./lib/xorwow":57,"./seedrandom":58}],52:[function(require,module,exports){ +// A port of an algorithm by Johannes Baagøe , 2010 +// http://baagoe.com/en/RandomMusings/javascript/ +// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror +// Original work is under MIT license - - var paddingBytes = inx - (input.length - 1); +// Copyright (C) 2010 by Johannes Baagøe +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. - switch (paddingBytes) { - case 2: - // Set last 2 characters to padding char - encodedCharIndexes[3] = 64; - encodedCharIndexes[2] = 64; - break; - case 1: - // Set last character to padding char - encodedCharIndexes[3] = 64; - break; - default: - break; - // No padding - proceed - } // Now we will grab each appropriate character out of our keystring - // based on our index array and append it to the output string +(function(global, module, define) { +function Alea(seed) { + var me = this, mash = Mash(); - for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { - output += _keyStr.charAt(encodedCharIndexes[_jnx]); - } - } + me.next = function() { + var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32 + me.s0 = me.s1; + me.s1 = me.s2; + return me.s2 = t - (me.c = t | 0); + }; - return output; + // Apply the seeding algorithm from Baagoe. + me.c = 1; + me.s0 = mash(' '); + me.s1 = mash(' '); + me.s2 = mash(' '); + me.s0 -= mash(seed); + if (me.s0 < 0) { me.s0 += 1; } + me.s1 -= mash(seed); + if (me.s1 < 0) { me.s1 += 1; } + me.s2 -= mash(seed); + if (me.s2 < 0) { me.s2 += 1; } + mash = null; } -var Url = window.URL || window.webkitURL; -/** - * A middleware for transforming XHR loaded Blobs into more useful objects - * - * @memberof middleware - * @function parsing - * @example - * import { Loader, middleware } from 'resource-loader'; - * const loader = new Loader(); - * loader.use(middleware.parsing); - * @param {Resource} resource - Current Resource - * @param {function} next - Callback when complete - */ - -function parsing(resource, next) { - if (!resource.data) { - next(); - return; - } // if this was an XHR load of a blob - - - if (resource.xhr && resource.xhrType === Resource.XHR_RESPONSE_TYPE.BLOB) { - // if there is no blob support we probably got a binary string back - if (!window.Blob || typeof resource.data === 'string') { - var type = resource.xhr.getResponseHeader('content-type'); // this is an image, convert the binary string into a data url - - if (type && type.indexOf('image') === 0) { - resource.data = new Image(); - resource.data.src = "data:" + type + ";base64," + encodeBinary(resource.xhr.responseText); - resource.type = Resource.TYPE.IMAGE; // wait until the image loads and then callback - - resource.data.onload = function () { - resource.data.onload = null; - next(); - }; // next will be called on load +function copy(f, t) { + t.c = f.c; + t.s0 = f.s0; + t.s1 = f.s1; + t.s2 = f.s2; + return t; +} +function impl(seed, opts) { + var xg = new Alea(seed), + state = opts && opts.state, + prng = xg.next; + prng.int32 = function() { return (xg.next() * 0x100000000) | 0; } + prng.double = function() { + return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 + }; + prng.quick = prng; + if (state) { + if (typeof(state) == 'object') copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} - return; - } - } // if content type says this is an image, then we should transform the blob into an Image object - else if (resource.data.type.indexOf('image') === 0) { - var src = Url.createObjectURL(resource.data); - resource.blob = resource.data; - resource.data = new Image(); - resource.data.src = src; - resource.type = Resource.TYPE.IMAGE; // cleanup the no longer used blob after the image loads - // TODO: Is this correct? Will the image be invalid after revoking? +function Mash() { + var n = 0xefc8249d; - resource.data.onload = function () { - Url.revokeObjectURL(src); - resource.data.onload = null; - next(); - }; // next will be called on load. + var mash = function(data) { + data = String(data); + for (var i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + var h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000; // 2^32 + } + return (n >>> 0) * 2.3283064365386963e-10; // 2^-32 + }; + return mash; +} - return; - } - } - next(); +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.alea = impl; } -/** - * @namespace middleware - */ - -var index = ({ - caching: caching, - parsing: parsing -}); +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); -var MAX_PROGRESS = 100; -var rgxExtractUrlHash = /(#[\w-]+)?$/; -/** - * Manages the state and loading of multiple resources to load. - * - * @class - */ -var Loader = -/*#__PURE__*/ -function () { - /** - * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. - * @param {number} [concurrency=10] - The number of resources to load concurrently. - */ - function Loader(baseUrl, concurrency) { - var _this = this; - if (baseUrl === void 0) { - baseUrl = ''; - } +},{}],53:[function(require,module,exports){ +// A Javascript implementaion of the "Tyche-i" prng algorithm by +// Samuel Neves and Filipe Araujo. +// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf - if (concurrency === void 0) { - concurrency = 10; - } +(function(global, module, define) { - /** - * The base url for all resources loaded by this loader. - * - * @member {string} - */ - this.baseUrl = baseUrl; - /** - * The progress percent of the loader going through the queue. - * - * @member {number} - * @default 0 - */ +function XorGen(seed) { + var me = this, strseed = ''; - this.progress = 0; - /** - * Loading state of the loader, true if it is currently loading resources. - * - * @member {boolean} - * @default false - */ + // Set up generator function. + me.next = function() { + var b = me.b, c = me.c, d = me.d, a = me.a; + b = (b << 25) ^ (b >>> 7) ^ c; + c = (c - d) | 0; + d = (d << 24) ^ (d >>> 8) ^ a; + a = (a - b) | 0; + me.b = b = (b << 20) ^ (b >>> 12) ^ c; + me.c = c = (c - d) | 0; + me.d = (d << 16) ^ (c >>> 16) ^ a; + return me.a = (a - b) | 0; + }; - this.loading = false; - /** - * A querystring to append to every URL added to the loader. - * - * This should be a valid query string *without* the question-mark (`?`). The loader will - * also *not* escape values for you. Make sure to escape your parameters with - * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. - * - * @example - * const loader = new Loader(); - * - * loader.defaultQueryString = 'user=me&password=secret'; - * - * // This will request 'image.png?user=me&password=secret' - * loader.add('image.png').load(); - * - * loader.reset(); - * - * // This will request 'image.png?v=1&user=me&password=secret' - * loader.add('iamge.png?v=1').load(); - * - * @member {string} - * @default '' - */ + /* The following is non-inverted tyche, which has better internal + * bit diffusion, but which is about 25% slower than tyche-i in JS. + me.next = function() { + var a = me.a, b = me.b, c = me.c, d = me.d; + a = (me.a + me.b | 0) >>> 0; + d = me.d ^ a; d = d << 16 ^ d >>> 16; + c = me.c + d | 0; + b = me.b ^ c; b = b << 12 ^ d >>> 20; + me.a = a = a + b | 0; + d = d ^ a; me.d = d = d << 8 ^ d >>> 24; + me.c = c = c + d | 0; + b = b ^ c; + return me.b = (b << 7 ^ b >>> 25); + } + */ - this.defaultQueryString = ''; - /** - * The middleware to run before loading each resource. - * - * @private - * @member {function[]} - */ + me.a = 0; + me.b = 0; + me.c = 2654435769 | 0; + me.d = 1367130551; - this._beforeMiddleware = []; - /** - * The middleware to run after loading each resource. - * - * @private - * @member {function[]} - */ + if (seed === Math.floor(seed)) { + // Integer seed. + me.a = (seed / 0x100000000) | 0; + me.b = seed | 0; + } else { + // String seed. + strseed += seed; + } - this._afterMiddleware = []; - /** - * The tracks the resources we are currently completing parsing for. - * - * @private - * @member {Resource[]} - */ + // Mix in string seed, then discard an initial batch of 64 values. + for (var k = 0; k < strseed.length + 20; k++) { + me.b ^= strseed.charCodeAt(k) | 0; + me.next(); + } +} - this._resourcesParsing = []; - /** - * The `_loadResource` function bound with this object context. - * - * @private - * @member {function} - * @param {Resource} r - The resource to load - * @param {Function} d - The dequeue function - * @return {undefined} - */ +function copy(f, t) { + t.a = f.a; + t.b = f.b; + t.c = f.c; + t.d = f.d; + return t; +}; - this._boundLoadResource = function (r, d) { - return _this._loadResource(r, d); - }; - /** - * The resources waiting to be loaded. - * - * @private - * @member {Resource[]} - */ +function impl(seed, opts) { + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof(state) == 'object') copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.tychei = impl; +} - this._queue = queue(this._boundLoadResource, concurrency); +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); - this._queue.pause(); - /** - * All the resources for this loader keyed by name. - * - * @member {object} - */ - this.resources = {}; - /** - * Dispatched once per loaded or errored resource. - * - * The callback looks like {@link Loader.OnProgressSignal}. - * - * @member {Signal} - */ +},{}],54:[function(require,module,exports){ +// A Javascript implementaion of the "xor128" prng algorithm by +// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper - this.onProgress = new Signal(); - /** - * Dispatched once per errored resource. - * - * The callback looks like {@link Loader.OnErrorSignal}. - * - * @member {Signal} - */ +(function(global, module, define) { - this.onError = new Signal(); - /** - * Dispatched once per loaded resource. - * - * The callback looks like {@link Loader.OnLoadSignal}. - * - * @member {Signal} - */ +function XorGen(seed) { + var me = this, strseed = ''; - this.onLoad = new Signal(); - /** - * Dispatched when the loader begins to process the queue. - * - * The callback looks like {@link Loader.OnStartSignal}. - * - * @member {Signal} - */ + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; - this.onStart = new Signal(); - /** - * Dispatched when the queued resources all load. - * - * The callback looks like {@link Loader.OnCompleteSignal}. - * - * @member {Signal} - */ + // Set up generator function. + me.next = function() { + var t = me.x ^ (me.x << 11); + me.x = me.y; + me.y = me.z; + me.z = me.w; + return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8); + }; - this.onComplete = new Signal(); // Add default before middleware + if (seed === (seed | 0)) { + // Integer seed. + me.x = seed; + } else { + // String seed. + strseed += seed; + } - for (var i = 0; i < Loader._defaultBeforeMiddleware.length; ++i) { - this.pre(Loader._defaultBeforeMiddleware[i]); - } // Add default after middleware + // Mix in string seed, then discard an initial batch of 64 values. + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + me.next(); + } +} +function copy(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + return t; +} - for (var _i = 0; _i < Loader._defaultAfterMiddleware.length; ++_i) { - this.use(Loader._defaultAfterMiddleware[_i]); - } +function impl(seed, opts) { + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof(state) == 'object') copy(state, xg); + prng.state = function() { return copy(xg, {}); } } - /** - * When the progress changes the loader and resource are disaptched. - * - * @memberof Loader - * @callback OnProgressSignal - * @param {Loader} loader - The loader the progress is advancing on. - * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. - */ + return prng; +} - /** - * When an error occurrs the loader and resource are disaptched. - * - * @memberof Loader - * @callback OnErrorSignal - * @param {Loader} loader - The loader the error happened in. - * @param {Resource} resource - The resource that caused the error. - */ +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.xor128 = impl; +} - /** - * When a load completes the loader and resource are disaptched. - * - * @memberof Loader - * @callback OnLoadSignal - * @param {Loader} loader - The loader that laoded the resource. - * @param {Resource} resource - The resource that has completed loading. - */ +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); - /** - * When the loader starts loading resources it dispatches this callback. - * - * @memberof Loader - * @callback OnStartSignal - * @param {Loader} loader - The loader that has started loading resources. - */ - /** - * When the loader completes loading resources it dispatches this callback. - * - * @memberof Loader - * @callback OnCompleteSignal - * @param {Loader} loader - The loader that has finished loading resources. - */ - /** - * Options for a call to `.add()`. - * - * @see Loader#add - * - * @typedef {object} IAddOptions - * @property {string} [name] - The name of the resource to load, if not passed the url is used. - * @property {string} [key] - Alias for `name`. - * @property {string} [url] - The url for this resource, relative to the baseUrl of this loader. - * @property {string|boolean} [crossOrigin] - Is this request cross-origin? Default is to - * determine automatically. - * @property {number} [timeout=0] - A timeout in milliseconds for the load. If the load takes - * longer than this time it is cancelled and the load is considered a failure. If this value is - * set to `0` then there is no explicit timeout. - * @property {Resource.LOAD_TYPE} [loadType=Resource.LOAD_TYPE.XHR] - How should this resource - * be loaded? - * @property {Resource.XHR_RESPONSE_TYPE} [xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How - * should the data being loaded be interpreted when using XHR? - * @property {Resource.OnCompleteSignal} [onComplete] - Callback to add an an onComplete signal istener. - * @property {Resource.OnCompleteSignal} [callback] - Alias for `onComplete`. - * @property {Resource.IMetadata} [metadata] - Extra configuration for middleware and the Resource object. - */ +},{}],55:[function(require,module,exports){ +// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm. +// +// This fast non-cryptographic random number generator is designed for +// use in Monte-Carlo algorithms. It combines a long-period xorshift +// generator with a Weyl generator, and it passes all common batteries +// of stasticial tests for randomness while consuming only a few nanoseconds +// for each prng generated. For background on the generator, see Brent's +// paper: "Some long-period random number generators using shifts and xors." +// http://arxiv.org/pdf/1004.3115v1.pdf +// +// Usage: +// +// var xor4096 = require('xor4096'); +// random = xor4096(1); // Seed with int32 or string. +// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits. +// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits. +// +// For nonzero numeric keys, this impelementation provides a sequence +// identical to that by Brent's xorgens 3 implementaion in C. This +// implementation also provides for initalizing the generator with +// string seeds, or for saving and restoring the state of the generator. +// +// On Chrome, this prng benchmarks about 2.1 times slower than +// Javascript's built-in Math.random(). - /* eslint-disable require-jsdoc,valid-jsdoc */ +(function(global, module, define) { + +function XorGen(seed) { + var me = this; + + // Set up generator function. + me.next = function() { + var w = me.w, + X = me.X, i = me.i, t, v; + // Update Weyl generator. + me.w = w = (w + 0x61c88647) | 0; + // Update xor generator. + v = X[(i + 34) & 127]; + t = X[i = ((i + 1) & 127)]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + // Update Xor generator array state. + v = X[i] = v ^ t; + me.i = i; + // Result is the combination. + return (v + (w ^ (w >>> 16))) | 0; + }; + + function init(me, seed) { + var t, v, i, j, w, X = [], limit = 128; + if (seed === (seed | 0)) { + // Numeric seeds initialize v, which is used to generates X. + v = seed; + seed = null; + } else { + // String seeds are mixed into v and X one character at a time. + seed = seed + '\0'; + v = 0; + limit = Math.max(limit, seed.length); + } + // Initialize circular array and weyl value. + for (i = 0, j = -32; j < limit; ++j) { + // Put the unicode characters into the array, and shuffle them. + if (seed) v ^= seed.charCodeAt((j + 32) % seed.length); + // After 32 shuffles, take v as the starting w value. + if (j === 0) w = v; + v ^= v << 10; + v ^= v >>> 15; + v ^= v << 4; + v ^= v >>> 13; + if (j >= 0) { + w = (w + 0x61c88647) | 0; // Weyl. + t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array. + i = (0 == t) ? i + 1 : 0; // Count zeroes. + } + } + // We have detected all zeroes; make the key nonzero. + if (i >= 128) { + X[(seed && seed.length || 0) & 127] = -1; + } + // Run the generator 512 times to further mix the state before using it. + // Factoring this as a function slows the main generator, so it is just + // unrolled here. The weyl generator is not advanced while warming up. + i = 127; + for (j = 4 * 128; j > 0; --j) { + v = X[(i + 34) & 127]; + t = X[i = ((i + 1) & 127)]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + X[i] = v ^ t; + } + // Storing state as object members is faster than using closure variables. + me.w = w; + me.X = X; + me.i = i; + } + + init(me, seed); +} + +function copy(f, t) { + t.i = f.i; + t.w = f.w; + t.X = f.X.slice(); + return t; +}; - /** - * Adds a resource (or multiple resources) to the loader queue. - * - * This function can take a wide variety of different parameters. The only thing that is always - * required the url to load. All the following will work: - * - * ```js - * loader - * // normal param syntax - * .add('key', 'http://...', function () {}) - * .add('http://...', function () {}) - * .add('http://...') - * - * // object syntax - * .add({ - * name: 'key2', - * url: 'http://...' - * }, function () {}) - * .add({ - * url: 'http://...' - * }, function () {}) - * .add({ - * name: 'key3', - * url: 'http://...' - * onComplete: function () {} - * }) - * .add({ - * url: 'https://...', - * onComplete: function () {}, - * crossOrigin: true - * }) - * - * // you can also pass an array of objects or urls or both - * .add([ - * { name: 'key4', url: 'http://...', onComplete: function () {} }, - * { url: 'http://...', onComplete: function () {} }, - * 'http://...' - * ]) - * - * // and you can use both params and options - * .add('key', 'http://...', { crossOrigin: true }, function () {}) - * .add('http://...', { crossOrigin: true }, function () {}); - * ``` - * - * @function - * @variation 1 - * @param {string} name - The name of the resource to load. - * @param {string} url - The url for this resource, relative to the baseUrl of this loader. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ +function impl(seed, opts) { + if (seed == null) seed = +(new Date); + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.X) copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} - /** - * @function - * @variation 2 - * @param {string} name - The name of the resource to load. - * @param {string} url - The url for this resource, relative to the baseUrl of this loader. - * @param {IAddOptions} [options] - The options for the load. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.xor4096 = impl; +} - /** - * @function - * @variation 3 - * @param {string} url - The url for this resource, relative to the baseUrl of this loader. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ +})( + this, // window object or global + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); - /** - * @function - * @variation 4 - * @param {string} url - The url for this resource, relative to the baseUrl of this loader. - * @param {IAddOptions} [options] - The options for the load. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ +},{}],56:[function(require,module,exports){ +// A Javascript implementaion of the "xorshift7" algorithm by +// François Panneton and Pierre L'ecuyer: +// "On the Xorgshift Random Number Generators" +// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf - /** - * @function - * @variation 5 - * @param {IAddOptions} options - The options for the load. This object must contain a `url` property. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ +(function(global, module, define) { - /** - * @function - * @variation 6 - * @param {Array} resources - An array of resources to load, where each is - * either an object with the options or a string url. If you pass an object, it must contain a `url` property. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ +function XorGen(seed) { + var me = this; + // Set up generator function. + me.next = function() { + // Update xor generator. + var X = me.x, i = me.i, t, v, w; + t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24); + t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10); + t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3); + t = X[(i + 4) & 7]; v ^= t ^ (t << 7); + t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9); + X[i] = v; + me.i = (i + 1) & 7; + return v; + }; - var _proto = Loader.prototype; + function init(me, seed) { + var j, w, X = []; - _proto.add = function add(name, url, options, cb) { - // special case of an array of objects or urls - if (Array.isArray(name)) { - for (var i = 0; i < name.length; ++i) { - this.add(name[i]); + if (seed === (seed | 0)) { + // Seed state array using a 32-bit integer. + w = X[0] = seed; + } else { + // Seed state using a string. + seed = '' + seed; + for (j = 0; j < seed.length; ++j) { + X[j & 7] = (X[j & 7] << 15) ^ + (seed.charCodeAt(j) + X[(j + 1) & 7] << 13); } + } + // Enforce an array length of 8, not all zeroes. + while (X.length < 8) X.push(0); + for (j = 0; j < 8 && X[j] === 0; ++j); + if (j == 8) w = X[7] = -1; else w = X[j]; - return this; - } // if an object is passed instead of params + me.x = X; + me.i = 0; + // Discard an initial 256 values. + for (j = 256; j > 0; --j) { + me.next(); + } + } - if (typeof name === 'object') { - cb = url || name.callback || name.onComplete; - options = name; - url = name.url; - name = name.name || name.key || name.url; - } // case where no name is passed shift all args over by one. + init(me, seed); +} +function copy(f, t) { + t.x = f.x.slice(); + t.i = f.i; + return t; +} - if (typeof url !== 'string') { - cb = options; - options = url; - url = name; - } // now that we shifted make sure we have a proper url. +function impl(seed, opts) { + if (seed == null) seed = +(new Date); + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.x) copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.xorshift7 = impl; +} - if (typeof url !== 'string') { - throw new Error('No url passed to add resource to loader.'); - } // options are optional so people might pass a function and no options +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); - if (typeof options === 'function') { - cb = options; - options = null; - } // if loading already you can only add resources that have a parent. +},{}],57:[function(require,module,exports){ +// A Javascript implementaion of the "xorwow" prng algorithm by +// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper +(function(global, module, define) { - if (this.loading && (!options || !options.parentResource)) { - throw new Error('Cannot add resources while the loader is running.'); - } // check if resource already exists. +function XorGen(seed) { + var me = this, strseed = ''; + // Set up generator function. + me.next = function() { + var t = (me.x ^ (me.x >>> 2)); + me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v; + return (me.d = (me.d + 362437 | 0)) + + (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0; + }; - if (this.resources[name]) { - throw new Error("Resource named \"" + name + "\" already exists."); - } // add base url if this isn't an absolute url + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; + me.v = 0; + if (seed === (seed | 0)) { + // Integer seed. + me.x = seed; + } else { + // String seed. + strseed += seed; + } - url = this._prepareUrl(url); // create the store the resource + // Mix in string seed, then discard an initial batch of 64 values. + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + if (k == strseed.length) { + me.d = me.x << 10 ^ me.x >>> 4; + } + me.next(); + } +} - this.resources[name] = new Resource(name, url, options); +function copy(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + t.v = f.v; + t.d = f.d; + return t; +} - if (typeof cb === 'function') { - this.resources[name].onAfterMiddleware.once(cb); - } // if actively loading, make sure to adjust progress chunks for that parent and its children +function impl(seed, opts) { + var xg = new XorGen(seed), + state = opts && opts.state, + prng = function() { return (xg.next() >>> 0) / 0x100000000; }; + prng.double = function() { + do { + var top = xg.next() >>> 11, + bot = (xg.next() >>> 0) / 0x100000000, + result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof(state) == 'object') copy(state, xg); + prng.state = function() { return copy(xg, {}); } + } + return prng; +} +if (module && module.exports) { + module.exports = impl; +} else if (define && define.amd) { + define(function() { return impl; }); +} else { + this.xorwow = impl; +} - if (this.loading) { - var parent = options.parentResource; - var incompleteChildren = []; +})( + this, + (typeof module) == 'object' && module, // present in node.js + (typeof define) == 'function' && define // present with an AMD loader +); - for (var _i2 = 0; _i2 < parent.children.length; ++_i2) { - if (!parent.children[_i2].isComplete) { - incompleteChildren.push(parent.children[_i2]); - } - } - var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent - var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child +},{}],58:[function(require,module,exports){ +/* +Copyright 2019 David Bau. - parent.children.push(this.resources[name]); - parent.progressChunk = eachChunk; +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: - for (var _i3 = 0; _i3 < incompleteChildren.length; ++_i3) { - incompleteChildren[_i3].progressChunk = eachChunk; - } +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. - this.resources[name].progressChunk = eachChunk; - } // add the resource to the queue +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ - this._queue.push(this.resources[name]); +(function (global, pool, math) { +// +// The following constants are related to IEEE 754 limits. +// - return this; - } - /* eslint-enable require-jsdoc,valid-jsdoc */ +var width = 256, // each RC4 output is 0 <= x < 256 + chunks = 6, // at least six RC4 outputs for each double + digits = 52, // there are 52 significant digits in a double + rngname = 'random', // rngname: name for Math.random and Math.seedrandom + startdenom = math.pow(width, chunks), + significance = math.pow(2, digits), + overflow = significance * 2, + mask = width - 1, + nodecrypto; // node.js crypto module, initialized at the bottom. - /** - * Sets up a middleware function that will run *before* the - * resource is loaded. - * - * @param {function} fn - The middleware function to register. - * @return {this} Returns itself. - */ - ; +// +// seedrandom() +// This is the seedrandom function described above. +// +function seedrandom(seed, options, callback) { + var key = []; + options = (options == true) ? { entropy: true } : (options || {}); - _proto.pre = function pre(fn) { - this._beforeMiddleware.push(fn); + // Flatten the seed string or build one from local entropy if needed. + var shortseed = mixkey(flatten( + options.entropy ? [seed, tostring(pool)] : + (seed == null) ? autoseed() : seed, 3), key); - return this; - } - /** - * Sets up a middleware function that will run *after* the - * resource is loaded. - * - * @param {function} fn - The middleware function to register. - * @return {this} Returns itself. - */ - ; + // Use the seed to initialize an ARC4 generator. + var arc4 = new ARC4(key); - _proto.use = function use(fn) { - this._afterMiddleware.push(fn); + // This function returns a random double in [0, 1) that contains + // randomness in every bit of the mantissa of the IEEE 754 value. + var prng = function() { + var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48 + d = startdenom, // and denominator d = 2 ^ 48. + x = 0; // and no 'extra last byte'. + while (n < significance) { // Fill up all significant digits by + n = (n + x) * width; // shifting numerator and + d *= width; // denominator and generating a + x = arc4.g(1); // new least-significant-byte. + } + while (n >= overflow) { // To avoid rounding up, before adding + n /= 2; // last byte, shift everything + d /= 2; // right using integer math until + x >>>= 1; // we have exactly the desired bits. + } + return (n + x) / d; // Form the number within [0, 1). + }; - return this; - } - /** - * Resets the queue of the loader to prepare for a new load. - * - * @return {this} Returns itself. - */ - ; + prng.int32 = function() { return arc4.g(4) | 0; } + prng.quick = function() { return arc4.g(4) / 0x100000000; } + prng.double = prng; - _proto.reset = function reset() { - this.progress = 0; - this.loading = false; + // Mix the randomness into accumulated entropy. + mixkey(tostring(arc4.S), pool); - this._queue.kill(); + // Calling convention: what to return as a function of prng, seed, is_math. + return (options.pass || callback || + function(prng, seed, is_math_call, state) { + if (state) { + // Load the arc4 state from the given state if it has an S array. + if (state.S) { copy(state, arc4); } + // Only provide the .state method if requested via options.state. + prng.state = function() { return copy(arc4, {}); } + } - this._queue.pause(); // abort all resource loads + // If called as a method of Math (Math.seedrandom()), mutate + // Math.random because that is how seedrandom.js has worked since v1.0. + if (is_math_call) { math[rngname] = prng; return seed; } + // Otherwise, it is a newer calling convention, so return the + // prng directly. + else return prng; + })( + prng, + shortseed, + 'global' in options ? options.global : (this == math), + options.state); +} - for (var k in this.resources) { - var res = this.resources[k]; +// +// ARC4 +// +// An ARC4 implementation. The constructor takes a key in the form of +// an array of at most (width) integers that should be 0 <= x < (width). +// +// The g(count) method returns a pseudorandom integer that concatenates +// the next (count) outputs from ARC4. Its return value is a number x +// that is in the range 0 <= x < (width ^ count). +// +function ARC4(key) { + var t, keylen = key.length, + me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; - if (res._onLoadBinding) { - res._onLoadBinding.detach(); - } + // The empty key [] is treated as [0]. + if (!keylen) { key = [keylen++]; } + + // Set up S using the standard key scheduling algorithm. + while (i < width) { + s[i] = i++; + } + for (i = 0; i < width; i++) { + s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))]; + s[j] = t; + } + + // The "g" method returns the next (count) outputs as one number. + (me.g = function(count) { + // Using instance members instead of closure state nearly doubles speed. + var t, r = 0, + i = me.i, j = me.j, s = me.S; + while (count--) { + t = s[i = mask & (i + 1)]; + r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))]; + } + me.i = i; me.j = j; + return r; + // For robust unpredictability, the function call below automatically + // discards an initial batch of values. This is called RC4-drop[256]. + // See http://google.com/search?q=rsa+fluhrer+response&btnI + })(width); +} - if (res.isLoading) { - res.abort(); - } - } +// +// copy() +// Copies internal state of ARC4 to or from a plain object. +// +function copy(f, t) { + t.i = f.i; + t.j = f.j; + t.S = f.S.slice(); + return t; +}; - this.resources = {}; - return this; +// +// flatten() +// Converts an object tree to nested arrays of strings. +// +function flatten(obj, depth) { + var result = [], typ = (typeof obj), prop; + if (depth && typ == 'object') { + for (prop in obj) { + try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} + } } - /** - * Starts loading the queued resources. - * - * @param {function} [cb] - Optional callback that will be bound to the `complete` event. - * @return {this} Returns itself. - */ - ; - - _proto.load = function load(cb) { - // register complete callback if they pass one - if (typeof cb === 'function') { - this.onComplete.once(cb); - } // if the queue has already started we are done here + return (result.length ? result : typ == 'string' ? obj : obj + '\0'); +} +// +// mixkey() +// Mixes a string seed into a key that is an array of integers, and +// returns a shortened string seed that is equivalent to the result key. +// +function mixkey(seed, key) { + var stringseed = seed + '', smear, j = 0; + while (j < stringseed.length) { + key[mask & j] = + mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++)); + } + return tostring(key); +} - if (this.loading) { - return this; +// +// autoseed() +// Returns an object for autoseeding, using window.crypto and Node crypto +// module if available. +// +function autoseed() { + try { + var out; + if (nodecrypto && (out = nodecrypto.randomBytes)) { + // The use of 'out' to remember randomBytes makes tight minified code. + out = out(width); + } else { + out = new Uint8Array(width); + (global.crypto || global.msCrypto).getRandomValues(out); } + return tostring(out); + } catch (e) { + var browser = global.navigator, + plugins = browser && browser.plugins; + return [+new Date, global, plugins, global.screen, tostring(pool)]; + } +} - if (this._queue.idle()) { - this._onStart(); +// +// tostring() +// Converts an array of charcodes to a string +// +function tostring(a) { + return String.fromCharCode.apply(0, a); +} - this._onComplete(); - } else { - // distribute progress chunks - var numTasks = this._queue._tasks.length; - var chunk = MAX_PROGRESS / numTasks; +// +// When seedrandom.js is loaded, we immediately mix a few bits +// from the built-in RNG into the entropy pool. Because we do +// not want to interfere with deterministic PRNG state later, +// seedrandom will not call math.random on its own again after +// initialization. +// +mixkey(math.random(), pool); - for (var i = 0; i < this._queue._tasks.length; ++i) { - this._queue._tasks[i].data.progressChunk = chunk; - } // notify we are starting +// +// Nodejs and AMD support: export the implementation as a module using +// either convention. +// +if ((typeof module) == 'object' && module.exports) { + module.exports = seedrandom; + // When in node.js, try using crypto package for autoseeding. + try { + nodecrypto = require('crypto'); + } catch (ex) {} +} else if ((typeof define) == 'function' && define.amd) { + define(function() { return seedrandom; }); +} else { + // When included as a plain script, set up Math.seedrandom global. + math['seed' + rngname] = seedrandom; +} - this._onStart(); // start loading +// End anonymous scope, and pass initial values. +})( + // global: `self` in browsers (including strict mode and web workers), + // otherwise `this` in Node and other environments + (typeof self !== 'undefined') ? self : this, + [], // pool: entropy pool starts empty + Math // math: package containing random, pow, and seedrandom +); +},{"crypto":63}],59:[function(require,module,exports){ +// TinyColor v1.4.1 +// https://github.com/bgrins/TinyColor +// Brian Grinstead, MIT License - this._queue.resume(); - } +(function(Math) { - return this; - } - /** - * The number of resources to load concurrently. - * - * @member {number} - * @default 10 - */ - ; +var trimLeft = /^\s+/, + trimRight = /\s+$/, + tinyCounter = 0, + mathRound = Math.round, + mathMin = Math.min, + mathMax = Math.max, + mathRandom = Math.random; - /** - * Prepares a url for usage based on the configuration of this object - * - * @private - * @param {string} url - The url to prepare. - * @return {string} The prepared url. - */ - _proto._prepareUrl = function _prepareUrl(url) { - var parsedUrl = parseUri(url, { - strictMode: true - }); - var result; // absolute url, just use it as is. +function tinycolor (color, opts) { - if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { - result = url; - } // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween - else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { - result = this.baseUrl + "/" + url; - } else { - result = this.baseUrl + url; - } // if we need to add a default querystring, there is a bit more work + color = (color) ? color : ''; + opts = opts || { }; + // If input is already a tinycolor, return itself + if (color instanceof tinycolor) { + return color; + } + // If we are called as a function, call using new instead + if (!(this instanceof tinycolor)) { + return new tinycolor(color, opts); + } - if (this.defaultQueryString) { - var hash = rgxExtractUrlHash.exec(result)[0]; - result = result.substr(0, result.length - hash.length); + var rgb = inputToRGB(color); + this._originalInput = color, + this._r = rgb.r, + this._g = rgb.g, + this._b = rgb.b, + this._a = rgb.a, + this._roundA = mathRound(100*this._a) / 100, + this._format = opts.format || rgb.format; + this._gradientType = opts.gradientType; - if (result.indexOf('?') !== -1) { - result += "&" + this.defaultQueryString; - } else { - result += "?" + this.defaultQueryString; - } + // Don't let the range of [0,255] come back in [0,1]. + // Potentially lose a little bit of precision here, but will fix issues where + // .5 gets interpreted as half of the total, instead of half of 1 + // If it was supposed to be 128, this was already taken care of by `inputToRgb` + if (this._r < 1) { this._r = mathRound(this._r); } + if (this._g < 1) { this._g = mathRound(this._g); } + if (this._b < 1) { this._b = mathRound(this._b); } - result += hash; - } + this._ok = rgb.ok; + this._tc_id = tinyCounter++; +} - return result; - } - /** - * Loads a single resource. - * - * @private - * @param {Resource} resource - The resource to load. - * @param {function} dequeue - The function to call when we need to dequeue this item. - */ - ; +tinycolor.prototype = { + isDark: function() { + return this.getBrightness() < 128; + }, + isLight: function() { + return !this.isDark(); + }, + isValid: function() { + return this._ok; + }, + getOriginalInput: function() { + return this._originalInput; + }, + getFormat: function() { + return this._format; + }, + getAlpha: function() { + return this._a; + }, + getBrightness: function() { + //http://www.w3.org/TR/AERT#color-contrast + var rgb = this.toRgb(); + return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; + }, + getLuminance: function() { + //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + var rgb = this.toRgb(); + var RsRGB, GsRGB, BsRGB, R, G, B; + RsRGB = rgb.r/255; + GsRGB = rgb.g/255; + BsRGB = rgb.b/255; - _proto._loadResource = function _loadResource(resource, dequeue) { - var _this2 = this; + if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);} + if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);} + if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);} + return (0.2126 * R) + (0.7152 * G) + (0.0722 * B); + }, + setAlpha: function(value) { + this._a = boundAlpha(value); + this._roundA = mathRound(100*this._a) / 100; + return this; + }, + toHsv: function() { + var hsv = rgbToHsv(this._r, this._g, this._b); + return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; + }, + toHsvString: function() { + var hsv = rgbToHsv(this._r, this._g, this._b); + var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); + return (this._a == 1) ? + "hsv(" + h + ", " + s + "%, " + v + "%)" : + "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")"; + }, + toHsl: function() { + var hsl = rgbToHsl(this._r, this._g, this._b); + return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; + }, + toHslString: function() { + var hsl = rgbToHsl(this._r, this._g, this._b); + var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); + return (this._a == 1) ? + "hsl(" + h + ", " + s + "%, " + l + "%)" : + "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")"; + }, + toHex: function(allow3Char) { + return rgbToHex(this._r, this._g, this._b, allow3Char); + }, + toHexString: function(allow3Char) { + return '#' + this.toHex(allow3Char); + }, + toHex8: function(allow4Char) { + return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); + }, + toHex8String: function(allow4Char) { + return '#' + this.toHex8(allow4Char); + }, + toRgb: function() { + return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a }; + }, + toRgbString: function() { + return (this._a == 1) ? + "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" : + "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")"; + }, + toPercentageRgb: function() { + return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a }; + }, + toPercentageRgbString: function() { + return (this._a == 1) ? + "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" : + "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; + }, + toName: function() { + if (this._a === 0) { + return "transparent"; + } - resource._dequeue = dequeue; // run before middleware + if (this._a < 1) { + return false; + } - eachSeries(this._beforeMiddleware, function (fn, next) { - fn.call(_this2, resource, function () { - // if the before middleware marks the resource as complete, - // break and don't process any more before middleware - next(resource.isComplete ? {} : null); - }); - }, function () { - if (resource.isComplete) { - _this2._onLoad(resource); - } else { - resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); - resource.load(); - } - }, true); - } - /** - * Called once loading has started. - * - * @private - */ - ; + return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; + }, + toFilter: function(secondColor) { + var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a); + var secondHex8String = hex8String; + var gradientType = this._gradientType ? "GradientType = 1, " : ""; - _proto._onStart = function _onStart() { - this.progress = 0; - this.loading = true; - this.onStart.dispatch(this); - } - /** - * Called once each resource has loaded. - * - * @private - */ - ; + if (secondColor) { + var s = tinycolor(secondColor); + secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a); + } - _proto._onComplete = function _onComplete() { - this.progress = MAX_PROGRESS; - this.loading = false; - this.onComplete.dispatch(this, this.resources); - } - /** - * Called each time a resources is loaded. - * - * @private - * @param {Resource} resource - The resource that was loaded - */ - ; + return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")"; + }, + toString: function(format) { + var formatSet = !!format; + format = format || this._format; - _proto._onLoad = function _onLoad(resource) { - var _this3 = this; + var formattedString = false; + var hasAlpha = this._a < 1 && this._a >= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); - resource._onLoadBinding = null; // remove this resource from the async queue, and add it to our list of resources that are being parsed + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); + } + if (format === "rgb") { + formattedString = this.toRgbString(); + } + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex4") { + formattedString = this.toHex8String(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); + } - this._resourcesParsing.push(resource); + return formattedString || this.toHexString(); + }, + clone: function() { + return tinycolor(this.toString()); + }, - resource._dequeue(); // run all the after middleware for this resource + _applyModification: function(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function() { + return this._applyModification(lighten, arguments); + }, + brighten: function() { + return this._applyModification(brighten, arguments); + }, + darken: function() { + return this._applyModification(darken, arguments); + }, + desaturate: function() { + return this._applyModification(desaturate, arguments); + }, + saturate: function() { + return this._applyModification(saturate, arguments); + }, + greyscale: function() { + return this._applyModification(greyscale, arguments); + }, + spin: function() { + return this._applyModification(spin, arguments); + }, + _applyCombination: function(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function() { + return this._applyCombination(analogous, arguments); + }, + complement: function() { + return this._applyCombination(complement, arguments); + }, + monochromatic: function() { + return this._applyCombination(monochromatic, arguments); + }, + splitcomplement: function() { + return this._applyCombination(splitcomplement, arguments); + }, + triad: function() { + return this._applyCombination(triad, arguments); + }, + tetrad: function() { + return this._applyCombination(tetrad, arguments); + } +}; - eachSeries(this._afterMiddleware, function (fn, next) { - fn.call(_this3, resource, next); - }, function () { - resource.onAfterMiddleware.dispatch(resource); - _this3.progress = Math.min(MAX_PROGRESS, _this3.progress + resource.progressChunk); +// If input is an object, force 1 into "1.0" to handle ratios properly +// String input requires "1.0" as input, so 1 will be treated as 1 +tinycolor.fromRatio = function(color, opts) { + if (typeof color == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } + else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; + } - _this3.onProgress.dispatch(_this3, resource); + return tinycolor(color, opts); +}; - if (resource.error) { - _this3.onError.dispatch(resource.error, _this3, resource); - } else { - _this3.onLoad.dispatch(_this3, resource); - } +// Given a string or object, convert that input to RGB +// Possible string inputs: +// +// "red" +// "#f00" or "f00" +// "#ff0000" or "ff0000" +// "#ff000000" or "ff000000" +// "rgb 255 0 0" or "rgb (255, 0, 0)" +// "rgb 1.0 0 0" or "rgb (1, 0, 0)" +// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" +// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" +// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" +// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" +// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" +// +function inputToRGB(color) { - _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); // do completion check + var rgb = { r: 0, g: 0, b: 0 }; + var a = 1; + var s = null; + var v = null; + var l = null; + var ok = false; + var format = false; + if (typeof color == "string") { + color = stringInputToObject(color); + } - if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { - _this3._onComplete(); - } - }, true); - }; + if (typeof color == "object") { + if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } + else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { + s = convertToPercentage(color.s); + v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, s, v); + ok = true; + format = "hsv"; + } + else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { + s = convertToPercentage(color.s); + l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, s, l); + ok = true; + format = "hsl"; + } - _createClass(Loader, [{ - key: "concurrency", - get: function get() { - return this._queue.concurrency; - } // eslint-disable-next-line require-jsdoc - , - set: function set(concurrency) { - this._queue.concurrency = concurrency; + if (color.hasOwnProperty("a")) { + a = color.a; + } } - }]); - return Loader; -}(); -/** - * A default array of middleware to run before loading each resource. - * Each of these middlewares are added to any new Loader instances when they are created. - * - * @private - * @member {function[]} - */ + a = boundAlpha(a); + return { + ok: ok, + format: color.format || format, + r: mathMin(255, mathMax(rgb.r, 0)), + g: mathMin(255, mathMax(rgb.g, 0)), + b: mathMin(255, mathMax(rgb.b, 0)), + a: a + }; +} -Loader._defaultBeforeMiddleware = []; -/** - * A default array of middleware to run after loading each resource. - * Each of these middlewares are added to any new Loader instances when they are created. - * - * @private - * @member {function[]} - */ -Loader._defaultAfterMiddleware = []; -/** - * Sets up a middleware function that will run *before* the - * resource is loaded. - * - * @static - * @param {function} fn - The middleware function to register. - * @return {Loader} Returns itself. - */ +// Conversion Functions +// -------------------- -Loader.pre = function LoaderPreStatic(fn) { - Loader._defaultBeforeMiddleware.push(fn); +// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: +// - return Loader; -}; -/** - * Sets up a middleware function that will run *after* the - * resource is loaded. - * - * @static - * @param {function} fn - The middleware function to register. - * @return {Loader} Returns itself. - */ +// `rgbToRgb` +// Handle bounds / percentage checking to conform to CSS color spec +// +// *Assumes:* r, g, b in [0, 255] or [0, 1] +// *Returns:* { r, g, b } in [0, 255] +function rgbToRgb(r, g, b){ + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; +} +// `rgbToHsl` +// Converts an RGB color value to HSL. +// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] +// *Returns:* { h, s, l } in [0,1] +function rgbToHsl(r, g, b) { -Loader.use = function LoaderUseStatic(fn) { - Loader._defaultAfterMiddleware.push(fn); + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); - return Loader; -}; + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, l = (max + min) / 2; -exports.Loader = Loader; -exports.Resource = Resource; -exports.async = async; -exports.encodeBinary = encodeBinary; -exports.middleware = index; + if(max == min) { + h = s = 0; // achromatic + } + else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } -},{"mini-signals":53,"parse-uri":55}],59:[function(require,module,exports){ -// A library of seedable RNGs implemented in Javascript. -// -// Usage: -// -// var seedrandom = require('seedrandom'); -// var random = seedrandom(1); // or any seed. -// var x = random(); // 0 <= x < 1. Every bit is random. -// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness. + return { h: h, s: s, l: l }; +} -// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe. -// Period: ~2^116 -// Reported to pass all BigCrush tests. -var alea = require('./lib/alea'); +// `hslToRgb` +// Converts an HSL color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] +function hslToRgb(h, s, l) { + var r, g, b; -// xor128, a pure xor-shift generator by George Marsaglia. -// Period: 2^128-1. -// Reported to fail: MatrixRank and LinearComp. -var xor128 = require('./lib/xor128'); + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); -// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl. -// Period: 2^192-2^32 -// Reported to fail: CollisionOver, SimpPoker, and LinearComp. -var xorwow = require('./lib/xorwow'); + function hue2rgb(p, q, t) { + if(t < 0) t += 1; + if(t > 1) t -= 1; + if(t < 1/6) return p + (q - p) * 6 * t; + if(t < 1/2) return q; + if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; + } -// xorshift7, by François Panneton and Pierre L'ecuyer, takes -// a different approach: it adds robustness by allowing more shifts -// than Marsaglia's original three. It is a 7-shift generator -// with 256 bits, that passes BigCrush with no systmatic failures. -// Period 2^256-1. -// No systematic BigCrush failures reported. -var xorshift7 = require('./lib/xorshift7'); + if(s === 0) { + r = g = b = l; // achromatic + } + else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1/3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1/3); + } -// xor4096, by Richard Brent, is a 4096-bit xor-shift with a -// very long period that also adds a Weyl generator. It also passes -// BigCrush with no systematic failures. Its long period may -// be useful if you have many generators and need to avoid -// collisions. -// Period: 2^4128-2^32. -// No systematic BigCrush failures reported. -var xor4096 = require('./lib/xor4096'); + return { r: r * 255, g: g * 255, b: b * 255 }; +} -// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random -// number generator derived from ChaCha, a modern stream cipher. -// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf -// Period: ~2^127 -// No systematic BigCrush failures reported. -var tychei = require('./lib/tychei'); +// `rgbToHsv` +// Converts an RGB color value to HSV +// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] +// *Returns:* { h, s, v } in [0,1] +function rgbToHsv(r, g, b) { -// The original ARC4-based prng included in this library. -// Period: ~2^1600 -var sr = require('./seedrandom'); + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); -sr.alea = alea; -sr.xor128 = xor128; -sr.xorwow = xorwow; -sr.xorshift7 = xorshift7; -sr.xor4096 = xor4096; -sr.tychei = tychei; + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, v = max; -module.exports = sr; + var d = max - min; + s = max === 0 ? 0 : d / max; -},{"./lib/alea":60,"./lib/tychei":61,"./lib/xor128":62,"./lib/xor4096":63,"./lib/xorshift7":64,"./lib/xorwow":65,"./seedrandom":66}],60:[function(require,module,exports){ -// A port of an algorithm by Johannes Baagøe , 2010 -// http://baagoe.com/en/RandomMusings/javascript/ -// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror -// Original work is under MIT license - + if(max == min) { + h = 0; // achromatic + } + else { + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + return { h: h, s: s, v: v }; +} -// Copyright (C) 2010 by Johannes Baagøe -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. +// `hsvToRgb` +// Converts an HSV color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + var i = Math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; -(function(global, module, define) { + return { r: r * 255, g: g * 255, b: b * 255 }; +} -function Alea(seed) { - var me = this, mash = Mash(); +// `rgbToHex` +// Converts an RGB color to hex +// Assumes r, g, and b are contained in the set [0, 255] +// Returns a 3 or 6 character hex +function rgbToHex(r, g, b, allow3Char) { - me.next = function() { - var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32 - me.s0 = me.s1; - me.s1 = me.s2; - return me.s2 = t - (me.c = t | 0); - }; + var hex = [ + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; - // Apply the seeding algorithm from Baagoe. - me.c = 1; - me.s0 = mash(' '); - me.s1 = mash(' '); - me.s2 = mash(' '); - me.s0 -= mash(seed); - if (me.s0 < 0) { me.s0 += 1; } - me.s1 -= mash(seed); - if (me.s1 < 0) { me.s1 += 1; } - me.s2 -= mash(seed); - if (me.s2 < 0) { me.s2 += 1; } - mash = null; -} + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + } -function copy(f, t) { - t.c = f.c; - t.s0 = f.s0; - t.s1 = f.s1; - t.s2 = f.s2; - return t; + return hex.join(""); } -function impl(seed, opts) { - var xg = new Alea(seed), - state = opts && opts.state, - prng = xg.next; - prng.int32 = function() { return (xg.next() * 0x100000000) | 0; } - prng.double = function() { - return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 - }; - prng.quick = prng; - if (state) { - if (typeof(state) == 'object') copy(state, xg); - prng.state = function() { return copy(xg, {}); } - } - return prng; -} +// `rgbaToHex` +// Converts an RGBA color plus alpha transparency to hex +// Assumes r, g, b are contained in the set [0, 255] and +// a in [0, 1]. Returns a 4 or 8 character rgba hex +function rgbaToHex(r, g, b, a, allow4Char) { -function Mash() { - var n = 0xefc8249d; + var hex = [ + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)), + pad2(convertDecimalToHex(a)) + ]; - var mash = function(data) { - data = String(data); - for (var i = 0; i < data.length; i++) { - n += data.charCodeAt(i); - var h = 0.02519603282416938 * n; - n = h >>> 0; - h -= n; - h *= n; - n = h >>> 0; - h -= n; - n += h * 0x100000000; // 2^32 + // Return a 4 character hex if possible + if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); } - return (n >>> 0) * 2.3283064365386963e-10; // 2^-32 - }; - return mash; + return hex.join(""); } +// `rgbaToArgbHex` +// Converts an RGBA color to an ARGB Hex8 string +// Rarely used, but required for "toFilter()" +function rgbaToArgbHex(r, g, b, a) { -if (module && module.exports) { - module.exports = impl; -} else if (define && define.amd) { - define(function() { return impl; }); -} else { - this.alea = impl; -} + var hex = [ + pad2(convertDecimalToHex(a)), + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; -})( - this, - (typeof module) == 'object' && module, // present in node.js - (typeof define) == 'function' && define // present with an AMD loader -); + return hex.join(""); +} +// `equals` +// Can be called with any tinycolor input +tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) { return false; } + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); +}; +tinycolor.random = function() { + return tinycolor.fromRatio({ + r: mathRandom(), + g: mathRandom(), + b: mathRandom() + }); +}; -},{}],61:[function(require,module,exports){ -// A Javascript implementaion of the "Tyche-i" prng algorithm by -// Samuel Neves and Filipe Araujo. -// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf -(function(global, module, define) { +// Modification Functions +// ---------------------- +// Thanks to less.js for some of the basics here +// -function XorGen(seed) { - var me = this, strseed = ''; +function desaturate(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); +} - // Set up generator function. - me.next = function() { - var b = me.b, c = me.c, d = me.d, a = me.a; - b = (b << 25) ^ (b >>> 7) ^ c; - c = (c - d) | 0; - d = (d << 24) ^ (d >>> 8) ^ a; - a = (a - b) | 0; - me.b = b = (b << 20) ^ (b >>> 12) ^ c; - me.c = c = (c - d) | 0; - me.d = (d << 16) ^ (c >>> 16) ^ a; - return me.a = (a - b) | 0; - }; +function saturate(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); +} - /* The following is non-inverted tyche, which has better internal - * bit diffusion, but which is about 25% slower than tyche-i in JS. - me.next = function() { - var a = me.a, b = me.b, c = me.c, d = me.d; - a = (me.a + me.b | 0) >>> 0; - d = me.d ^ a; d = d << 16 ^ d >>> 16; - c = me.c + d | 0; - b = me.b ^ c; b = b << 12 ^ d >>> 20; - me.a = a = a + b | 0; - d = d ^ a; me.d = d = d << 8 ^ d >>> 24; - me.c = c = c + d | 0; - b = b ^ c; - return me.b = (b << 7 ^ b >>> 25); - } - */ +function greyscale(color) { + return tinycolor(color).desaturate(100); +} - me.a = 0; - me.b = 0; - me.c = 2654435769 | 0; - me.d = 1367130551; +function lighten (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); +} - if (seed === Math.floor(seed)) { - // Integer seed. - me.a = (seed / 0x100000000) | 0; - me.b = seed | 0; - } else { - // String seed. - strseed += seed; - } +function brighten(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var rgb = tinycolor(color).toRgb(); + rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); + rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); + rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); + return tinycolor(rgb); +} - // Mix in string seed, then discard an initial batch of 64 values. - for (var k = 0; k < strseed.length + 20; k++) { - me.b ^= strseed.charCodeAt(k) | 0; - me.next(); - } +function darken (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); } -function copy(f, t) { - t.a = f.a; - t.b = f.b; - t.c = f.c; - t.d = f.d; - return t; -}; +// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. +// Values outside of this range will be wrapped into this range. +function spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (hsl.h + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); +} -function impl(seed, opts) { - var xg = new XorGen(seed), - state = opts && opts.state, - prng = function() { return (xg.next() >>> 0) / 0x100000000; }; - prng.double = function() { - do { - var top = xg.next() >>> 11, - bot = (xg.next() >>> 0) / 0x100000000, - result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof(state) == 'object') copy(state, xg); - prng.state = function() { return copy(xg, {}); } - } - return prng; +// Combination Functions +// --------------------- +// Thanks to jQuery xColor for some of the ideas behind these +// + +function complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); } -if (module && module.exports) { - module.exports = impl; -} else if (define && define.amd) { - define(function() { return impl; }); -} else { - this.tychei = impl; +function triad(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) + ]; } -})( - this, - (typeof module) == 'object' && module, // present in node.js - (typeof define) == 'function' && define // present with an AMD loader -); +function tetrad(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) + ]; +} +function splitcomplement(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), + tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) + ]; +} +function analogous(color, results, slices) { + results = results || 6; + slices = slices || 30; -},{}],62:[function(require,module,exports){ -// A Javascript implementaion of the "xor128" prng algorithm by -// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; -(function(global, module, define) { + for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); + } + return ret; +} -function XorGen(seed) { - var me = this, strseed = ''; +function monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, s = hsv.s, v = hsv.v; + var ret = []; + var modification = 1 / results; - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; + while (results--) { + ret.push(tinycolor({ h: h, s: s, v: v})); + v = (v + modification) % 1; + } - // Set up generator function. - me.next = function() { - var t = me.x ^ (me.x << 11); - me.x = me.y; - me.y = me.z; - me.z = me.w; - return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8); - }; + return ret; +} - if (seed === (seed | 0)) { - // Integer seed. - me.x = seed; - } else { - // String seed. - strseed += seed; - } +// Utility Functions +// --------------------- - // Mix in string seed, then discard an initial batch of 64 values. - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - me.next(); - } -} +tinycolor.mix = function(color1, color2, amount) { + amount = (amount === 0) ? 0 : (amount || 50); -function copy(f, t) { - t.x = f.x; - t.y = f.y; - t.z = f.z; - t.w = f.w; - return t; -} + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); -function impl(seed, opts) { - var xg = new XorGen(seed), - state = opts && opts.state, - prng = function() { return (xg.next() >>> 0) / 0x100000000; }; - prng.double = function() { - do { - var top = xg.next() >>> 11, - bot = (xg.next() >>> 0) / 0x100000000, - result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof(state) == 'object') copy(state, xg); - prng.state = function() { return copy(xg, {}); } - } - return prng; -} + var p = amount / 100; -if (module && module.exports) { - module.exports = impl; -} else if (define && define.amd) { - define(function() { return impl; }); -} else { - this.xor128 = impl; -} + var rgba = { + r: ((rgb2.r - rgb1.r) * p) + rgb1.r, + g: ((rgb2.g - rgb1.g) * p) + rgb1.g, + b: ((rgb2.b - rgb1.b) * p) + rgb1.b, + a: ((rgb2.a - rgb1.a) * p) + rgb1.a + }; -})( - this, - (typeof module) == 'object' && module, // present in node.js - (typeof define) == 'function' && define // present with an AMD loader -); + return tinycolor(rgba); +}; +// Readability Functions +// --------------------- +// false +// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false +tinycolor.isReadable = function(color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; - // Set up generator function. - me.next = function() { - var w = me.w, - X = me.X, i = me.i, t, v; - // Update Weyl generator. - me.w = w = (w + 0x61c88647) | 0; - // Update xor generator. - v = X[(i + 34) & 127]; - t = X[i = ((i + 1) & 127)]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - // Update Xor generator array state. - v = X[i] = v ^ t; - me.i = i; - // Result is the combination. - return (v + (w ^ (w >>> 16))) | 0; - }; + out = false; - function init(me, seed) { - var t, v, i, j, w, X = [], limit = 128; - if (seed === (seed | 0)) { - // Numeric seeds initialize v, which is used to generates X. - v = seed; - seed = null; - } else { - // String seeds are mixed into v and X one character at a time. - seed = seed + '\0'; - v = 0; - limit = Math.max(limit, seed.length); + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; } - // Initialize circular array and weyl value. - for (i = 0, j = -32; j < limit; ++j) { - // Put the unicode characters into the array, and shuffle them. - if (seed) v ^= seed.charCodeAt((j + 32) % seed.length); - // After 32 shuffles, take v as the starting w value. - if (j === 0) w = v; - v ^= v << 10; - v ^= v >>> 15; - v ^= v << 4; - v ^= v >>> 13; - if (j >= 0) { - w = (w + 0x61c88647) | 0; // Weyl. - t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array. - i = (0 == t) ? i + 1 : 0; // Count zeroes. - } + return out; + +}; + +// `mostReadable` +// Given a base color and a list of possible foreground or background +// colors for that base, returns the most readable color. +// Optionally returns Black or White if the most readable color is unreadable. +// *Example* +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" +tinycolor.mostReadable = function(baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size ; + args = args || {}; + includeFallbackColors = args.includeFallbackColors ; + level = args.level; + size = args.size; + + for (var i= 0; i < colorList.length ; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); + } } - // We have detected all zeroes; make the key nonzero. - if (i >= 128) { - X[(seed && seed.length || 0) & 127] = -1; + + if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { + return bestColor; } - // Run the generator 512 times to further mix the state before using it. - // Factoring this as a function slows the main generator, so it is just - // unrolled here. The weyl generator is not advanced while warming up. - i = 127; - for (j = 4 * 128; j > 0; --j) { - v = X[(i + 34) & 127]; - t = X[i = ((i + 1) & 127)]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - X[i] = v ^ t; + else { + args.includeFallbackColors=false; + return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); } - // Storing state as object members is faster than using closure variables. - me.w = w; - me.X = X; - me.i = i; - } +}; + + +// Big List of Colors +// ------------------ +// +var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" +}; - init(me, seed); -} +// Make it easy to access colors via `hexNames[hex]` +var hexNames = tinycolor.hexNames = flip(names); -function copy(f, t) { - t.i = f.i; - t.w = f.w; - t.X = f.X.slice(); - return t; -}; -function impl(seed, opts) { - if (seed == null) seed = +(new Date); - var xg = new XorGen(seed), - state = opts && opts.state, - prng = function() { return (xg.next() >>> 0) / 0x100000000; }; - prng.double = function() { - do { - var top = xg.next() >>> 11, - bot = (xg.next() >>> 0) / 0x100000000, - result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (state.X) copy(state, xg); - prng.state = function() { return copy(xg, {}); } - } - return prng; -} +// Utilities +// --------- -if (module && module.exports) { - module.exports = impl; -} else if (define && define.amd) { - define(function() { return impl; }); -} else { - this.xor4096 = impl; +// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` +function flip(o) { + var flipped = { }; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; } -})( - this, // window object or global - (typeof module) == 'object' && module, // present in node.js - (typeof define) == 'function' && define // present with an AMD loader -); - -},{}],64:[function(require,module,exports){ -// A Javascript implementaion of the "xorshift7" algorithm by -// François Panneton and Pierre L'ecuyer: -// "On the Xorgshift Random Number Generators" -// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf +// Return a valid alpha value [0,1] with all invalid values being set to 1 +function boundAlpha(a) { + a = parseFloat(a); -(function(global, module, define) { + if (isNaN(a) || a < 0 || a > 1) { + a = 1; + } -function XorGen(seed) { - var me = this; + return a; +} - // Set up generator function. - me.next = function() { - // Update xor generator. - var X = me.x, i = me.i, t, v, w; - t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24); - t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10); - t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3); - t = X[(i + 4) & 7]; v ^= t ^ (t << 7); - t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9); - X[i] = v; - me.i = (i + 1) & 7; - return v; - }; +// Take input from [0, n] and return it as [0, 1] +function bound01(n, max) { + if (isOnePointZero(n)) { n = "100%"; } - function init(me, seed) { - var j, w, X = []; + var processPercent = isPercentage(n); + n = mathMin(max, mathMax(0, parseFloat(n))); - if (seed === (seed | 0)) { - // Seed state array using a 32-bit integer. - w = X[0] = seed; - } else { - // Seed state using a string. - seed = '' + seed; - for (j = 0; j < seed.length; ++j) { - X[j & 7] = (X[j & 7] << 15) ^ - (seed.charCodeAt(j) + X[(j + 1) & 7] << 13); - } + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; } - // Enforce an array length of 8, not all zeroes. - while (X.length < 8) X.push(0); - for (j = 0; j < 8 && X[j] === 0; ++j); - if (j == 8) w = X[7] = -1; else w = X[j]; - - me.x = X; - me.i = 0; - // Discard an initial 256 values. - for (j = 256; j > 0; --j) { - me.next(); + // Handle floating point rounding errors + if ((Math.abs(n - max) < 0.000001)) { + return 1; } - } - init(me, seed); + // Convert into [0, 1] range if it isn't already + return (n % max) / parseFloat(max); } -function copy(f, t) { - t.x = f.x.slice(); - t.i = f.i; - return t; +// Force a number between 0 and 1 +function clamp01(val) { + return mathMin(1, mathMax(0, val)); } -function impl(seed, opts) { - if (seed == null) seed = +(new Date); - var xg = new XorGen(seed), - state = opts && opts.state, - prng = function() { return (xg.next() >>> 0) / 0x100000000; }; - prng.double = function() { - do { - var top = xg.next() >>> 11, - bot = (xg.next() >>> 0) / 0x100000000, - result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (state.x) copy(state, xg); - prng.state = function() { return copy(xg, {}); } - } - return prng; +// Parse a base-16 hex value into a base-10 integer +function parseIntFromHex(val) { + return parseInt(val, 16); } -if (module && module.exports) { - module.exports = impl; -} else if (define && define.amd) { - define(function() { return impl; }); -} else { - this.xorshift7 = impl; +// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 +// +function isOnePointZero(n) { + return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; } -})( - this, - (typeof module) == 'object' && module, // present in node.js - (typeof define) == 'function' && define // present with an AMD loader -); - - -},{}],65:[function(require,module,exports){ -// A Javascript implementaion of the "xorwow" prng algorithm by -// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper - -(function(global, module, define) { - -function XorGen(seed) { - var me = this, strseed = ''; - - // Set up generator function. - me.next = function() { - var t = (me.x ^ (me.x >>> 2)); - me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v; - return (me.d = (me.d + 362437 | 0)) + - (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0; - }; - - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; - me.v = 0; +// Check to see if string passed in is a percentage +function isPercentage(n) { + return typeof n === "string" && n.indexOf('%') != -1; +} - if (seed === (seed | 0)) { - // Integer seed. - me.x = seed; - } else { - // String seed. - strseed += seed; - } +// Force a hex value to have 2 characters +function pad2(c) { + return c.length == 1 ? '0' + c : '' + c; +} - // Mix in string seed, then discard an initial batch of 64 values. - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - if (k == strseed.length) { - me.d = me.x << 10 ^ me.x >>> 4; +// Replace a decimal with it's percentage value +function convertToPercentage(n) { + if (n <= 1) { + n = (n * 100) + "%"; } - me.next(); - } -} -function copy(f, t) { - t.x = f.x; - t.y = f.y; - t.z = f.z; - t.w = f.w; - t.v = f.v; - t.d = f.d; - return t; + return n; } -function impl(seed, opts) { - var xg = new XorGen(seed), - state = opts && opts.state, - prng = function() { return (xg.next() >>> 0) / 0x100000000; }; - prng.double = function() { - do { - var top = xg.next() >>> 11, - bot = (xg.next() >>> 0) / 0x100000000, - result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof(state) == 'object') copy(state, xg); - prng.state = function() { return copy(xg, {}); } - } - return prng; +// Converts a decimal to a hex value +function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); } - -if (module && module.exports) { - module.exports = impl; -} else if (define && define.amd) { - define(function() { return impl; }); -} else { - this.xorwow = impl; +// Converts a hex value to a decimal +function convertHexToDecimal(h) { + return (parseIntFromHex(h) / 255); } -})( - this, - (typeof module) == 'object' && module, // present in node.js - (typeof define) == 'function' && define // present with an AMD loader -); +var matchers = (function() { + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; -},{}],66:[function(require,module,exports){ -/* -Copyright 2019 David Bau. + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. + return { + CSS_UNIT: new RegExp(CSS_UNIT), + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; +})(); -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// `isValidCSSUnit` +// Take in a single string / number and check to see if it looks like a CSS unit +// (see `matchers` above for definition). +function isValidCSSUnit(color) { + return !!matchers.CSS_UNIT.exec(color); +} -*/ +// `stringInputToObject` +// Permissive string parsing. Take in a number of formats, and output an object +// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` +function stringInputToObject(color) { -(function (global, pool, math) { -// -// The following constants are related to IEEE 754 limits. -// + color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; + } + else if (color == 'transparent') { + return { r: 0, g: 0, b: 0, a: 0, format: "name" }; + } -var width = 256, // each RC4 output is 0 <= x < 256 - chunks = 6, // at least six RC4 outputs for each double - digits = 52, // there are 52 significant digits in a double - rngname = 'random', // rngname: name for Math.random and Math.seedrandom - startdenom = math.pow(width, chunks), - significance = math.pow(2, digits), - overflow = significance * 2, - mask = width - 1, - nodecrypto; // node.js crypto module, initialized at the bottom. + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if ((match = matchers.rgb.exec(color))) { + return { r: match[1], g: match[2], b: match[3] }; + } + if ((match = matchers.rgba.exec(color))) { + return { r: match[1], g: match[2], b: match[3], a: match[4] }; + } + if ((match = matchers.hsl.exec(color))) { + return { h: match[1], s: match[2], l: match[3] }; + } + if ((match = matchers.hsla.exec(color))) { + return { h: match[1], s: match[2], l: match[3], a: match[4] }; + } + if ((match = matchers.hsv.exec(color))) { + return { h: match[1], s: match[2], v: match[3] }; + } + if ((match = matchers.hsva.exec(color))) { + return { h: match[1], s: match[2], v: match[3], a: match[4] }; + } + if ((match = matchers.hex8.exec(color))) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + a: convertHexToDecimal(match[4]), + format: named ? "name" : "hex8" + }; + } + if ((match = matchers.hex6.exec(color))) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if ((match = matchers.hex4.exec(color))) { + return { + r: parseIntFromHex(match[1] + '' + match[1]), + g: parseIntFromHex(match[2] + '' + match[2]), + b: parseIntFromHex(match[3] + '' + match[3]), + a: convertHexToDecimal(match[4] + '' + match[4]), + format: named ? "name" : "hex8" + }; + } + if ((match = matchers.hex3.exec(color))) { + return { + r: parseIntFromHex(match[1] + '' + match[1]), + g: parseIntFromHex(match[2] + '' + match[2]), + b: parseIntFromHex(match[3] + '' + match[3]), + format: named ? "name" : "hex" + }; + } -// -// seedrandom() -// This is the seedrandom function described above. -// -function seedrandom(seed, options, callback) { - var key = []; - options = (options == true) ? { entropy: true } : (options || {}); + return false; +} - // Flatten the seed string or build one from local entropy if needed. - var shortseed = mixkey(flatten( - options.entropy ? [seed, tostring(pool)] : - (seed == null) ? autoseed() : seed, 3), key); +function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || {"level":"AA", "size":"small"}; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return {"level":level, "size":size}; +} - // Use the seed to initialize an ARC4 generator. - var arc4 = new ARC4(key); +// Node: Export function +if (typeof module !== "undefined" && module.exports) { + module.exports = tinycolor; +} +// AMD/requirejs: Define the module +else if (typeof define === 'function' && define.amd) { + define(function () {return tinycolor;}); +} +// Browser: Expose to window +else { + window.tinycolor = tinycolor; +} - // This function returns a random double in [0, 1) that contains - // randomness in every bit of the mantissa of the IEEE 754 value. - var prng = function() { - var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48 - d = startdenom, // and denominator d = 2 ^ 48. - x = 0; // and no 'extra last byte'. - while (n < significance) { // Fill up all significant digits by - n = (n + x) * width; // shifting numerator and - d *= width; // denominator and generating a - x = arc4.g(1); // new least-significant-byte. +})(Math); + +},{}],60:[function(require,module,exports){ +// yy-counter +// In-browser counter to watch changeable values like counters or FPS +// David Figatner +// (c) YOPEY YOPEY LLC 2017 +// MIT License +// https://github.com/davidfig/counter + +module.exports = class Counter +{ + /** + * @param {object} [options] + * @param {string} [options.side=rightbottom] side to place the panel (combination of right/left and bottom/top) + * @param {number} [options.padding=7px] + * @param {string} [options.color=white] + * @param {string} [options.background=rgba(0,0,0,0.5)] + * @param {*} {options.xxx} where xxx is a CSS style for the div + */ + constructor(options) + { + options = options || {} + options.side = options.side || 'rightbottom' + options.side.toLowerCase() + options.padding = options.padding || '7px' + options.color = options.color || 'white' + options.background = options.background || 'rgba(0,0,0,0.5)' + this.div = document.createElement('div') + Counter.findParent(options.side).appendChild(this.div) + for (let style in options) + { + if (style !== 'parent' && style !== 'side') + { + this.div.style[style] = options[style] + } + } } - while (n >= overflow) { // To avoid rounding up, before adding - n /= 2; // last byte, shift everything - d /= 2; // right using integer math until - x >>>= 1; // we have exactly the desired bits. + + /** + * find the parent div for one of the corners + * @param {string} [options.side] side to place the panel (combination of right/left and bottom/top) + * @return {HTMLElement} + */ + static findParent(side) + { + const styles = [] + let name = 'yy-counter-' + if (side.indexOf('left') !== -1) + { + name += 'left-' + styles['left'] = 0 + } + else + { + name += 'right-' + styles['right'] = 0 + } + if (side.indexOf('top') !== -1) + { + name += 'top' + styles['top'] = 0 + } + else + { + name += 'bottom' + styles['bottom'] = 0 + } + const test = document.getElementById(name) + if (test) + { + return test + } + const container = document.createElement('div') + container.id = name + container.style.overflow = 'hidden' + container.style.position = 'fixed' + container.style.zIndex = 10000 + container.style.pointerEvents = 'none' + container.style.userSelect = 'none' + for (let style in styles) + { + container.style[style] = styles[style] + } + document.body.appendChild(container) + return container } - return (n + x) / d; // Form the number within [0, 1). - }; - - prng.int32 = function() { return arc4.g(4) | 0; } - prng.quick = function() { return arc4.g(4) / 0x100000000; } - prng.double = prng; - - // Mix the randomness into accumulated entropy. - mixkey(tostring(arc4.S), pool); - // Calling convention: what to return as a function of prng, seed, is_math. - return (options.pass || callback || - function(prng, seed, is_math_call, state) { - if (state) { - // Load the arc4 state from the given state if it has an S array. - if (state.S) { copy(state, arc4); } - // Only provide the .state method if requested via options.state. - prng.state = function() { return copy(arc4, {}); } + /** + * replaces the innerHTML of the console + * @param {string|number} text1 + * @param {string|number} [text2] + * @param {string|number} [...textn] any number of arguments + */ + log() + { + let s = '' + for (let arg of arguments) + { + s += '
' + arg + '
' } + this.div.innerHTML = s + } - // If called as a method of Math (Math.seedrandom()), mutate - // Math.random because that is how seedrandom.js has worked since v1.0. - if (is_math_call) { math[rngname] = prng; return seed; } - - // Otherwise, it is a newer calling convention, so return the - // prng directly. - else return prng; - })( - prng, - shortseed, - 'global' in options ? options.global : (this == math), - options.state); + /** + * appends to the innerHTML of the console + * @param {string|number} text1 + * @param {string|number} [text2] + * @param {string|number} [...textn] any number of arguments + */ + append() + { + let s = this.div.innerHTML + for (let arg of arguments) + { + s += '
' + arg + '
' + } + this.div.innerHTML = s + } } +},{}],61:[function(require,module,exports){ +'use strict'; -// -// ARC4 -// -// An ARC4 implementation. The constructor takes a key in the form of -// an array of at most (width) integers that should be 0 <= x < (width). -// -// The g(count) method returns a pseudorandom integer that concatenates -// the next (count) outputs from ARC4. Its return value is a number x -// that is in the range 0 <= x < (width ^ count). -// -function ARC4(key) { - var t, keylen = key.length, - me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - // The empty key [] is treated as [0]. - if (!keylen) { key = [keylen++]; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - // Set up S using the standard key scheduling algorithm. - while (i < width) { - s[i] = i++; - } - for (i = 0; i < width; i++) { - s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))]; - s[j] = t; - } +var Color = require('tinycolor2'); +var Counter = require('yy-counter'); - // The "g" method returns the next (count) outputs as one number. - (me.g = function(count) { - // Using instance members instead of closure state nearly doubles speed. - var t, r = 0, - i = me.i, j = me.j, s = me.S; - while (count--) { - t = s[i = mask & (i + 1)]; - r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))]; - } - me.i = i; me.j = j; - return r; - // For robust unpredictability, the function call below automatically - // discards an initial batch of values. This is called RC4-drop[256]. - // See http://google.com/search?q=rsa+fluhrer+response&btnI - })(width); -} +var STYLES = { + 'background': 'rgba(0, 0, 0, 0.5)', + 'color': 'white' +}; -// -// copy() -// Copies internal state of ARC4 to or from a plain object. -// -function copy(f, t) { - t.i = f.i; - t.j = f.j; - t.S = f.S.slice(); - return t; +var STYLES_FPS = { + 'padding': '0.1em 0.5em' }; -// -// flatten() -// Converts an object tree to nested arrays of strings. -// -function flatten(obj, depth) { - var result = [], typ = (typeof obj), prop; - if (depth && typ == 'object') { - for (prop in obj) { - try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} - } - } - return (result.length ? result : typ == 'string' ? obj : obj + '\0'); -} +var STYLES_METER = {}; -// -// mixkey() -// Mixes a string seed into a key that is an array of integers, and -// returns a shortened string seed that is equivalent to the result key. -// -function mixkey(seed, key) { - var stringseed = seed + '', smear, j = 0; - while (j < stringseed.length) { - key[mask & j] = - mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++)); - } - return tostring(key); -} +module.exports = function () { + /** + * @param {object} [options] + * @param {boolean} [options.meter=true] include a meter with the FPS + * @param {string} [options.side=bottom-right] include any combination of left/right and top/bottom + * @param {number} [options.FPS=60] desired FPS + * @param {number} [options.tolerance=1] minimum tolerance for fluctuations in FPS number + * @param {number} [options.meterWidth=100] width of meter div + * @param {number} [options.meterHeight=25] height of meter div + * @param {number} [options.meterLineHeight=4] height of meter line + * @param {styles[]} [options.styles] CSS styles to apply to the div (in javascript format) + * @param {styles[]} [options.stylesFPS] CSS styles to apply to the FPS text (in javascript format) + * @param {styles[]} [options.stylesMeter] CSS styles to apply to the FPS meter (in javascript format) + * @param {string} [options.text=" FPS"] change the text to the right of the FPS + */ + function FPS(options) { + _classCallCheck(this, FPS); -// -// autoseed() -// Returns an object for autoseeding, using window.crypto and Node crypto -// module if available. -// -function autoseed() { - try { - var out; - if (nodecrypto && (out = nodecrypto.randomBytes)) { - // The use of 'out' to remember randomBytes makes tight minified code. - out = out(width); - } else { - out = new Uint8Array(width); - (global.crypto || global.msCrypto).getRandomValues(out); + this.options = options || {}; + this.tolerance = this.options.tolerance || 1; + this.FPS = this.options.FPS || 60; + this.meterWidth = this.options.meterWidth || 100; + this.meterHeight = this.options.meterHeight || 25; + this.meterLineHeight = this.options.meterLineHeight || 4; + this.div = document.createElement('div'); + Counter.findParent(this.options.side || 'bottom-right').appendChild(this.div); + this.style(this.div, STYLES, this.options.styles); + this.divFPS(); + this.meter = typeof this.options.meter === 'undefined' || this.options.meter; + this.lastTime = 0; + this.frameNumber = 0; + this.lastUpdate = 0; + this.lastFPS = '--'; } - return tostring(out); - } catch (e) { - var browser = global.navigator, - plugins = browser && browser.plugins; - return [+new Date, global, plugins, global.screen, tostring(pool)]; - } -} - -// -// tostring() -// Converts an array of charcodes to a string -// -function tostring(a) { - return String.fromCharCode.apply(0, a); -} - -// -// When seedrandom.js is loaded, we immediately mix a few bits -// from the built-in RNG into the entropy pool. Because we do -// not want to interfere with deterministic PRNG state later, -// seedrandom will not call math.random on its own again after -// initialization. -// -mixkey(math.random(), pool); -// -// Nodejs and AMD support: export the implementation as a module using -// either convention. -// -if ((typeof module) == 'object' && module.exports) { - module.exports = seedrandom; - // When in node.js, try using crypto package for autoseeding. - try { - nodecrypto = require('crypto'); - } catch (ex) {} -} else if ((typeof define) == 'function' && define.amd) { - define(function() { return seedrandom; }); -} else { - // When included as a plain script, set up Math.seedrandom global. - math['seed' + rngname] = seedrandom; -} + /** + * change desired FPS + * @type {number} + */ -// End anonymous scope, and pass initial values. -})( - // global: `self` in browsers (including strict mode and web workers), - // otherwise `this` in Node and other environments - (typeof self !== 'undefined') ? self : this, - [], // pool: entropy pool starts empty - Math // math: package containing random, pow, and seedrandom -); + _createClass(FPS, [{ + key: 'remove', -},{"crypto":1}],67:[function(require,module,exports){ -// TinyColor v1.4.1 -// https://github.com/bgrins/TinyColor -// Brian Grinstead, MIT License -(function(Math) { + /** + * remove meter from DOM + */ + value: function remove() { + this.div.remove(); + } -var trimLeft = /^\s+/, - trimRight = /\s+$/, - tinyCounter = 0, - mathRound = Math.round, - mathMin = Math.min, - mathMax = Math.max, - mathRandom = Math.random; + /** + * @type {boolean} meter (the FPS graph) is on or off + */ -function tinycolor (color, opts) { + }, { + key: 'style', + value: function style(div, style1, style2) { + for (var style in style1) { + div.style[style] = style1[style]; + } + if (style2) { + for (var _style in style2) { + div.style[_style] = style2[_style]; + } + } + } - color = (color) ? color : ''; - opts = opts || { }; + /** + * create div for text FPS + * @private + * @param {HTMLElement} div + * @param {object} options (see contructor) + */ - // If input is already a tinycolor, return itself - if (color instanceof tinycolor) { - return color; - } - // If we are called as a function, call using new instead - if (!(this instanceof tinycolor)) { - return new tinycolor(color, opts); - } + }, { + key: 'divFPS', + value: function divFPS() { + var div = this.div; + var options = this.options; + var divFPS = document.createElement('div'); + div.appendChild(divFPS); + this.fpsSpan = document.createElement('span'); + divFPS.appendChild(this.fpsSpan); + var span = document.createElement('span'); + divFPS.appendChild(span); + span.innerText = typeof options.text !== 'undefined' ? options.text : ' FPS'; + this.style(div, STYLES_FPS, options.stylesFPS); + } - var rgb = inputToRGB(color); - this._originalInput = color, - this._r = rgb.r, - this._g = rgb.g, - this._b = rgb.b, - this._a = rgb.a, - this._roundA = mathRound(100*this._a) / 100, - this._format = opts.format || rgb.format; - this._gradientType = opts.gradientType; + /** + * create div for FPS meter + * @private + * @param {HTMLElement} div + * @param {object} options (see contructor) + */ - // Don't let the range of [0,255] come back in [0,1]. - // Potentially lose a little bit of precision here, but will fix issues where - // .5 gets interpreted as half of the total, instead of half of 1 - // If it was supposed to be 128, this was already taken care of by `inputToRgb` - if (this._r < 1) { this._r = mathRound(this._r); } - if (this._g < 1) { this._g = mathRound(this._g); } - if (this._b < 1) { this._b = mathRound(this._b); } + }, { + key: 'divMeter', + value: function divMeter() { + var div = this.div; + var options = this.options; + if (!this.meterCanvas) { + this.meterCanvas = document.createElement('canvas'); + div.appendChild(this.meterCanvas); + this.meterCanvas.width = this.meterWidth; + this.meterCanvas.height = this.meterHeight; + this.meterCanvas.style.width = div.width + 'px'; + this.meterCanvas.style.height = div.height + 'px'; + this.style(this.meterCanvas, STYLES_METER, options.stylesMeter); + } else { + this.meterCanvas.style.display = 'block'; + } + } - this._ok = rgb.ok; - this._tc_id = tinyCounter++; -} + /** + * call this at the start of the frame to calculate FPS + */ -tinycolor.prototype = { - isDark: function() { - return this.getBrightness() < 128; - }, - isLight: function() { - return !this.isDark(); - }, - isValid: function() { - return this._ok; - }, - getOriginalInput: function() { - return this._originalInput; - }, - getFormat: function() { - return this._format; - }, - getAlpha: function() { - return this._a; - }, - getBrightness: function() { - //http://www.w3.org/TR/AERT#color-contrast - var rgb = this.toRgb(); - return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; - }, - getLuminance: function() { - //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef - var rgb = this.toRgb(); - var RsRGB, GsRGB, BsRGB, R, G, B; - RsRGB = rgb.r/255; - GsRGB = rgb.g/255; - BsRGB = rgb.b/255; + }, { + key: 'frame', + value: function frame() { + this.frameNumber++; + var currentTime = performance.now() - this.lastTime; - if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);} - if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);} - if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);} - return (0.2126 * R) + (0.7152 * G) + (0.0722 * B); - }, - setAlpha: function(value) { - this._a = boundAlpha(value); - this._roundA = mathRound(100*this._a) / 100; - return this; - }, - toHsv: function() { - var hsv = rgbToHsv(this._r, this._g, this._b); - return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; - }, - toHsvString: function() { - var hsv = rgbToHsv(this._r, this._g, this._b); - var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); - return (this._a == 1) ? - "hsv(" + h + ", " + s + "%, " + v + "%)" : - "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")"; - }, - toHsl: function() { - var hsl = rgbToHsl(this._r, this._g, this._b); - return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; - }, - toHslString: function() { - var hsl = rgbToHsl(this._r, this._g, this._b); - var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); - return (this._a == 1) ? - "hsl(" + h + ", " + s + "%, " + l + "%)" : - "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")"; - }, - toHex: function(allow3Char) { - return rgbToHex(this._r, this._g, this._b, allow3Char); - }, - toHexString: function(allow3Char) { - return '#' + this.toHex(allow3Char); - }, - toHex8: function(allow4Char) { - return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); - }, - toHex8String: function(allow4Char) { - return '#' + this.toHex8(allow4Char); - }, - toRgb: function() { - return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a }; - }, - toRgbString: function() { - return (this._a == 1) ? - "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" : - "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")"; - }, - toPercentageRgb: function() { - return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a }; - }, - toPercentageRgbString: function() { - return (this._a == 1) ? - "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" : - "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; - }, - toName: function() { - if (this._a === 0) { - return "transparent"; + // skip large differences to remove garbage + if (currentTime > 500) { + if (this.lastTime !== 0) { + this.lastFPS = Math.floor(this.frameNumber / (currentTime / 1000)); + if (this.lastFPS >= this.FPS - this.tolerance && this.lastFPS <= this.FPS + this.tolerance) { + this.lastFPS = this.FPS; + } + } + this.lastTime = performance.now(); + this.frameNumber = 0; + } + this.fpsSpan.innerText = this.lastFPS; + if (this.meterCanvas && this.lastFPS !== '--') { + this.meterUpdate(this.lastFPS / this.FPS); + } + } + }, { + key: 'meterUpdate', + value: function meterUpdate(percent) { + var c = this.meterCanvas.getContext('2d'); + var data = c.getImageData(0, 0, this.meterCanvas.width, this.meterCanvas.height); + c.putImageData(data, -1, 0); + c.clearRect(this.meterCanvas.width - 1, 0, 1, this.meterCanvas.height); + if (percent < 0.5) { + c.fillStyle = Color.mix('#ff0000', '0xffa500', percent * 200).toHexString(); + } else { + c.fillStyle = Color.mix('#ffa500', '#00ff00', (percent - 0.5) * 200).toHexString(); + } + var height = (this.meterCanvas.height - this.meterLineHeight) * (1 - percent); + c.fillRect(this.meterCanvas.width - 1, height, 1, this.meterLineHeight); } - - if (this._a < 1) { - return false; + }, { + key: 'side', + value: function side(options) { + if (options.side) { + options.side = options.side.toLowerCase(); + if (options.side.indexOf('left') !== -1) { + STYLES['left'] = 0; + delete STYLES['right']; + } else { + STYLES['right'] = 0; + delete STYLES['left']; + } + if (options.side.indexOf('top') !== -1) { + STYLES['top'] = 0; + delete STYLES['bottom']; + } else { + STYLES['bottom'] = 0; + delete STYLES['top']; + } + } else { + STYLES['right'] = 0; + STYLES['bottom'] = 0; + } + } + }, { + key: 'fps', + get: function get() { + return this.FPS; + }, + set: function set(value) { + this.FPS = value; + } + }, { + key: 'meter', + get: function get() { + return this._meter; + }, + set: function set(value) { + if (value) { + this.divMeter(); + } else if (this.meterCanvas) { + this.meterCanvas.style.display = 'none'; + } } + }]); - return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; - }, - toFilter: function(secondColor) { - var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a); - var secondHex8String = hex8String; - var gradientType = this._gradientType ? "GradientType = 1, " : ""; + return FPS; +}(); - if (secondColor) { - var s = tinycolor(secondColor); - secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a); - } +},{"tinycolor2":59,"yy-counter":60}],62:[function(require,module,exports){ +'use strict'; - return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")"; - }, - toString: function(format) { - var formatSet = !!format; - format = format || this._format; +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - var formattedString = false; - var hasAlpha = this._a < 1 && this._a >= 0; - var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - if (needsAlphaFormat) { - // Special case for "transparent", all other non-alpha formats - // will return rgba when there is transparency. - if (format === "name" && this._a === 0) { - return this.toName(); - } - return this.toRgbString(); - } - if (format === "rgb") { - formattedString = this.toRgbString(); - } - if (format === "prgb") { - formattedString = this.toPercentageRgbString(); - } - if (format === "hex" || format === "hex6") { - formattedString = this.toHexString(); - } - if (format === "hex3") { - formattedString = this.toHexString(true); - } - if (format === "hex4") { - formattedString = this.toHex8String(true); - } - if (format === "hex8") { - formattedString = this.toHex8String(); - } - if (format === "name") { - formattedString = this.toName(); - } - if (format === "hsl") { - formattedString = this.toHslString(); - } - if (format === "hsv") { - formattedString = this.toHsvString(); - } +// yy-random +// by David Figatner +// MIT license +// copyright YOPEY YOPEY LLC 2016-17 +// https://github.com/davidfig/random - return formattedString || this.toHexString(); - }, - clone: function() { - return tinycolor(this.toString()); - }, +var seedrandom = require('seedrandom'); - _applyModification: function(fn, args) { - var color = fn.apply(null, [this].concat([].slice.call(args))); - this._r = color._r; - this._g = color._g; - this._b = color._b; - this.setAlpha(color._a); - return this; - }, - lighten: function() { - return this._applyModification(lighten, arguments); - }, - brighten: function() { - return this._applyModification(brighten, arguments); - }, - darken: function() { - return this._applyModification(darken, arguments); - }, - desaturate: function() { - return this._applyModification(desaturate, arguments); - }, - saturate: function() { - return this._applyModification(saturate, arguments); - }, - greyscale: function() { - return this._applyModification(greyscale, arguments); - }, - spin: function() { - return this._applyModification(spin, arguments); - }, +var Random = function () { + function Random() { + _classCallCheck(this, Random); - _applyCombination: function(fn, args) { - return fn.apply(null, [this].concat([].slice.call(args))); - }, - analogous: function() { - return this._applyCombination(analogous, arguments); - }, - complement: function() { - return this._applyCombination(complement, arguments); - }, - monochromatic: function() { - return this._applyCombination(monochromatic, arguments); - }, - splitcomplement: function() { - return this._applyCombination(splitcomplement, arguments); - }, - triad: function() { - return this._applyCombination(triad, arguments); - }, - tetrad: function() { - return this._applyCombination(tetrad, arguments); + this.generator = Math.random; } -}; -// If input is an object, force 1 into "1.0" to handle ratios properly -// String input requires "1.0" as input, so 1 will be treated as 1 -tinycolor.fromRatio = function(color, opts) { - if (typeof color == "object") { - var newColor = {}; - for (var i in color) { - if (color.hasOwnProperty(i)) { - if (i === "a") { - newColor[i] = color[i]; - } - else { - newColor[i] = convertToPercentage(color[i]); - } - } - } - color = newColor; - } + /** + * generates a seeded number + * @param {number} seed + * @param {object} [options] + * @param {string} [PRNG="alea"] - name of algorithm, see https://github.com/davidbau/seedrandom + * @param {(boolean|string)} [state] - can include the state returned from save() + */ - return tinycolor(color, opts); -}; -// Given a string or object, convert that input to RGB -// Possible string inputs: -// -// "red" -// "#f00" or "f00" -// "#ff0000" or "ff0000" -// "#ff000000" or "ff000000" -// "rgb 255 0 0" or "rgb (255, 0, 0)" -// "rgb 1.0 0 0" or "rgb (1, 0, 0)" -// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" -// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" -// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" -// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" -// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" -// -function inputToRGB(color) { + _createClass(Random, [{ + key: 'seed', + value: function seed(_seed, options) { + options = options || {}; + this.generator = seedrandom[options.PRNG || 'alea'](_seed, { state: options.state }); + this.options = options; + } - var rgb = { r: 0, g: 0, b: 0 }; - var a = 1; - var s = null; - var v = null; - var l = null; - var ok = false; - var format = false; + /** + * saves the state of the random generator + * can only be used after Random.seed() is called with options.state = true + * @returns {number} state + */ - if (typeof color == "string") { - color = stringInputToObject(color); - } + }, { + key: 'save', + value: function save() { + if (this.generator !== Math.random) { + return this.generator.state(); + } + } - if (typeof color == "object") { - if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { - rgb = rgbToRgb(color.r, color.g, color.b); - ok = true; - format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + /** + * restores the state of the random generator + * @param {number} state + */ + + }, { + key: 'restore', + value: function restore(state) { + this.generator = seedrandom[this.options.PRNG || 'alea']('', { state: state }); } - else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { - s = convertToPercentage(color.s); - v = convertToPercentage(color.v); - rgb = hsvToRgb(color.h, s, v); - ok = true; - format = "hsv"; + + /** + * changes the generator to use the old Math.sin-based random function + * based on : http://stackoverflow.com/questions/521295/javascript-random-seeds + * (deprecated) Use only for compatibility purposes + * @param {number} seed + */ + + }, { + key: 'seedOld', + value: function seedOld(seed) { + this.generator = function () { + var x = Math.sin(seed++) * 10000; + return x - Math.floor(x); + }; } - else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { - s = convertToPercentage(color.s); - l = convertToPercentage(color.l); - rgb = hslToRgb(color.h, s, l); - ok = true; - format = "hsl"; + + /** + * create a separate random generator using the seed + * @param {number} seed + * @return {object} + */ + + }, { + key: 'separateSeed', + value: function separateSeed(seed) { + var random = new Random(); + random.seed(seed); + return random; } - if (color.hasOwnProperty("a")) { - a = color.a; + /** + * resets the random number this.generator to Math.random() + */ + + }, { + key: 'reset', + value: function reset() { + this.generator = Math.random; } - } - a = boundAlpha(a); + /** + * returns a random number using the this.generator between [0, ceiling - 1] + * @param {number} ceiling + * @param {boolean} [useFloat=false] + * @return {number} + */ - return { - ok: ok, - format: color.format || format, - r: mathMin(255, mathMax(rgb.r, 0)), - g: mathMin(255, mathMax(rgb.g, 0)), - b: mathMin(255, mathMax(rgb.b, 0)), - a: a - }; -} + }, { + key: 'get', + value: function get(ceiling, useFloat) { + var negative = ceiling < 0 ? -1 : 1; + ceiling *= negative; + var result = void 0; + if (useFloat) { + result = this.generator() * ceiling; + } else { + result = Math.floor(this.generator() * ceiling); + } + return result * negative; + } + /** + * returns a random integer between 0 - Number.MAX_SAFE_INTEGER + * @return {number} + */ -// Conversion Functions -// -------------------- + }, { + key: 'getHuge', + value: function getHuge() { + return this.get(Number.MAX_SAFE_INTEGER); + } -// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: -// + /** + * random number [middle - range, middle + range] + * @param {number} middle + * @param {number} delta + * @param {boolean} [useFloat=false] + * @return {number} + */ -// `rgbToRgb` -// Handle bounds / percentage checking to conform to CSS color spec -// -// *Assumes:* r, g, b in [0, 255] or [0, 1] -// *Returns:* { r, g, b } in [0, 255] -function rgbToRgb(r, g, b){ - return { - r: bound01(r, 255) * 255, - g: bound01(g, 255) * 255, - b: bound01(b, 255) * 255 - }; -} + }, { + key: 'middle', + value: function middle(_middle, delta, useFloat) { + var half = delta / 2; + return this.range(_middle - half, _middle + half, useFloat); + } -// `rgbToHsl` -// Converts an RGB color value to HSL. -// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] -// *Returns:* { h, s, l } in [0,1] -function rgbToHsl(r, g, b) { + /** + * random number [start, end] + * @param {number} start + * @param {number} end + * @param {boolean} [useFloat=false] if true, then range is (start, end)--i.e., not inclusive to start and end + * @return {number} + */ - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); + }, { + key: 'range', + value: function range(start, end, useFloat) { + // case where there is no range + if (end === start) { + return end; + } - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, l = (max + min) / 2; + if (useFloat) { + return this.get(end - start, true) + start; + } else { + var range = void 0; + if (start < 0 && end > 0) { + range = -start + end + 1; + } else if (start === 0 && end > 0) { + range = end + 1; + } else if (start < 0 && end === 0) { + range = start - 1; + start = 1; + } else if (start < 0 && end < 0) { + range = end - start - 1; + } else { + range = end - start + 1; + } + return Math.floor(this.generator() * range) + start; + } + } - if(max == min) { - h = s = 0; // achromatic - } - else { - var d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; + /** + * an array of random numbers between [start, end] + * @param {number} start + * @param {number} end + * @param {number} count + * @param {boolean} [useFloat=false] + * @return {number[]} + */ + + }, { + key: 'rangeMultiple', + value: function rangeMultiple(start, end, count, useFloat) { + var array = []; + for (var i = 0; i < count; i++) { + array.push(this.range(start, end, useFloat)); + } + return array; } - h /= 6; - } + /** + * an array of random numbers between [middle - range, middle + range] + * @param {number} middle + * @param {number} range + * @param {number} count + * @param {boolean} [useFloat=false] + * @return {number[]} + */ - return { h: h, s: s, l: l }; -} + }, { + key: 'middleMultiple', + value: function middleMultiple(middle, range, count, useFloat) { + var array = []; + for (var i = 0; i < count; i++) { + array.push(middle(middle, range, useFloat)); + } + return array; + } -// `hslToRgb` -// Converts an HSL color value to RGB. -// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] -// *Returns:* { r, g, b } in the set [0, 255] -function hslToRgb(h, s, l) { - var r, g, b; + /** + * @param {number} [chance=0.5] + * returns random sign (either +1 or -1) + * @return {number} + */ - h = bound01(h, 360); - s = bound01(s, 100); - l = bound01(l, 100); + }, { + key: 'sign', + value: function sign(chance) { + chance = chance || 0.5; + return this.generator() < chance ? 1 : -1; + } - function hue2rgb(p, q, t) { - if(t < 0) t += 1; - if(t > 1) t -= 1; - if(t < 1/6) return p + (q - p) * 6 * t; - if(t < 1/2) return q; - if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; - return p; - } + /** + * tells you whether a random chance was achieved + * @param {number} [percent=0.5] + * @return {boolean} + */ - if(s === 0) { - r = g = b = l; // achromatic - } - else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hue2rgb(p, q, h + 1/3); - g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1/3); - } + }, { + key: 'chance', + value: function chance(percent) { + return this.generator() < (percent || 0.5); + } - return { r: r * 255, g: g * 255, b: b * 255 }; -} + /** + * returns a random angle in radians [0 - 2 * Math.PI) + */ -// `rgbToHsv` -// Converts an RGB color value to HSV -// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] -// *Returns:* { h, s, v } in [0,1] -function rgbToHsv(r, g, b) { + }, { + key: 'angle', + value: function angle() { + return this.get(Math.PI * 2, true); + } - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); + /** + * Shuffle array (either in place or copied) + * from http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array + * @param {Array} array + * @param {boolean} [copy=false] whether to shuffle in place (default) or return a new shuffled array + * @return {Array} a shuffled array + */ - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, v = max; + }, { + key: 'shuffle', + value: function shuffle(array, copy) { + if (copy) { + array = array.slice(); + } + if (array.length === 0) { + return array; + } - var d = max - min; - s = max === 0 ? 0 : d / max; + var currentIndex = array.length, + temporaryValue = void 0, + randomIndex = void 0; - if(max == min) { - h = 0; // achromatic - } - else { - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; - } - h /= 6; - } - return { h: h, s: s, v: v }; -} + // While there remain elements to shuffle... + while (0 !== currentIndex) { + // Pick a remaining element... + randomIndex = this.get(currentIndex); + currentIndex -= 1; -// `hsvToRgb` -// Converts an HSV color value to RGB. -// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] -// *Returns:* { r, g, b } in the set [0, 255] - function hsvToRgb(h, s, v) { + // And swap it with the current element. + temporaryValue = array[currentIndex]; + array[currentIndex] = array[randomIndex]; + array[randomIndex] = temporaryValue; + } + return array; + } - h = bound01(h, 360) * 6; - s = bound01(s, 100); - v = bound01(v, 100); + /** + * picks a random element from an array + * @param {Array} array + * @return {*} + */ - var i = Math.floor(h), - f = h - i, - p = v * (1 - s), - q = v * (1 - f * s), - t = v * (1 - (1 - f) * s), - mod = i % 6, - r = [v, q, p, p, t, v][mod], - g = [t, v, v, q, p, p][mod], - b = [p, p, t, v, v, q][mod]; + }, { + key: 'pick', + value: function pick(array, remove) { + if (!remove) { + return array[this.get(array.length)]; + } else { + var pick = this.get(array.length); + var temp = array[pick]; + array.splice(pick, 1); + return temp; + } + } - return { r: r * 255, g: g * 255, b: b * 255 }; -} + /** + * returns a random property from an object + * from http://stackoverflow.com/questions/2532218/pick-random-property-from-a-javascript-object + * @param {object} obj + * @return {*} + */ -// `rgbToHex` -// Converts an RGB color to hex -// Assumes r, g, and b are contained in the set [0, 255] -// Returns a 3 or 6 character hex -function rgbToHex(r, g, b, allow3Char) { + }, { + key: 'property', + value: function property(obj) { + var result; + var count = 0; + for (var prop in obj) { + if (this.chance(1 / ++count)) { + result = prop; + } + } + return result; + } - var hex = [ - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; + /** + * creates a random set where each entry is a value between [min, max] + * @param {number} min + * @param {number} max + * @param {number} amount of numbers in set + * @param {number[]} + */ - // Return a 3 character hex if possible - if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { - return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); - } + }, { + key: 'set', + value: function set(min, max, amount) { + var set = [], + all = [], + i; + for (i = min; i < max; i++) { + all.push(i); + } - return hex.join(""); -} + for (i = 0; i < amount; i++) { + var found = this.get(all.length); + set.push(all[found]); + all.splice(found, 1); + } + return set; + } -// `rgbaToHex` -// Converts an RGBA color plus alpha transparency to hex -// Assumes r, g, b are contained in the set [0, 255] and -// a in [0, 1]. Returns a 4 or 8 character rgba hex -function rgbaToHex(r, g, b, a, allow4Char) { + /** + * returns a set of numbers with a randomly even distribution (i.e., no overlapping and filling the space) + * @param {number} start position + * @param {number} end position + * @param {number} count of non-start/end points + * @param {boolean} [includeStart=false] includes start point (count++) + * @param {boolean} [includeEnd=false] includes end point (count++) + * @param {boolean} [useFloat=false] + * @param {number[]} + */ - var hex = [ - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)), - pad2(convertDecimalToHex(a)) - ]; + }, { + key: 'distribution', + value: function distribution(start, end, count, includeStart, includeEnd, useFloat) { + var interval = Math.floor((end - start) / count); + var halfInterval = interval / 2; + var quarterInterval = interval / 4; + var set = []; + if (includeStart) { + set.push(start); + } + for (var i = 0; i < count; i++) { + set.push(start + i * interval + halfInterval + this.range(-quarterInterval, quarterInterval, useFloat)); + } + if (includeEnd) { + set.push(end); + } + return set; + } - // Return a 4 character hex if possible - if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { - return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); - } + /** + * returns a random number based on weighted probability between [min, max] + * from http://stackoverflow.com/questions/22656126/javascript-random-number-with-weighted-probability + * @param {number} min value + * @param {number} max value + * @param {number} target for average value + * @param {number} stddev - standard deviation + */ - return hex.join(""); -} + }, { + key: 'weightedProbabilityInt', + value: function weightedProbabilityInt(min, max, target, stddev) { + function normRand() { + var x1 = void 0, + x2 = void 0, + rad = void 0; + do { + x1 = 2 * this.get(1, true) - 1; + x2 = 2 * this.get(1, true) - 1; + rad = x1 * x1 + x2 * x2; + } while (rad >= 1 || rad === 0); + var c = Math.sqrt(-2 * Math.log(rad) / rad); + return x1 * c; + } -// `rgbaToArgbHex` -// Converts an RGBA color to an ARGB Hex8 string -// Rarely used, but required for "toFilter()" -function rgbaToArgbHex(r, g, b, a) { + stddev = stddev || 1; + if (Math.random() < 0.81546) { + while (true) { + var sample = normRand() * stddev + target; + if (sample >= min && sample <= max) { + return sample; + } + } + } else { + return this.range(min, max); + } + } - var hex = [ - pad2(convertDecimalToHex(a)), - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; + /* + * returns a random hex color (0 - 0xffffff) + * @return {number} + */ - return hex.join(""); -} + }, { + key: 'color', + value: function color() { + return this.get(0xffffff); + } + }]); -// `equals` -// Can be called with any tinycolor input -tinycolor.equals = function (color1, color2) { - if (!color1 || !color2) { return false; } - return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); -}; + return Random; +}(); -tinycolor.random = function() { - return tinycolor.fromRatio({ - r: mathRandom(), - g: mathRandom(), - b: mathRandom() - }); -}; +module.exports = new Random(); +},{"seedrandom":51}],63:[function(require,module,exports){ -// Modification Functions -// ---------------------- -// Thanks to less.js for some of the basics here -// +},{}],64:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; -function desaturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s -= amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); -} +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. -function saturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s += amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); -} +var cachedSetTimeout; +var cachedClearTimeout; -function greyscale(color) { - return tinycolor(color).desaturate(100); +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); } - -function lighten (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l += amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); } +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } -function brighten(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var rgb = tinycolor(color).toRgb(); - rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); - rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); - rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); - return tinycolor(rgb); -} -function darken (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l -= amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); } +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } -// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. -// Values outside of this range will be wrapped into this range. -function spin(color, amount) { - var hsl = tinycolor(color).toHsl(); - var hue = (hsl.h + amount) % 360; - hsl.h = hue < 0 ? 360 + hue : hue; - return tinycolor(hsl); -} -// Combination Functions -// --------------------- -// Thanks to jQuery xColor for some of the ideas behind these -// -function complement(color) { - var hsl = tinycolor(color).toHsl(); - hsl.h = (hsl.h + 180) % 360; - return tinycolor(hsl); } +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; -function triad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) - ]; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } } -function tetrad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) - ]; +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); } -function splitcomplement(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), - tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) - ]; +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; } +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; -function analogous(color, results, slices) { - results = results || 6; - slices = slices || 30; +function noop() {} - var hsl = tinycolor(color).toHsl(); - var part = 360 / slices; - var ret = [tinycolor(color)]; +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; - for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { - hsl.h = (hsl.h + part) % 360; - ret.push(tinycolor(hsl)); - } - return ret; -} +process.listeners = function (name) { return [] } -function monochromatic(color, results) { - results = results || 6; - var hsv = tinycolor(color).toHsv(); - var h = hsv.h, s = hsv.s, v = hsv.v; - var ret = []; - var modification = 1 / results; +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; - while (results--) { - ret.push(tinycolor({ h: h, s: s, v: v})); - v = (v + modification) % 1; - } +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; - return ret; -} +},{}],65:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { -// Utility Functions -// --------------------- + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } -tinycolor.mix = function(color1, color2, amount) { - amount = (amount === 0) ? 0 : (amount || 50); + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, - var rgb1 = tinycolor(color1).toRgb(); - var rgb2 = tinycolor(color2).toRgb(); + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - var p = amount / 100; + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' - var rgba = { - r: ((rgb2.r - rgb1.r) * p) + rgb1.r, - g: ((rgb2.g - rgb1.g) * p) + rgb1.g, - b: ((rgb2.b - rgb1.b) * p) + rgb1.b, - a: ((rgb2.a - rgb1.a) * p) + rgb1.a - }; + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - return tinycolor(rgba); -}; + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, -// Readability Functions -// --------------------- -// false -// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false -tinycolor.isReadable = function(color1, color2, wcag2) { - var readability = tinycolor.readability(color1, color2); - var wcag2Parms, out; + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } - out = false; + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } - wcag2Parms = validateWCAG2Parms(wcag2); - switch (wcag2Parms.level + wcag2Parms.size) { - case "AAsmall": - case "AAAlarge": - out = readability >= 4.5; - break; - case "AAlarge": - out = readability >= 3; - break; - case "AAAsmall": - out = readability >= 7; - break; - } - return out; + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } -}; + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } -// `mostReadable` -// Given a base color and a list of possible foreground or background -// colors for that base, returns the most readable color. -// Optionally returns Black or White if the most readable color is unreadable. -// *Example* -// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" -// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" -// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" -// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" -tinycolor.mostReadable = function(baseColor, colorList, args) { - var bestColor = null; - var bestScore = 0; - var readability; - var includeFallbackColors, level, size ; - args = args || {}; - includeFallbackColors = args.includeFallbackColors ; - level = args.level; - size = args.size; + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } - for (var i= 0; i < colorList.length ; i++) { - readability = tinycolor.readability(baseColor, colorList[i]); - if (readability > bestScore) { - bestScore = readability; - bestColor = tinycolor(colorList[i]); - } - } + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } - if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { - return bestColor; - } - else { - args.includeFallbackColors=false; - return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); - } -}; + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; -// Big List of Colors -// ------------------ -// -var names = tinycolor.names = { - aliceblue: "f0f8ff", - antiquewhite: "faebd7", - aqua: "0ff", - aquamarine: "7fffd4", - azure: "f0ffff", - beige: "f5f5dc", - bisque: "ffe4c4", - black: "000", - blanchedalmond: "ffebcd", - blue: "00f", - blueviolet: "8a2be2", - brown: "a52a2a", - burlywood: "deb887", - burntsienna: "ea7e5d", - cadetblue: "5f9ea0", - chartreuse: "7fff00", - chocolate: "d2691e", - coral: "ff7f50", - cornflowerblue: "6495ed", - cornsilk: "fff8dc", - crimson: "dc143c", - cyan: "0ff", - darkblue: "00008b", - darkcyan: "008b8b", - darkgoldenrod: "b8860b", - darkgray: "a9a9a9", - darkgreen: "006400", - darkgrey: "a9a9a9", - darkkhaki: "bdb76b", - darkmagenta: "8b008b", - darkolivegreen: "556b2f", - darkorange: "ff8c00", - darkorchid: "9932cc", - darkred: "8b0000", - darksalmon: "e9967a", - darkseagreen: "8fbc8f", - darkslateblue: "483d8b", - darkslategray: "2f4f4f", - darkslategrey: "2f4f4f", - darkturquoise: "00ced1", - darkviolet: "9400d3", - deeppink: "ff1493", - deepskyblue: "00bfff", - dimgray: "696969", - dimgrey: "696969", - dodgerblue: "1e90ff", - firebrick: "b22222", - floralwhite: "fffaf0", - forestgreen: "228b22", - fuchsia: "f0f", - gainsboro: "dcdcdc", - ghostwhite: "f8f8ff", - gold: "ffd700", - goldenrod: "daa520", - gray: "808080", - green: "008000", - greenyellow: "adff2f", - grey: "808080", - honeydew: "f0fff0", - hotpink: "ff69b4", - indianred: "cd5c5c", - indigo: "4b0082", - ivory: "fffff0", - khaki: "f0e68c", - lavender: "e6e6fa", - lavenderblush: "fff0f5", - lawngreen: "7cfc00", - lemonchiffon: "fffacd", - lightblue: "add8e6", - lightcoral: "f08080", - lightcyan: "e0ffff", - lightgoldenrodyellow: "fafad2", - lightgray: "d3d3d3", - lightgreen: "90ee90", - lightgrey: "d3d3d3", - lightpink: "ffb6c1", - lightsalmon: "ffa07a", - lightseagreen: "20b2aa", - lightskyblue: "87cefa", - lightslategray: "789", - lightslategrey: "789", - lightsteelblue: "b0c4de", - lightyellow: "ffffe0", - lime: "0f0", - limegreen: "32cd32", - linen: "faf0e6", - magenta: "f0f", - maroon: "800000", - mediumaquamarine: "66cdaa", - mediumblue: "0000cd", - mediumorchid: "ba55d3", - mediumpurple: "9370db", - mediumseagreen: "3cb371", - mediumslateblue: "7b68ee", - mediumspringgreen: "00fa9a", - mediumturquoise: "48d1cc", - mediumvioletred: "c71585", - midnightblue: "191970", - mintcream: "f5fffa", - mistyrose: "ffe4e1", - moccasin: "ffe4b5", - navajowhite: "ffdead", - navy: "000080", - oldlace: "fdf5e6", - olive: "808000", - olivedrab: "6b8e23", - orange: "ffa500", - orangered: "ff4500", - orchid: "da70d6", - palegoldenrod: "eee8aa", - palegreen: "98fb98", - paleturquoise: "afeeee", - palevioletred: "db7093", - papayawhip: "ffefd5", - peachpuff: "ffdab9", - peru: "cd853f", - pink: "ffc0cb", - plum: "dda0dd", - powderblue: "b0e0e6", - purple: "800080", - rebeccapurple: "663399", - red: "f00", - rosybrown: "bc8f8f", - royalblue: "4169e1", - saddlebrown: "8b4513", - salmon: "fa8072", - sandybrown: "f4a460", - seagreen: "2e8b57", - seashell: "fff5ee", - sienna: "a0522d", - silver: "c0c0c0", - skyblue: "87ceeb", - slateblue: "6a5acd", - slategray: "708090", - slategrey: "708090", - snow: "fffafa", - springgreen: "00ff7f", - steelblue: "4682b4", - tan: "d2b48c", - teal: "008080", - thistle: "d8bfd8", - tomato: "ff6347", - turquoise: "40e0d0", - violet: "ee82ee", - wheat: "f5deb3", - white: "fff", - whitesmoke: "f5f5f5", - yellow: "ff0", - yellowgreen: "9acd32" -}; + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. -// Make it easy to access colors via `hexNames[hex]` -var hexNames = tinycolor.hexNames = flip(names); + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } -// Utilities -// --------- + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. -// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` -function flip(o) { - var flipped = { }; - for (var i in o) { - if (o.hasOwnProperty(i)) { - flipped[o[i]] = i; - } - } - return flipped; -} + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { -// Return a valid alpha value [0,1] with all invalid values being set to 1 -function boundAlpha(a) { - a = parseFloat(a); + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - if (isNaN(a) || a < 0 || a > 1) { - a = 1; - } + if (index >= inputLength) { + error('invalid-input'); + } - return a; -} + digit = basicToDigit(input.charCodeAt(index++)); -// Take input from [0, n] and return it as [0, 1] -function bound01(n, max) { - if (isOnePointZero(n)) { n = "100%"; } + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } - var processPercent = isPercentage(n); - n = mathMin(max, mathMax(0, parseFloat(n))); + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - // Automatically convert percentage into number - if (processPercent) { - n = parseInt(n * max, 10) / 100; - } + if (digit < t) { + break; + } - // Handle floating point rounding errors - if ((Math.abs(n - max) < 0.000001)) { - return 1; - } + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } - // Convert into [0, 1] range if it isn't already - return (n % max) / parseFloat(max); -} + w *= baseMinusT; -// Force a number between 0 and 1 -function clamp01(val) { - return mathMin(1, mathMax(0, val)); -} + } -// Parse a base-16 hex value into a base-10 integer -function parseIntFromHex(val) { - return parseInt(val, 16); -} + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); -// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 -// -function isOnePointZero(n) { - return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; -} + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } -// Check to see if string passed in is a percentage -function isPercentage(n) { - return typeof n === "string" && n.indexOf('%') != -1; -} + n += floor(i / out); + i %= out; -// Force a hex value to have 2 characters -function pad2(c) { - return c.length == 1 ? '0' + c : '' + c; -} + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); -// Replace a decimal with it's percentage value -function convertToPercentage(n) { - if (n <= 1) { - n = (n * 100) + "%"; - } + } - return n; -} + return ucs2encode(output); + } -// Converts a decimal to a hex value -function convertDecimalToHex(d) { - return Math.round(parseFloat(d) * 255).toString(16); -} -// Converts a hex value to a decimal -function convertHexToDecimal(h) { - return (parseIntFromHex(h) / 255); -} + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; -var matchers = (function() { + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); - // - var CSS_INTEGER = "[-\\+]?\\d+%?"; + // Cache the length + inputLength = input.length; - // - var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; - // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. - var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } - // Actual matching. - // Parentheses and commas are optional, but not required. - // Whitespace can take the place of commas or opening paren - var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; - var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + handledCPCount = basicLength = output.length; - return { - CSS_UNIT: new RegExp(CSS_UNIT), - rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), - rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), - hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), - hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), - hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), - hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), - hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, - hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ - }; -})(); + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. -// `isValidCSSUnit` -// Take in a single string / number and check to see if it looks like a CSS unit -// (see `matchers` above for definition). -function isValidCSSUnit(color) { - return !!matchers.CSS_UNIT.exec(color); + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],66:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); } -// `stringInputToObject` -// Permissive string parsing. Take in a number of formats, and output an object -// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` -function stringInputToObject(color) { +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; - color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); - var named = false; - if (names[color]) { - color = names[color]; - named = true; - } - else if (color == 'transparent') { - return { r: 0, g: 0, b: 0, a: 0, format: "name" }; - } + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } - // Try to match string input using regular expressions. - // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] - // Just return an object and let the conversion functions handle that. - // This way the result will be the same whether the tinycolor is initialized with string or object. - var match; - if ((match = matchers.rgb.exec(color))) { - return { r: match[1], g: match[2], b: match[3] }; - } - if ((match = matchers.rgba.exec(color))) { - return { r: match[1], g: match[2], b: match[3], a: match[4] }; - } - if ((match = matchers.hsl.exec(color))) { - return { h: match[1], s: match[2], l: match[3] }; - } - if ((match = matchers.hsla.exec(color))) { - return { h: match[1], s: match[2], l: match[3], a: match[4] }; - } - if ((match = matchers.hsv.exec(color))) { - return { h: match[1], s: match[2], v: match[3] }; - } - if ((match = matchers.hsva.exec(color))) { - return { h: match[1], s: match[2], v: match[3], a: match[4] }; - } - if ((match = matchers.hex8.exec(color))) { - return { - r: parseIntFromHex(match[1]), - g: parseIntFromHex(match[2]), - b: parseIntFromHex(match[3]), - a: convertHexToDecimal(match[4]), - format: named ? "name" : "hex8" - }; - } - if ((match = matchers.hex6.exec(color))) { - return { - r: parseIntFromHex(match[1]), - g: parseIntFromHex(match[2]), - b: parseIntFromHex(match[3]), - format: named ? "name" : "hex" - }; - } - if ((match = matchers.hex4.exec(color))) { - return { - r: parseIntFromHex(match[1] + '' + match[1]), - g: parseIntFromHex(match[2] + '' + match[2]), - b: parseIntFromHex(match[3] + '' + match[3]), - a: convertHexToDecimal(match[4] + '' + match[4]), - format: named ? "name" : "hex8" - }; + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; } - if ((match = matchers.hex3.exec(color))) { - return { - r: parseIntFromHex(match[1] + '' + match[1]), - g: parseIntFromHex(match[2] + '' + match[2]), - b: parseIntFromHex(match[3] + '' + match[3]), - format: named ? "name" : "hex" - }; + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],67:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - return false; -} +'use strict'; -function validateWCAG2Parms(parms) { - // return valid WCAG2 parms for isReadable. - // If input parms are invalid, return {"level":"AA", "size":"small"} - var level, size; - parms = parms || {"level":"AA", "size":"small"}; - level = (parms.level || "AA").toUpperCase(); - size = (parms.size || "small").toLowerCase(); - if (level !== "AA" && level !== "AAA") { - level = "AA"; - } - if (size !== "small" && size !== "large") { - size = "small"; - } - return {"level":level, "size":size}; -} +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; -// Node: Export function -if (typeof module !== "undefined" && module.exports) { - module.exports = tinycolor; -} -// AMD/requirejs: Define the module -else if (typeof define === 'function' && define.amd) { - define(function () {return tinycolor;}); -} -// Browser: Expose to window -else { - window.tinycolor = tinycolor; -} + case 'boolean': + return v ? 'true' : 'false'; -})(Math); + case 'number': + return isFinite(v) ? v : ''; -},{}],68:[function(require,module,exports){ -// yy-counter -// In-browser counter to watch changeable values like counters or FPS -// David Figatner -// (c) YOPEY YOPEY LLC 2017 -// MIT License -// https://github.com/davidfig/counter + default: + return ''; + } +}; -module.exports = class Counter -{ - /** - * @param {object} [options] - * @param {string} [options.side=rightbottom] side to place the panel (combination of right/left and bottom/top) - * @param {number} [options.padding=7px] - * @param {string} [options.color=white] - * @param {string} [options.background=rgba(0,0,0,0.5)] - * @param {*} {options.xxx} where xxx is a CSS style for the div - */ - constructor(options) - { - options = options || {} - options.side = options.side || 'rightbottom' - options.side.toLowerCase() - options.padding = options.padding || '7px' - options.color = options.color || 'white' - options.background = options.background || 'rgba(0,0,0,0.5)' - this.div = document.createElement('div') - Counter.findParent(options.side).appendChild(this.div) - for (let style in options) - { - if (style !== 'parent' && style !== 'side') - { - this.div.style[style] = options[style] - } - } - } +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } - /** - * find the parent div for one of the corners - * @param {string} [options.side] side to place the panel (combination of right/left and bottom/top) - * @return {HTMLElement} - */ - static findParent(side) - { - const styles = [] - let name = 'yy-counter-' - if (side.indexOf('left') !== -1) - { - name += 'left-' - styles['left'] = 0 - } - else - { - name += 'right-' - styles['right'] = 0 - } - if (side.indexOf('top') !== -1) - { - name += 'top' - styles['top'] = 0 - } - else - { - name += 'bottom' - styles['bottom'] = 0 - } - const test = document.getElementById(name) - if (test) - { - return test - } - const container = document.createElement('div') - container.id = name - container.style.overflow = 'hidden' - container.style.position = 'fixed' - container.style.zIndex = 10000 - container.style.pointerEvents = 'none' - container.style.userSelect = 'none' - for (let style in styles) - { - container.style[style] = styles[style] - } - document.body.appendChild(container) - return container - } + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); - /** - * replaces the innerHTML of the console - * @param {string|number} text1 - * @param {string|number} [text2] - * @param {string|number} [...textn] any number of arguments - */ - log() - { - let s = '' - for (let arg of arguments) - { - s += '
' + arg + '
' - } - this.div.innerHTML = s - } + } - /** - * appends to the innerHTML of the console - * @param {string|number} text1 - * @param {string|number} [text2] - * @param {string|number} [...textn] any number of arguments - */ - append() - { - let s = this.div.innerHTML - for (let arg of arguments) - { - s += '
' + arg + '
' - } - this.div.innerHTML = s - } + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; } -},{}],69:[function(require,module,exports){ + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],68:[function(require,module,exports){ 'use strict'; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +},{"./decode":66,"./encode":67}],69:[function(require,module,exports){ +(function (setImmediate,clearImmediate){ +var nextTick = require('process/browser.js').nextTick; +var apply = Function.prototype.apply; +var slice = Array.prototype.slice; +var immediateIds = {}; +var nextImmediateId = 0; -var Color = require('tinycolor2'); -var Counter = require('yy-counter'); +// DOM APIs, for completeness -var STYLES = { - 'background': 'rgba(0, 0, 0, 0.5)', - 'color': 'white' +exports.setTimeout = function() { + return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); +}; +exports.setInterval = function() { + return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; +exports.clearTimeout = +exports.clearInterval = function(timeout) { timeout.close(); }; -var STYLES_FPS = { - 'padding': '0.1em 0.5em' +function Timeout(id, clearFn) { + this._id = id; + this._clearFn = clearFn; +} +Timeout.prototype.unref = Timeout.prototype.ref = function() {}; +Timeout.prototype.close = function() { + this._clearFn.call(window, this._id); }; -var STYLES_METER = {}; +// Does not start the time, just sets up the members needed. +exports.enroll = function(item, msecs) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = msecs; +}; -module.exports = function () { - /** - * @param {object} [options] - * @param {boolean} [options.meter=true] include a meter with the FPS - * @param {string} [options.side=bottom-right] include any combination of left/right and top/bottom - * @param {number} [options.FPS=60] desired FPS - * @param {number} [options.tolerance=1] minimum tolerance for fluctuations in FPS number - * @param {number} [options.meterWidth=100] width of meter div - * @param {number} [options.meterHeight=25] height of meter div - * @param {number} [options.meterLineHeight=4] height of meter line - * @param {styles[]} [options.styles] CSS styles to apply to the div (in javascript format) - * @param {styles[]} [options.stylesFPS] CSS styles to apply to the FPS text (in javascript format) - * @param {styles[]} [options.stylesMeter] CSS styles to apply to the FPS meter (in javascript format) - * @param {string} [options.text=" FPS"] change the text to the right of the FPS - */ - function FPS(options) { - _classCallCheck(this, FPS); +exports.unenroll = function(item) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = -1; +}; - this.options = options || {}; - this.tolerance = this.options.tolerance || 1; - this.FPS = this.options.FPS || 60; - this.meterWidth = this.options.meterWidth || 100; - this.meterHeight = this.options.meterHeight || 25; - this.meterLineHeight = this.options.meterLineHeight || 4; - this.div = document.createElement('div'); - Counter.findParent(this.options.side || 'bottom-right').appendChild(this.div); - this.style(this.div, STYLES, this.options.styles); - this.divFPS(); - this.meter = typeof this.options.meter === 'undefined' || this.options.meter; - this.lastTime = 0; - this.frameNumber = 0; - this.lastUpdate = 0; - this.lastFPS = '--'; +exports._unrefActive = exports.active = function(item) { + clearTimeout(item._idleTimeoutId); + + var msecs = item._idleTimeout; + if (msecs >= 0) { + item._idleTimeoutId = setTimeout(function onTimeout() { + if (item._onTimeout) + item._onTimeout(); + }, msecs); + } +}; + +// That's not how node.js implements it but the exposed api is the same. +exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { + var id = nextImmediateId++; + var args = arguments.length < 2 ? false : slice.call(arguments, 1); + + immediateIds[id] = true; + + nextTick(function onNextTick() { + if (immediateIds[id]) { + // fn.call() is faster so we optimize for the common use-case + // @see http://jsperf.com/call-apply-segu + if (args) { + fn.apply(null, args); + } else { + fn.call(null); + } + // Prevent ids from leaking + exports.clearImmediate(id); } + }); - /** - * change desired FPS - * @type {number} - */ + return id; +}; +exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { + delete immediateIds[id]; +}; +}).call(this,require("timers").setImmediate,require("timers").clearImmediate) +},{"process/browser.js":64,"timers":69}],70:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - _createClass(FPS, [{ - key: 'remove', +'use strict'; +var punycode = require('punycode'); +var util = require('./util'); - /** - * remove meter from DOM - */ - value: function remove() { - this.div.remove(); - } +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; - /** - * @type {boolean} meter (the FPS graph) is on or off - */ +exports.Url = Url; - }, { - key: 'style', - value: function style(div, style1, style2) { - for (var style in style1) { - div.style[style] = style1[style]; - } - if (style2) { - for (var _style in style2) { - div.style[_style] = style2[_style]; - } - } - } +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} - /** - * create div for text FPS - * @private - * @param {HTMLElement} div - * @param {object} options (see contructor) - */ +// Reference: RFC 3986, RFC 1808, RFC 2396 - }, { - key: 'divFPS', - value: function divFPS() { - var div = this.div; - var options = this.options; - var divFPS = document.createElement('div'); - div.appendChild(divFPS); - this.fpsSpan = document.createElement('span'); - divFPS.appendChild(this.fpsSpan); - var span = document.createElement('span'); - divFPS.appendChild(span); - span.innerText = typeof options.text !== 'undefined' ? options.text : ' FPS'; - this.style(div, STYLES_FPS, options.stylesFPS); - } +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, - /** - * create div for FPS meter - * @private - * @param {HTMLElement} div - * @param {object} options (see contructor) - */ + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - }, { - key: 'divMeter', - value: function divMeter() { - var div = this.div; - var options = this.options; - if (!this.meterCanvas) { - this.meterCanvas = document.createElement('canvas'); - div.appendChild(this.meterCanvas); - this.meterCanvas.width = this.meterWidth; - this.meterCanvas.height = this.meterHeight; - this.meterCanvas.style.width = div.width + 'px'; - this.meterCanvas.style.height = div.height + 'px'; - this.style(this.meterCanvas, STYLES_METER, options.stylesMeter); - } else { - this.meterCanvas.style.display = 'block'; - } - } + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); - /** - * call this at the start of the frame to calculate FPS - */ + var rest = url; - }, { - key: 'frame', - value: function frame() { - this.frameNumber++; - var currentTime = performance.now() - this.lastTime; + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); - // skip large differences to remove garbage - if (currentTime > 500) { - if (this.lastTime !== 0) { - this.lastFPS = Math.floor(this.frameNumber / (currentTime / 1000)); - if (this.lastFPS >= this.FPS - this.tolerance && this.lastFPS <= this.FPS + this.tolerance) { - this.lastFPS = this.FPS; - } - } - this.lastTime = performance.now(); - this.frameNumber = 0; - } - this.fpsSpan.innerText = this.lastFPS; - if (this.meterCanvas && this.lastFPS !== '--') { - this.meterUpdate(this.lastFPS / this.FPS); - } - } - }, { - key: 'meterUpdate', - value: function meterUpdate(percent) { - var c = this.meterCanvas.getContext('2d'); - var data = c.getImageData(0, 0, this.meterCanvas.width, this.meterCanvas.height); - c.putImageData(data, -1, 0); - c.clearRect(this.meterCanvas.width - 1, 0, 1, this.meterCanvas.height); - if (percent < 0.5) { - c.fillStyle = Color.mix('#ff0000', '0xffa500', percent * 200).toHexString(); - } else { - c.fillStyle = Color.mix('#ffa500', '#00ff00', (percent - 0.5) * 200).toHexString(); - } - var height = (this.meterCanvas.height - this.meterLineHeight) * (1 - percent); - c.fillRect(this.meterCanvas.width - 1, height, 1, this.meterLineHeight); - } - }, { - key: 'side', - value: function side(options) { - if (options.side) { - options.side = options.side.toLowerCase(); - if (options.side.indexOf('left') !== -1) { - STYLES['left'] = 0; - delete STYLES['right']; - } else { - STYLES['right'] = 0; - delete STYLES['left']; - } - if (options.side.indexOf('top') !== -1) { - STYLES['top'] = 0; - delete STYLES['bottom']; - } else { - STYLES['bottom'] = 0; - delete STYLES['top']; - } - } else { - STYLES['right'] = 0; - STYLES['bottom'] = 0; - } - } - }, { - key: 'fps', - get: function get() { - return this.FPS; - }, - set: function set(value) { - this.FPS = value; - } - }, { - key: 'meter', - get: function get() { - return this._meter; - }, - set: function set(value) { - if (value) { - this.divMeter(); - } else if (this.meterCanvas) { - this.meterCanvas.style.display = 'none'; - } + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); } - }]); + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } - return FPS; -}(); + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } -},{"tinycolor2":67,"yy-counter":68}],70:[function(require,module,exports){ -'use strict'; + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c -// yy-random -// by David Figatner -// MIT license -// copyright YOPEY YOPEY LLC 2016-17 -// https://github.com/davidfig/random + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. -var seedrandom = require('seedrandom'); + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } -var Random = function () { - function Random() { - _classCallCheck(this, Random); + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } - this.generator = Math.random; + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); } - /** - * generates a seeded number - * @param {number} seed - * @param {object} [options] - * @param {string} [PRNG="alea"] - name of algorithm, see https://github.com/davidbau/seedrandom - * @param {(boolean|string)} [state] - can include the state returned from save() - */ + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); - _createClass(Random, [{ - key: 'seed', - value: function seed(_seed, options) { - options = options || {}; - this.generator = seedrandom[options.PRNG || 'alea'](_seed, { state: options.state }); - this.options = options; - } + // pull out port. + this.parseHost(); - /** - * saves the state of the random generator - * can only be used after Random.seed() is called with options.state = true - * @returns {number} state - */ + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; - }, { - key: 'save', - value: function save() { - if (this.generator !== Math.random) { - return this.generator.state(); + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; } + this.hostname = validParts.join('.'); + break; + } } + } + } - /** - * restores the state of the random generator - * @param {number} state - */ + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } - }, { - key: 'restore', - value: function restore(state) { - this.generator = seedrandom[this.options.PRNG || 'alea']('', { state: state }); - } + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } - /** - * changes the generator to use the old Math.sin-based random function - * based on : http://stackoverflow.com/questions/521295/javascript-random-seeds - * (deprecated) Use only for compatibility purposes - * @param {number} seed - */ + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; - }, { - key: 'seedOld', - value: function seedOld(seed) { - this.generator = function () { - var x = Math.sin(seed++) * 10000; - return x - Math.floor(x); - }; - } + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } - /** - * create a separate random generator using the seed - * @param {number} seed - * @return {object} - */ + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { - }, { - key: 'separateSeed', - value: function separateSeed(seed) { - var random = new Random(); - random.seed(seed); - return random; - } + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } - /** - * resets the random number this.generator to Math.random() - */ - }, { - key: 'reset', - value: function reset() { - this.generator = Math.random; - } + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } - /** - * returns a random number using the this.generator between [0, ceiling - 1] - * @param {number} ceiling - * @param {boolean} [useFloat=false] - * @return {number} - */ + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } - }, { - key: 'get', - value: function get(ceiling, useFloat) { - var negative = ceiling < 0 ? -1 : 1; - ceiling *= negative; - var result = void 0; - if (useFloat) { - result = this.generator() * ceiling; - } else { - result = Math.floor(this.generator() * ceiling); - } - return result * negative; - } + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; - /** - * returns a random integer between 0 - Number.MAX_SAFE_INTEGER - * @return {number} - */ +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} - }, { - key: 'getHuge', - value: function getHuge() { - return this.get(Number.MAX_SAFE_INTEGER); - } +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } - /** - * random number [middle - range, middle + range] - * @param {number} middle - * @param {number} delta - * @param {boolean} [useFloat=false] - * @return {number} - */ + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; - }, { - key: 'middle', - value: function middle(_middle, delta, useFloat) { - var half = delta / 2; - return this.range(_middle - half, _middle + half, useFloat); - } + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } - /** - * random number [start, end] - * @param {number} start - * @param {number} end - * @param {boolean} [useFloat=false] if true, then range is (start, end)--i.e., not inclusive to start and end - * @return {number} - */ + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } - }, { - key: 'range', - value: function range(start, end, useFloat) { - // case where there is no range - if (end === start) { - return end; - } + var search = this.search || (query && ('?' + query)) || ''; - if (useFloat) { - return this.get(end - start, true) + start; - } else { - var range = void 0; - if (start < 0 && end > 0) { - range = -start + end + 1; - } else if (start === 0 && end > 0) { - range = end + 1; - } else if (start < 0 && end === 0) { - range = start - 1; - start = 1; - } else if (start < 0 && end < 0) { - range = end - start - 1; - } else { - range = end - start + 1; - } - return Math.floor(this.generator() * range) + start; - } - } + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - /** - * an array of random numbers between [start, end] - * @param {number} start - * @param {number} end - * @param {number} count - * @param {boolean} [useFloat=false] - * @return {number[]} - */ + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; - }, { - key: 'rangeMultiple', - value: function rangeMultiple(start, end, count, useFloat) { - var array = []; - for (var i = 0; i < count; i++) { - array.push(this.range(start, end, useFloat)); - } - return array; - } + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); - /** - * an array of random numbers between [middle - range, middle + range] - * @param {number} middle - * @param {number} range - * @param {number} count - * @param {boolean} [useFloat=false] - * @return {number[]} - */ + return protocol + host + pathname + search + hash; +}; - }, { - key: 'middleMultiple', - value: function middleMultiple(middle, range, count, useFloat) { - var array = []; - for (var i = 0; i < count; i++) { - array.push(middle(middle, range, useFloat)); - } - return array; - } +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} - /** - * @param {number} [chance=0.5] - * returns random sign (either +1 or -1) - * @return {number} - */ +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; - }, { - key: 'sign', - value: function sign(chance) { - chance = chance || 0.5; - return this.generator() < chance ? 1 : -1; - } +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} - /** - * tells you whether a random chance was achieved - * @param {number} [percent=0.5] - * @return {boolean} - */ +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } - }, { - key: 'chance', - value: function chance(percent) { - return this.generator() < (percent || 0.5); - } + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } - /** - * returns a random angle in radians [0 - 2 * Math.PI) - */ + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; - }, { - key: 'angle', - value: function angle() { - return this.get(Math.PI * 2, true); - } + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } - /** - * Shuffle array (either in place or copied) - * from http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array - * @param {Array} array - * @param {boolean} [copy=false] whether to shuffle in place (default) or return a new shuffled array - * @return {Array} a shuffled array - */ + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } - }, { - key: 'shuffle', - value: function shuffle(array, copy) { - if (copy) { - array = array.slice(); - } - if (array.length === 0) { - return array; - } + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } - var currentIndex = array.length, - temporaryValue = void 0, - randomIndex = void 0; + result.href = result.format(); + return result; + } - // While there remain elements to shuffle... - while (0 !== currentIndex) { - // Pick a remaining element... - randomIndex = this.get(currentIndex); - currentIndex -= 1; + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } - // And swap it with the current element. - temporaryValue = array[currentIndex]; - array[currentIndex] = array[randomIndex]; - array[randomIndex] = temporaryValue; - } - return array; - } + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } - /** - * picks a random element from an array - * @param {Array} array - * @return {*} - */ + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; - }, { - key: 'pick', - value: function pick(array, remove) { - if (!remove) { - return array[this.get(array.length)]; - } else { - var pick = this.get(array.length); - var temp = array[pick]; - array.splice(pick, 1); - return temp; - } - } + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } - /** - * returns a random property from an object - * from http://stackoverflow.com/questions/2532218/pick-random-property-from-a-javascript-object - * @param {object} obj - * @return {*} - */ + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } - }, { - key: 'property', - value: function property(obj) { - var result; - var count = 0; - for (var prop in obj) { - if (this.chance(1 / ++count)) { - result = prop; - } - } - return result; - } + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } - /** - * creates a random set where each entry is a value between [min, max] - * @param {number} min - * @param {number} max - * @param {number} amount of numbers in set - * @param {number[]} - */ + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); - }, { - key: 'set', - value: function set(min, max, amount) { - var set = [], - all = [], - i; - for (i = min; i < max; i++) { - all.push(i); - } + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } - for (i = 0; i < amount; i++) { - var found = this.get(all.length); - set.push(all[found]); - all.splice(found, 1); - } - return set; - } + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } - /** - * returns a set of numbers with a randomly even distribution (i.e., no overlapping and filling the space) - * @param {number} start position - * @param {number} end position - * @param {number} count of non-start/end points - * @param {boolean} [includeStart=false] includes start point (count++) - * @param {boolean} [includeEnd=false] includes end point (count++) - * @param {boolean} [useFloat=false] - * @param {number[]} - */ + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } - }, { - key: 'distribution', - value: function distribution(start, end, count, includeStart, includeEnd, useFloat) { - var interval = Math.floor((end - start) / count); - var halfInterval = interval / 2; - var quarterInterval = interval / 4; - var set = []; - if (includeStart) { - set.push(start); - } - for (var i = 0; i < count; i++) { - set.push(start + i * interval + halfInterval + this.range(-quarterInterval, quarterInterval, useFloat)); - } - if (includeEnd) { - set.push(end); - } - return set; - } + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } - /** - * returns a random number based on weighted probability between [min, max] - * from http://stackoverflow.com/questions/22656126/javascript-random-number-with-weighted-probability - * @param {number} min value - * @param {number} max value - * @param {number} target for average value - * @param {number} stddev - standard deviation - */ + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); - }, { - key: 'weightedProbabilityInt', - value: function weightedProbabilityInt(min, max, target, stddev) { - function normRand() { - var x1 = void 0, - x2 = void 0, - rad = void 0; - do { - x1 = 2 * this.get(1, true) - 1; - x2 = 2 * this.get(1, true) - 1; - rad = x1 * x1 + x2 * x2; - } while (rad >= 1 || rad === 0); - var c = Math.sqrt(-2 * Math.log(rad) / rad); - return x1 * c; - } + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } - stddev = stddev || 1; - if (Math.random() < 0.81546) { - while (true) { - var sample = normRand() * stddev + target; - if (sample >= min && sample <= max) { - return sample; - } - } - } else { - return this.range(min, max); - } - } + mustEndAbs = mustEndAbs || (result.host && srcPath.length); - /* - * returns a random hex color (0 - 0xffffff) - * @return {number} - */ + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } - }, { - key: 'color', - value: function color() { - return this.get(0xffffff); - } - }]); + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } - return Random; -}(); + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; -module.exports = new Random(); +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":71,"punycode":65,"querystring":68}],71:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; -},{"seedrandom":59}]},{},[13]); +},{}]},{},[4]); diff --git a/docs/jsdoc/Simple.html b/docs/jsdoc/Simple.html index 758c63f..c7f79ba 100644 --- a/docs/jsdoc/Simple.html +++ b/docs/jsdoc/Simple.html @@ -2336,7 +2336,7 @@

diff --git a/docs/jsdoc/SpatialHash.html b/docs/jsdoc/SpatialHash.html index b9259b1..1566af0 100644 --- a/docs/jsdoc/SpatialHash.html +++ b/docs/jsdoc/SpatialHash.html @@ -3604,7 +3604,7 @@

diff --git a/docs/jsdoc/global.html b/docs/jsdoc/global.html index 3b99d71..bfd7434 100644 --- a/docs/jsdoc/global.html +++ b/docs/jsdoc/global.html @@ -916,7 +916,7 @@

Properties:
diff --git a/docs/jsdoc/index.html b/docs/jsdoc/index.html index e3c3fca..4ce01c6 100644 --- a/docs/jsdoc/index.html +++ b/docs/jsdoc/index.html @@ -314,7 +314,7 @@

license

diff --git a/docs/jsdoc/simple.js.html b/docs/jsdoc/simple.js.html index 7b83ef7..cc2b67c 100644 --- a/docs/jsdoc/simple.js.html +++ b/docs/jsdoc/simple.js.html @@ -491,7 +491,7 @@

simple.js

diff --git a/docs/jsdoc/spatial-hash.js.html b/docs/jsdoc/spatial-hash.js.html index ed53be1..628c2cc 100644 --- a/docs/jsdoc/spatial-hash.js.html +++ b/docs/jsdoc/spatial-hash.js.html @@ -780,7 +780,7 @@

spatial-hash.js

diff --git a/yarn.lock b/yarn.lock index 591744f..46d7f7f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,319 +2,319 @@ # yarn lockfile v1 -"@babel/parser@^7.4.4": - version "7.7.5" - resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.7.5.tgz#cbf45321619ac12d83363fcf9c94bb67fa646d71" - integrity sha512-KNlOe9+/nk4i29g0VXgl8PEXIRms5xKLJeuZ6UptN0fHv+jDiriG+y94X6qAgWTR0h3KaoM1wK5G5h7MHFRSig== - -"@pixi/accessibility@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/accessibility/-/accessibility-5.2.0.tgz#e59a876e1ceaf149811fe225e171f16cc2ccbef6" - integrity sha512-IXnCy9YmzXl9/rMiXOzgFpP7onW0YNSnVQtFotonCEPd2azM/1p3Fy7wRTcpfOJm/JsMZRbnDeE/wB9Shg9/QQ== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/app@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/app/-/app-5.2.0.tgz#dd216fd3cfc2e290fbf62200639bc8ee3738ba3e" - integrity sha512-5rhjAGPruzC3w6+knySIWk4II1Td8Fw0LVfg1K48BRXI1mLXCrZ3tJb6hdFuBPhgeIDz1tUwecJ4KfkJOWgqPg== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - -"@pixi/constants@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/constants/-/constants-5.2.0.tgz#2ddf7aa62d01412136f973dc9f316d0aabd845ba" - integrity sha512-dXwzkKAvgpvOJmDBe9OQiE+HPp4uMIL/3ijHlyW0fgMqDPhtQtFcSUdSUAoFwb23Uaq56j1ejuEmly8LehJ0aQ== - -"@pixi/core@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/core/-/core-5.2.0.tgz#5c89e52f96ebf95bf3408dd783d796972d7ccd58" - integrity sha512-h8UuVWHfbWVGEO3a4SQS4vk70LSFMUMPKCvVpPq/3LtIUgPVDZO3tGL4O2jFteKwbmWNIMDCpDmBMu3XlqPlNQ== - dependencies: - "@pixi/constants" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/runner" "^5.2.0" - "@pixi/settings" "^5.2.0" - "@pixi/ticker" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/display@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/display/-/display-5.2.0.tgz#f6ca47c10db1379b62091e664b7a3a70c095e814" - integrity sha512-P+exW4aI7eyqhdmi0M3HmKJI+XzDYNYAiEsKMUyyONwbHYSVdjQF5hzPuvjUYotTNZ1stCWbf0457cNNSPLOzQ== - dependencies: - "@pixi/math" "^5.2.0" - "@pixi/settings" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/extract@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/extract/-/extract-5.2.0.tgz#ba44745380f40b104543871de4db09b6d2d09f7a" - integrity sha512-LUDsB6z+gkSYcS8urr/JjdpLlf/z3mAjpMJDOZlcxCdPXdayVka2ruNnrWb4dvf9nV9Wg7T8v1IOFGOWpOHEdQ== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/filter-alpha@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/filter-alpha/-/filter-alpha-5.2.0.tgz#a0b028655ee95a9d76963a85d7e78c6742113b3c" - integrity sha512-Jv/eqSt6zmKr9oGoi4UgUWA/pgxhyBSGMtUWMHiwuqjkXWl4Em4bC5l0f5GUX85xqMCRLwvOeqOH+fBE9fKadw== - dependencies: - "@pixi/core" "^5.2.0" - -"@pixi/filter-blur@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/filter-blur/-/filter-blur-5.2.0.tgz#a926b9e16abfab51dfb1bef2483ffb24cf02727d" - integrity sha512-052qyY+X3HMEvHdorqXIbe+iODK0Sj3j8goZMvOL2qATW6bDBGRuwrO2rGZ70BnmGgrbIrXzDVemwo9uLWEZSA== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/settings" "^5.2.0" - -"@pixi/filter-color-matrix@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/filter-color-matrix/-/filter-color-matrix-5.2.0.tgz#ae4685c1778388ea7aed23417180846a08653dfb" - integrity sha512-wtPzz+2NtP9zDW9cFn/lTryf97/DYwka4yi9A+sMCteoATsrZJCKz0zzPV5AORKv0hpCfu9wGYTISItOC8mBKw== - dependencies: - "@pixi/core" "^5.2.0" - -"@pixi/filter-displacement@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/filter-displacement/-/filter-displacement-5.2.0.tgz#c2420393ac8ae9dd91ea6fb7426f48b5f201c224" - integrity sha512-489KUlNF4ZmHZPNmI2X77cE95sfbvvw5NASeNXKmbCn5xi2gPSxiPMTv4XUTdhdOKxNcy81NFEQicG21eW335Q== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/math" "^5.2.0" - -"@pixi/filter-fxaa@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/filter-fxaa/-/filter-fxaa-5.2.0.tgz#57d8579cd806831763790179315ee37e69f6e2e6" - integrity sha512-rlhC65BALzQAVBEXYzr8bKqyhZIWLco+VWJ7Fs8D3bJCutyu6xX6d7XDAqQW5SmJCNrIdaKvl/B6Xzer/+z8DA== - dependencies: - "@pixi/core" "^5.2.0" - -"@pixi/filter-noise@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/filter-noise/-/filter-noise-5.2.0.tgz#6164828292a80a3ffc878507fcfa4f6fc8bf7fa1" - integrity sha512-7IBHqjuze5VEMYOKPz/O7wR3mks7xvYKvWmUaLV7FopUtDUFjklrVBWY39nBOsXKXm0qLOkkdKcwsqyXZ7xOFg== - dependencies: - "@pixi/core" "^5.2.0" - -"@pixi/graphics@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/graphics/-/graphics-5.2.0.tgz#d1a976f0257d53dd6adf5617f38a45268f0d0b96" - integrity sha512-sXmN8CEjzd56wVh18AOv1cxsB70tP1FWIukTPg8EaSlhiFqiclQDGkf6mKDajuVrj7JhBjvFenKmv3ADYnLkqA== - dependencies: - "@pixi/constants" "^5.2.0" - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/sprite" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/interaction@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/interaction/-/interaction-5.2.0.tgz#c2598c86cfde8d68ee141fce861ee35e3a5950c0" - integrity sha512-YoFGrwkKgNFsusXObcfgKJtLxjqeOaek3tZxssnZZOUSzIJGQ4mLur2I36C2AAufB+GxBL38TiP1nkAVurMC6A== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/ticker" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/loaders@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/loaders/-/loaders-5.2.0.tgz#803a72395516428d38d131d1aac5b0008cf3148c" - integrity sha512-lKd5RYGQ86NoQNFcu/IYLEkC/oa6XypDKewG9LDd7n9XKKeed0NRipg7HhcYVsliayYkszoQ/JdzidV/yxnHYw== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/utils" "^5.2.0" +"@babel/parser@^7.9.4": + version "7.11.3" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.11.3.tgz#9e1eae46738bcd08e23e867bab43e7b95299a8f9" + integrity sha512-REo8xv7+sDxkKvoxEywIdsNFiZLybwdI7hcT5uEPyQrSMB4YQ973BfC9OOrD/81MaIjh6UxdulIQXkjmiH3PcA== + +"@pixi/accessibility@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/accessibility/-/accessibility-5.3.3.tgz#b7bab17e3cf5eb5f511471df943155a4eadf0c6e" + integrity sha512-wC/enJtw5CrdWnu6l5u3VN9UIZPumNSNXlGez2BULY0osiLTywHJPdHpmXMz2YPXw75GsEBzkEvK4LTtnTp21A== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/app@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/app/-/app-5.3.3.tgz#6357e2e5acc1ed118b7f94c1179cef55ce6ed59c" + integrity sha512-OkO7Kq3N+FPRshVmApuiHKBpobic56VYbLVCMYPy6rjV0hc5ctkchKGFyouJuPt/rHeI6FrqZ0TaON1TShnKiA== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + +"@pixi/constants@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/constants/-/constants-5.3.3.tgz#faaed2d0ce364d67fe3e69ac97e9db1f6ad6c041" + integrity sha512-IybgxzLlEPm7ihp70cLNKc3IPyqkFuW+idk9Zw2St+OayJTw5ctCnLAg9cducwIVHjPYTvN46BYDa+n0KRWZYw== + +"@pixi/core@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/core/-/core-5.3.3.tgz#4b973ee3d18f6324d63311e8a00a68ecb1996532" + integrity sha512-taw50LnzV+TQVMx5HQA2ZJgF9wuhZ6DeoXHW2KkevYB0ekKYnEO2VMMiRDMcmchtyvHclJebzjeHZLGqDtKDgw== + dependencies: + "@pixi/constants" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/runner" "5.3.3" + "@pixi/settings" "5.3.3" + "@pixi/ticker" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/display@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/display/-/display-5.3.3.tgz#14646b35b80b8586316be3495e3c0e7fa610f499" + integrity sha512-dPm7Vk2BH9byu6RHBYsI9MtjUU8x1HNm/PIi6lIlxANhTjWnhxwfvmrGE7ZcRLThTenNdDVlZ2ke2XAXP98UgA== + dependencies: + "@pixi/math" "5.3.3" + "@pixi/settings" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/extract@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/extract/-/extract-5.3.3.tgz#5ab8e2977823d0ea75db003e45d6c6d72bc2b642" + integrity sha512-CE0GA+tEBPurpaXER2B1aq1sdumKLtCqE/Mms6fYUkIKF9D0Ogw9rqo79QCL9XkLMexa7xVeC3KPPiXW5wrOaA== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/filter-alpha@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/filter-alpha/-/filter-alpha-5.3.3.tgz#2d3e10e8f42f787a5115e81b13265839b2162797" + integrity sha512-AxyHLnvO892va9raZbMMtMtEGDVqO8SvEHHNnCjTBEZ67kVKy0HEYXFOBA6nJZ6BiTgGp9js+7kevi11tfqnJQ== + dependencies: + "@pixi/core" "5.3.3" + +"@pixi/filter-blur@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/filter-blur/-/filter-blur-5.3.3.tgz#c530e40038dec1725a399753ac97faa3418559cf" + integrity sha512-vLN1DL6PQXo4p7j/32PZIf+lhcBVfb9hdphSmtbxlAlpbhMWI52n3YUkeInwHs7Ev08NyhI/UhNWHqjN/lAM3w== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/settings" "5.3.3" + +"@pixi/filter-color-matrix@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/filter-color-matrix/-/filter-color-matrix-5.3.3.tgz#c1ecf83a44f68d78b5436b920b459c5222f373a5" + integrity sha512-HFr+vth5ZHHEFJYcjtWZ+O0s7Z2YWJyDyxr+nTd5Q8AT7gMDTVehpNVrm7ByaCKeEovOZzZI6A347+WmHcNpGg== + dependencies: + "@pixi/core" "5.3.3" + +"@pixi/filter-displacement@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/filter-displacement/-/filter-displacement-5.3.3.tgz#f25193f738b90cc75cd04bbbcd0aefe9ea037af1" + integrity sha512-kvrKMgqW4ELg+yT2p5vmu6h/IER/L8GD1PWyXovnzpI8RG7k8l136F9VvA3wkB6sYuNcXiDtqMtRQy5e6O4+rw== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/math" "5.3.3" + +"@pixi/filter-fxaa@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/filter-fxaa/-/filter-fxaa-5.3.3.tgz#c7701631d60f485b6ec1052f71afb0637ca5f0b8" + integrity sha512-p4vKdBwaoGRNZcoHz2ET8hBF1SoWvy9xU2B3Ci32+c0dg89ZUdGTEW0zimUHi2gMdU+2v/T0lqZ9NC9B6WVYAg== + dependencies: + "@pixi/core" "5.3.3" + +"@pixi/filter-noise@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/filter-noise/-/filter-noise-5.3.3.tgz#5d821d9f83f97d83d4be52f3ecc7e2d06ff1c084" + integrity sha512-HCky3XPk6BYGXTS7d9/FnAHnqq7Rwm5Rlj2XtWW3JItXGCScEBII227xYwrJu5Ke84tpVlDXK4W1/BevZ1AwlQ== + dependencies: + "@pixi/core" "5.3.3" + +"@pixi/graphics@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/graphics/-/graphics-5.3.3.tgz#cfaf5a0a94a811f7359c20875547c14095f1ecec" + integrity sha512-1bn9Jptg3JXgVOw0SrEMdmjSwkTBYDm6fPnPnh4goF3yDozh0xEqmXobVtCgy2fulMfHRzIfbgtRxrBf2mkCAg== + dependencies: + "@pixi/constants" "5.3.3" + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/sprite" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/interaction@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/interaction/-/interaction-5.3.3.tgz#07348e7d25b8e67473ed54f679ebe84ab9ee0400" + integrity sha512-Tjuw4XwmrG1fhGzfn5oGspRJT2OtlH+6V7AHscH0v5Ht1Kvk6aKjNncZuSCXllhGGlIuMu3Nn9WPvDEIvW3JNw== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/ticker" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/loaders@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/loaders/-/loaders-5.3.3.tgz#d415f25f9af64d97810e459caa2c0aca4b6a1b7c" + integrity sha512-wj0DzniApfDoZA/buMmO/CgCB7Q7SsESForHh7wSd7UC8rrCmz5prUTEICmJGhdHpBuVB7KDPtwaaLtr9Q/kQg== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/utils" "5.3.3" resource-loader "^3.0.1" -"@pixi/math@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/math/-/math-5.2.0.tgz#4c853b8621a31791be6ade9cdfcd4168c69b8079" - integrity sha512-Y21H/kMluJqZ/QWb8cdXuZlib6G26QfZtgc85KbSJmjpMVWw03g0OELqFqOhsMzNanXp3B4OL1ZsNXnp0lWROQ== - -"@pixi/mesh-extras@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/mesh-extras/-/mesh-extras-5.2.0.tgz#3c595ae56c33716a13c8c3a2b95794a70591dd98" - integrity sha512-vmBcV3sRqHWZIfwd8GQEscqR8zzsgCLXdgE/tWOCGqgGbv0+mv25y/vRnRnL42YXZb/sPU1RrtgnDr7xHNVL2w== - dependencies: - "@pixi/constants" "^5.2.0" - "@pixi/core" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/mesh" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/mesh@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/mesh/-/mesh-5.2.0.tgz#6e5f085e9959337b267b4712e54d860ece28b482" - integrity sha512-GTgxMlK3T2aWNk2CpWw6+zDXzOxDN15v4noVM6hqm691GQn6HXD68J14BHJhZxuP3PU9VD7/FARooMtAwaxVvg== - dependencies: - "@pixi/constants" "^5.2.0" - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/settings" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/mixin-cache-as-bitmap@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/mixin-cache-as-bitmap/-/mixin-cache-as-bitmap-5.2.0.tgz#349cf4436d2d2bea25cf45b4e0f45d5339e191a7" - integrity sha512-VaFxBiPFu5Ii3T/vwe+QozvQk/OMLApe0eTSXCzAZspijVCGVmnalTqDgY9GC6SvuLG967jRTdEwCAsc+w2uXA== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/settings" "^5.2.0" - "@pixi/sprite" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/mixin-get-child-by-name@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/mixin-get-child-by-name/-/mixin-get-child-by-name-5.2.0.tgz#857903c42e36aab01e80d0ae5cb9e8877bee3212" - integrity sha512-exL50cOrjOmJ02++Q56AamYkVKt7RqwdM0QQdfmJKRX9r8cG9u09IKW2/hWKGbyqNoP5gGORtZvXRCJG8JYH/A== - dependencies: - "@pixi/display" "^5.2.0" - -"@pixi/mixin-get-global-position@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/mixin-get-global-position/-/mixin-get-global-position-5.2.0.tgz#42adc4a0ba9c02186d3ab5964744bdd316cea2a6" - integrity sha512-9P2EeymV23OonCVOdgYu0ZFlUZoCXh0wK/6wf6wb0N4Nefcz0mPfafHV5gp/qwCgB9OJk4RLKna1BDfxXn4LCA== - dependencies: - "@pixi/display" "^5.2.0" - "@pixi/math" "^5.2.0" - -"@pixi/particles@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/particles/-/particles-5.2.0.tgz#c9671886bc91acdd318b56cc09cdf2f7981a1ca1" - integrity sha512-uB86M9hpiamclCOLMk6go0WJGXoiNfNzIIiC5OmUt61Fk3TSZiXbF//xWt/NB/unm3+WhycudSfR1IhLL1OdSw== - dependencies: - "@pixi/constants" "^5.2.0" - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/polyfill@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/polyfill/-/polyfill-5.2.0.tgz#69476c8b3432ee661dacff1a73d0887de0d8ef3e" - integrity sha512-xvwJ0vRVwf6fByvGTRzOsAv0N5GmopVI+pT5MV8Rk4AoqGQ8vWkhQQ8jy7PS4g0ak2DpwVrcTwUjxfrmjJCYTw== +"@pixi/math@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/math/-/math-5.3.3.tgz#5d40d36fa1701e195083adb84bddf2f6420c2f4c" + integrity sha512-k5C3kQpxlGm2AdBJEUjjW2l2YlSvTKf+54vNOjD4UcEfRoDevC5p4Zg49q3UAu855lrs5qw49AbkrFKsQvPIRA== + +"@pixi/mesh-extras@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/mesh-extras/-/mesh-extras-5.3.3.tgz#99c712fdb1b0a9db66fd95a76de26361a7055ab4" + integrity sha512-V2hARC7nUPaTEFxd+B8GDkSMrMZ38S8/IInqtYzGUy6FtFs7IYKty9Rz/G665eN7ThIq8tZrOVZOl6JRBtEC8A== + dependencies: + "@pixi/constants" "5.3.3" + "@pixi/core" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/mesh" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/mesh@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/mesh/-/mesh-5.3.3.tgz#f0adf0362c18e6e7646b7abaccec47d304cbb405" + integrity sha512-q8w70oAFNdArzOHVnsn7ban68NmO5S5TMg6qSez4A8te6cebMRQsNrT/0dQ/nZcG7ACFK4jiYfbXRQivO+jgVA== + dependencies: + "@pixi/constants" "5.3.3" + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/settings" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/mixin-cache-as-bitmap@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/mixin-cache-as-bitmap/-/mixin-cache-as-bitmap-5.3.3.tgz#cac6a2ecf3b72fbae58ab3657998360ddbda7382" + integrity sha512-P1mo3HKDWS8IZLgaP8gujiy4We4vRcxJH6EvQAevf+GsBzdjKfcGgkKzVb9HlyQvsXML5gpTOJuw5eKgRTxSQA== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/settings" "5.3.3" + "@pixi/sprite" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/mixin-get-child-by-name@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/mixin-get-child-by-name/-/mixin-get-child-by-name-5.3.3.tgz#828dc9a7beae603648ebe2ccb67517c7137bff19" + integrity sha512-CksDZ5ZG4/tHZfDOwSuznANduasJg5JR89X3D6E9DVYx4CLVE3G2K1sbeiOJNXfGIKy30UoSD7Y7IFmUzLxp/g== + dependencies: + "@pixi/display" "5.3.3" + +"@pixi/mixin-get-global-position@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/mixin-get-global-position/-/mixin-get-global-position-5.3.3.tgz#5700b03794e5b21f61c015aeda733c3cb625fc75" + integrity sha512-M3faQYDW/ISa1+lhVkjHXRALJ33BMzLN+7x9ucx8VeCmUWvcaLlRo3CaxZsgiR+52Fii5WHl/PF/cMzdkRMF9g== + dependencies: + "@pixi/display" "5.3.3" + "@pixi/math" "5.3.3" + +"@pixi/particles@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/particles/-/particles-5.3.3.tgz#3e9d2d317d6cd11a3736830dfbd4cc0c3a1082c8" + integrity sha512-t+lG8iGNYyS6ujKvC9qQjKzyxvjxqbFxvB6hkXcOKR98JWM2726ZguHouFlIbOzOxYAGoeuHIWSDlnQNvnVE2g== + dependencies: + "@pixi/constants" "5.3.3" + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/polyfill@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/polyfill/-/polyfill-5.3.3.tgz#4d0050b0bb75a7b51841f7bfec4c29243a605be7" + integrity sha512-gmx67A6VmwKllxfIMQWzMUNJ8wJfWPT5FlUR0SoPastdTB/SfbgbyQBgKLZHqgmc6LOh2CrOLhN423lNiAroeA== dependencies: es6-promise-polyfill "^1.2.0" object-assign "^4.1.1" -"@pixi/prepare@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/prepare/-/prepare-5.2.0.tgz#c62411f986b61e055f9906a784315fa9114e835a" - integrity sha512-WE/VUIJXFrYMXFmWom4BZYB78IHQNeRZfN1SDN4X11cOciFH8uDafDpkMsjND95HZAqw+yQPU2pKResQnWEtag== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/graphics" "^5.2.0" - "@pixi/settings" "^5.2.0" - "@pixi/text" "^5.2.0" - "@pixi/ticker" "^5.2.0" - -"@pixi/runner@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/runner/-/runner-5.2.0.tgz#b93688e2ed22f59b1c779be450730f383cae5691" - integrity sha512-vy/SGG8QFHMrWAqebMQdhxl/l6WlIbHXMDNDCYBWwXKYjmKzycrrj2o/mK9cBko8WDuoTRZ0Pe3JZ3XDYEsn9w== - -"@pixi/settings@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/settings/-/settings-5.2.0.tgz#34e2a9ad25b34be75226846417c806a40d6c6615" - integrity sha512-AIxcUbgM3mh2QxS+nxNcPsqnJEBg3x/UO9ZpNMRhed9UPM/5mQ8CGZUMLTzIxhjSS16Do4uK9vZikMjV8dXm/Q== - dependencies: - ismobilejs "^0.5.1" - -"@pixi/sprite-animated@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/sprite-animated/-/sprite-animated-5.2.0.tgz#e13a1fa112e07f2422cb510c359bb6e5d2ba8f6b" - integrity sha512-Liy5s3CKh2MuSJeVYX7w8mJ0//WMUPm/4ZHRJqRJApijjlXSxcnhHNxIMRLDb8iJNmqaoOi9qMUgK0AkGWuAtA== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/sprite" "^5.2.0" - "@pixi/ticker" "^5.2.0" - -"@pixi/sprite-tiling@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/sprite-tiling/-/sprite-tiling-5.2.0.tgz#194b4be9c7a3a99f4723d4614948efdfe970dab4" - integrity sha512-iLQ98PrUVKqVzTYJsu+ZMCIRsJ1wapg55tf+m/78KK+h0WmgY70CJbO/A68dTqYZMLR39XPCtUp9bXXzXNEEdQ== - dependencies: - "@pixi/constants" "^5.2.0" - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/sprite" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/sprite@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/sprite/-/sprite-5.2.0.tgz#7829a43c801e49a616c20f68179df4336643a304" - integrity sha512-IW+S2Cs3MTcMSrsSA5fjk+xx3Q8eNrsT4hGVXy6JxViv3IknIqbyQwdSFGAyoowOwzhyg7xJExz7VDZRQBBLwg== - dependencies: - "@pixi/constants" "^5.2.0" - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/settings" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/spritesheet@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/spritesheet/-/spritesheet-5.2.0.tgz#bf4c2e85b53fd3a4c8deb6b0f6022300d5cba4f0" - integrity sha512-48WNC3tSUXbWA7ZswEacSiVh396FLe3KLhFpWk2oIJ+7MtMQ1IdtkGjAaXgv0zx0EvvnvEt1VoQVo2eALswR5Q== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/loaders" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/text-bitmap@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/text-bitmap/-/text-bitmap-5.2.0.tgz#a787908ceb8639070b9377704bc3317a11bcf187" - integrity sha512-RZD7GpQrKD+1B2wehnX0dI7ABB43JWNWoWXHl5wKfhjmPCxVmKEB9UfvOZd3sbnlxeL7BUA/gpYSxD6b6ZiA8g== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/loaders" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/settings" "^5.2.0" - "@pixi/sprite" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/text@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/text/-/text-5.2.0.tgz#9b8db4532d353be617f7c60b461214ba1aaf9979" - integrity sha512-enEq/rJYXVobyGeTXCBTbRMlnKc7am+/WicymRt1bT7ia8L8A00xgOdEbfg6OeP2jLcyBVnopFhgHFe8jcp07Q== - dependencies: - "@pixi/core" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/settings" "^5.2.0" - "@pixi/sprite" "^5.2.0" - "@pixi/utils" "^5.2.0" - -"@pixi/ticker@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/ticker/-/ticker-5.2.0.tgz#6e0dae872d0c7dc5458067c10fd6743b0ce15960" - integrity sha512-6xX786cX/RWmQKeRQ3bNvg8JjS0VLA2LQy1sOmUctx2AwdZysI04k2xdw9Krtpn1mkudgAcNrTEsgPeGEjIF9Q== - dependencies: - "@pixi/settings" "^5.2.0" - -"@pixi/utils@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@pixi/utils/-/utils-5.2.0.tgz#11a8f00c6e52292cad7bd37110a4a2ec2571ea6c" - integrity sha512-oMLRlvx+vWHPR06uiOvfOhtkG/LDBR3Syea9QZoIbCJE/GLYgJX8f0cVfrdI0kCgfGj4luc8/CWI745MKafUqQ== - dependencies: - "@pixi/constants" "^5.2.0" - "@pixi/settings" "^5.2.0" +"@pixi/prepare@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/prepare/-/prepare-5.3.3.tgz#a3466ecf5256a5c3fb9b86a555db17cc72d54c87" + integrity sha512-DPsKWfYJ97J67YCjPU6uvU+LBdw+64O9LG9vmzfChmYXom5VMQF9yUC6ZoYTHUPmH31iilqzGeMlPUTobnqSog== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/graphics" "5.3.3" + "@pixi/settings" "5.3.3" + "@pixi/text" "5.3.3" + "@pixi/ticker" "5.3.3" + +"@pixi/runner@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/runner/-/runner-5.3.3.tgz#79fb35b12620d7724c65f4a7aa507190ea825ac0" + integrity sha512-7eLZxxT+PwxuwzcRL1egrnEdLHwD41yFb24pMSo6XM86ppP1tdBjrv5+pLDnUuDEfNjZQxx07FAlZY+sMKANmw== + +"@pixi/settings@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/settings/-/settings-5.3.3.tgz#3ff5f8afc8376d12c7627be043ec317eba139dcd" + integrity sha512-1MYJokqpPUtvYEX0BVi0Pq2Xi6KGmWDV5hlQnTXY9NGv6tmqrPYvIb/uHFaDyVUWmrqsFL3xZ4W5zMo+c/dwVA== + dependencies: + ismobilejs "^1.1.0" + +"@pixi/sprite-animated@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/sprite-animated/-/sprite-animated-5.3.3.tgz#f24949ae04aeff9ff44e22544bc8b7f336d5209e" + integrity sha512-nG5j8veJ/cFXQTgzafPLkZqaHKbuaHcIj+ZYN1I2f31Y85/pfr2PQQLHbGr+3441wOYkEHht9nHhmZHWlOOZ0Q== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/sprite" "5.3.3" + "@pixi/ticker" "5.3.3" + +"@pixi/sprite-tiling@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/sprite-tiling/-/sprite-tiling-5.3.3.tgz#d7306256b7bf6f13c181ea4a2d95905f5ae69b9d" + integrity sha512-+Xk9AUh82rpArtrnZkw+9aJchrmHZ8QkpjsPRJcgPFHx3WEfABIkT6QEoYbRKiYH34OgO7ZOUXy9hcGPHnxjvw== + dependencies: + "@pixi/constants" "5.3.3" + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/sprite" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/sprite@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/sprite/-/sprite-5.3.3.tgz#1681d5fd0a725581bfee3c9c2c490537bf8d21ea" + integrity sha512-qo7DG0oWS1uIBqfxw2jZPn34RCR6gQ+IjZRBpFxZPKPB1cL359scZmDBqBbQ4bd4rJ/6QXQfzUdGhXfQJtc9oQ== + dependencies: + "@pixi/constants" "5.3.3" + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/settings" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/spritesheet@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/spritesheet/-/spritesheet-5.3.3.tgz#e307400d0afe4aa6e1d8d756a519e391706b5f35" + integrity sha512-pTkOCTL8jsmyAguCgcbz03UPYu+3buRkgua1g/vGyeoZBN2eJ04iSXdB0pfPrsPisxkvThGHyU23UqEDYVtXRQ== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/loaders" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/text-bitmap@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/text-bitmap/-/text-bitmap-5.3.3.tgz#0d658473d6e02ce598f779c207c42333741e15bd" + integrity sha512-QRRdEAFBwmRctp8PCPii5WUPM57T1I3r/EwyTvFCCDubOYOZu4aX/iFpCKZMl5GIphDFaGp8mNvbl+BwjUmBCA== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/loaders" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/mesh" "5.3.3" + "@pixi/settings" "5.3.3" + "@pixi/text" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/text@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/text/-/text-5.3.3.tgz#d6fc00c52bc054450ae43e2d5c6f7cedcee9ecd2" + integrity sha512-juinZC2yFXnzucWWxSdty9nfIIOAq2WA8DD2k40YL+7Y5L52/ggkgnokeQ2lrTb1BvTfx6YVNlvAsKonUek0Og== + dependencies: + "@pixi/core" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/settings" "5.3.3" + "@pixi/sprite" "5.3.3" + "@pixi/utils" "5.3.3" + +"@pixi/ticker@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/ticker/-/ticker-5.3.3.tgz#a8766d8417879fffd7507175de869805aee25eb2" + integrity sha512-p5F/dwJGwfZWUg5cCPqOnEx5iYGW+huQlZZtrTKKd1KoVehFsrzHeRBOEp4d584jsOmBf7fjJaUTyzsFn0YtOQ== + dependencies: + "@pixi/settings" "5.3.3" + +"@pixi/utils@5.3.3": + version "5.3.3" + resolved "https://registry.yarnpkg.com/@pixi/utils/-/utils-5.3.3.tgz#525321f3bb00e3e001e341020a3edee94cc0d00a" + integrity sha512-GDP2h1Mph9Uei4zmJjzDK6GZ5S9O2A09VySVfWyKgWwP3SQ/Ss0bGYm4sE6+u1NMSz1WCrLgu66H82XuXs2Cbg== + dependencies: + "@pixi/constants" "5.3.3" + "@pixi/settings" "5.3.3" earcut "^2.1.5" eventemitter3 "^3.1.0" url "^0.11.0" @@ -979,7 +979,7 @@ binary-extensions@^1.0.0: resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.13.1.tgz#598afe54755b2868a5330d2aff9d4ebb53209b65" integrity sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw== -bluebird@^3.5.4: +bluebird@^3.7.2: version "3.7.2" resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f" integrity sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg== @@ -1107,7 +1107,7 @@ collection-visit@^1.0.0: map-visit "^1.0.0" object-visit "^1.0.0" -commander@^2.11.0, commander@~2.20.3: +commander@^2.11.0: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== @@ -1227,10 +1227,10 @@ electron-to-chromium@^1.3.47: resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.95.tgz#79fac438813ca7f3db182a525c2ab432934f6484" integrity sha512-0JZEDKOQAE05EO/4rk3vLAE+PYFI9OLCVLAS4QAq1y+Bb2y1N6MyQJz62ynzHN/y0Ka/nO5jVJcahbCEdfiXLQ== -entities@~1.1.1: - version "1.1.2" - resolved "https://registry.yarnpkg.com/entities/-/entities-1.1.2.tgz#bdfa735299664dfafd34529ed4f8522a275fea56" - integrity sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w== +entities@~2.0.0: + version "2.0.3" + resolved "https://registry.yarnpkg.com/entities/-/entities-2.0.3.tgz#5c487e5742ab93c15abb5da22759b8590ec03b7f" + integrity sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ== es6-promise-polyfill@^1.2.0: version "1.2.0" @@ -1700,10 +1700,10 @@ isarray@1.0.0, isarray@~1.0.0: resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= -ismobilejs@^0.5.1: - version "0.5.1" - resolved "https://registry.yarnpkg.com/ismobilejs/-/ismobilejs-0.5.1.tgz#0e3f825e29e32f84ad5ddbb60e9e04a894046488" - integrity sha512-QX4STsOcBYqlTjVGuAdP1MiRVxtiUbRHOKH0v7Gn1EvfUVIQnrSdgCM4zB4VCZuIejnb2NUMUx0Bwd3EIG6yyA== +ismobilejs@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/ismobilejs/-/ismobilejs-1.1.1.tgz#c56ca0ae8e52b24ca0f22ba5ef3215a2ddbbaa0e" + integrity sha512-VaFW53yt8QO61k2WJui0dHf4SlL8lxBofUuUmwBo0ljPk0Drz2TiuDW4jo3wDcv41qy/SxrJ+VAzJ/qYqsmzRw== isobject@^2.0.0: version "2.1.0" @@ -1727,32 +1727,32 @@ js-tokens@^3.0.2: resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" integrity sha1-mGbfOVECEw449/mWvOtlRDIJwls= -js2xmlparser@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/js2xmlparser/-/js2xmlparser-4.0.0.tgz#ae14cc711b2892083eed6e219fbc993d858bc3a5" - integrity sha512-WuNgdZOXVmBk5kUPMcTcVUpbGRzLfNkv7+7APq7WiDihpXVKrgxo6wwRpRl9OQeEBgKCVk9mR7RbzrnNWC8oBw== +js2xmlparser@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/js2xmlparser/-/js2xmlparser-4.0.1.tgz#670ef71bc5661f089cc90481b99a05a1227ae3bd" + integrity sha512-KrPTolcw6RocpYjdC7pL7v62e55q7qOMHvLX1UCLc5AAS8qeJ6nukarEJAF2KL2PZxlbGueEbINqZR2bDe/gUw== dependencies: - xmlcreate "^2.0.0" + xmlcreate "^2.0.3" -jsdoc@^3.6.3: - version "3.6.3" - resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.6.3.tgz#dccea97d0e62d63d306b8b3ed1527173b5e2190d" - integrity sha512-Yf1ZKA3r9nvtMWHO1kEuMZTlHOF8uoQ0vyo5eH7SQy5YeIiHM+B0DgKnn+X6y6KDYZcF7G2SPkKF+JORCXWE/A== +jsdoc@^3.6.5: + version "3.6.5" + resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.6.5.tgz#e004372ca6f2dcdf19b3d2ebcd7c725528485502" + integrity sha512-SbY+i9ONuxSK35cgVHaI8O9senTE4CDYAmGSDJ5l3+sfe62Ff4gy96osy6OW84t4K4A8iGnMrlRrsSItSNp3RQ== dependencies: - "@babel/parser" "^7.4.4" - bluebird "^3.5.4" + "@babel/parser" "^7.9.4" + bluebird "^3.7.2" catharsis "^0.8.11" escape-string-regexp "^2.0.0" - js2xmlparser "^4.0.0" + js2xmlparser "^4.0.1" klaw "^3.0.0" - markdown-it "^8.4.2" - markdown-it-anchor "^5.0.2" - marked "^0.7.0" - mkdirp "^0.5.1" + markdown-it "^10.0.0" + markdown-it-anchor "^5.2.7" + marked "^0.8.2" + mkdirp "^1.0.4" requizzle "^0.2.3" - strip-json-comments "^3.0.1" + strip-json-comments "^3.1.0" taffydb "2.6.2" - underscore "~1.9.1" + underscore "~1.10.2" jsesc@^1.3.0: version "1.3.0" @@ -1831,26 +1831,26 @@ map-visit@^1.0.0: dependencies: object-visit "^1.0.0" -markdown-it-anchor@^5.0.2: - version "5.2.5" - resolved "https://registry.yarnpkg.com/markdown-it-anchor/-/markdown-it-anchor-5.2.5.tgz#dbf13cfcdbffd16a510984f1263e1d479a47d27a" - integrity sha512-xLIjLQmtym3QpoY9llBgApknl7pxAcN3WDRc2d3rwpl+/YvDZHPmKscGs+L6E05xf2KrCXPBvosWt7MZukwSpQ== +markdown-it-anchor@^5.2.7: + version "5.3.0" + resolved "https://registry.yarnpkg.com/markdown-it-anchor/-/markdown-it-anchor-5.3.0.tgz#d549acd64856a8ecd1bea58365ef385effbac744" + integrity sha512-/V1MnLL/rgJ3jkMWo84UR+K+jF1cxNG1a+KwqeXqTIJ+jtA8aWSHuigx8lTzauiIjBDbwF3NcWQMotd0Dm39jA== -markdown-it@^8.4.2: - version "8.4.2" - resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-8.4.2.tgz#386f98998dc15a37722aa7722084f4020bdd9b54" - integrity sha512-GcRz3AWTqSUphY3vsUqQSFMbgR38a4Lh3GWlHRh/7MRwz8mcu9n2IO7HOh+bXHrR9kOPDl5RNCaEsrneb+xhHQ== +markdown-it@^10.0.0: + version "10.0.0" + resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-10.0.0.tgz#abfc64f141b1722d663402044e43927f1f50a8dc" + integrity sha512-YWOP1j7UbDNz+TumYP1kpwnP0aEa711cJjrAQrzd0UXlbJfc5aAq0F/PZHjiioqDC1NKgvIMX+o+9Bk7yuM2dg== dependencies: argparse "^1.0.7" - entities "~1.1.1" + entities "~2.0.0" linkify-it "^2.0.0" mdurl "^1.0.1" uc.micro "^1.0.5" -marked@^0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/marked/-/marked-0.7.0.tgz#b64201f051d271b1edc10a04d1ae9b74bb8e5c0e" - integrity sha512-c+yYdCZJQrsRjTPhUx7VKkApw9bwDkNbHUKo1ovgcfDjb2kc8rLuRbIFyXL5WOEUwzSSKo3IXpph2K6DqB/KZg== +marked@^0.8.2: + version "0.8.2" + resolved "https://registry.yarnpkg.com/marked/-/marked-0.8.2.tgz#4faad28d26ede351a7a1aaa5fec67915c869e355" + integrity sha512-EGwzEeCcLniFX51DhTpmTom+dSA/MG/OBUDjnWtHbEnjAH180VzUeAw+oE4+Zv+CoYBWyRlYOTR0N8SO9R1PVw== math-random@^1.0.1: version "1.0.4" @@ -1952,6 +1952,11 @@ mkdirp@^0.5.0, mkdirp@^0.5.1: dependencies: minimist "0.0.8" +mkdirp@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" + integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== + ms@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" @@ -2159,52 +2164,52 @@ penner@^0.1.3: resolved "https://registry.yarnpkg.com/penner/-/penner-0.1.3.tgz#0b8b482d4e9b39af2f3d7c37592229b8acc29705" integrity sha1-C4tILU6bOa8vPXw3WSIpuKzClwU= -pixi-viewport@^4.4.1: - version "4.4.1" - resolved "https://registry.yarnpkg.com/pixi-viewport/-/pixi-viewport-4.4.1.tgz#a708cce8ded33584514a3415f8257affeca53180" - integrity sha512-7IhgLxBPG7jkO25Lmq58rNvzpXbQF/MdizuPEfIQEH3LRSjYEJawmjhA4QpsBfSVT+WTl8w9XmOR6os2OEyBhg== +pixi-viewport@^4.13.2: + version "4.13.2" + resolved "https://registry.yarnpkg.com/pixi-viewport/-/pixi-viewport-4.13.2.tgz#3f470c0e531a3c81c8a7636288dad0f021b4146e" + integrity sha512-1yMSSEJrIQLH9QYxsKdyJpqnKCJHtqt36+BFfPRxcNMuraRGlAWm3pqZVYObMYnMSLpGHytErMrr3HieasTIAA== dependencies: penner "^0.1.3" -pixi.js@5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/pixi.js/-/pixi.js-5.2.0.tgz#097eb90825cd28e40230c779998876d575d02b69" - integrity sha512-q4gxbTU51nrh8qxbplU6EVx2dnb9SiI9OeQOrQmtmCTpysJXAK5p9M2c3v5JRIgK8ZCL74y5vrwHaaB1ZQoPKw== - dependencies: - "@pixi/accessibility" "^5.2.0" - "@pixi/app" "^5.2.0" - "@pixi/constants" "^5.2.0" - "@pixi/core" "^5.2.0" - "@pixi/display" "^5.2.0" - "@pixi/extract" "^5.2.0" - "@pixi/filter-alpha" "^5.2.0" - "@pixi/filter-blur" "^5.2.0" - "@pixi/filter-color-matrix" "^5.2.0" - "@pixi/filter-displacement" "^5.2.0" - "@pixi/filter-fxaa" "^5.2.0" - "@pixi/filter-noise" "^5.2.0" - "@pixi/graphics" "^5.2.0" - "@pixi/interaction" "^5.2.0" - "@pixi/loaders" "^5.2.0" - "@pixi/math" "^5.2.0" - "@pixi/mesh" "^5.2.0" - "@pixi/mesh-extras" "^5.2.0" - "@pixi/mixin-cache-as-bitmap" "^5.2.0" - "@pixi/mixin-get-child-by-name" "^5.2.0" - "@pixi/mixin-get-global-position" "^5.2.0" - "@pixi/particles" "^5.2.0" - "@pixi/polyfill" "^5.2.0" - "@pixi/prepare" "^5.2.0" - "@pixi/runner" "^5.2.0" - "@pixi/settings" "^5.2.0" - "@pixi/sprite" "^5.2.0" - "@pixi/sprite-animated" "^5.2.0" - "@pixi/sprite-tiling" "^5.2.0" - "@pixi/spritesheet" "^5.2.0" - "@pixi/text" "^5.2.0" - "@pixi/text-bitmap" "^5.2.0" - "@pixi/ticker" "^5.2.0" - "@pixi/utils" "^5.2.0" +pixi.js@5.3.3: + version "5.3.3" + resolved "https://registry.yarnpkg.com/pixi.js/-/pixi.js-5.3.3.tgz#6e326a52542f4acd97ea3f8593cb0aeae502df9a" + integrity sha512-uFQOXXyPMAVVayDebSFBS1AFfPT6QYNuz9Vu11yI2/k1DAef/rbYoJpSMM6SeB6dezDJPtIAaXXNxdaYzbe+kg== + dependencies: + "@pixi/accessibility" "5.3.3" + "@pixi/app" "5.3.3" + "@pixi/constants" "5.3.3" + "@pixi/core" "5.3.3" + "@pixi/display" "5.3.3" + "@pixi/extract" "5.3.3" + "@pixi/filter-alpha" "5.3.3" + "@pixi/filter-blur" "5.3.3" + "@pixi/filter-color-matrix" "5.3.3" + "@pixi/filter-displacement" "5.3.3" + "@pixi/filter-fxaa" "5.3.3" + "@pixi/filter-noise" "5.3.3" + "@pixi/graphics" "5.3.3" + "@pixi/interaction" "5.3.3" + "@pixi/loaders" "5.3.3" + "@pixi/math" "5.3.3" + "@pixi/mesh" "5.3.3" + "@pixi/mesh-extras" "5.3.3" + "@pixi/mixin-cache-as-bitmap" "5.3.3" + "@pixi/mixin-get-child-by-name" "5.3.3" + "@pixi/mixin-get-global-position" "5.3.3" + "@pixi/particles" "5.3.3" + "@pixi/polyfill" "5.3.3" + "@pixi/prepare" "5.3.3" + "@pixi/runner" "5.3.3" + "@pixi/settings" "5.3.3" + "@pixi/sprite" "5.3.3" + "@pixi/sprite-animated" "5.3.3" + "@pixi/sprite-tiling" "5.3.3" + "@pixi/spritesheet" "5.3.3" + "@pixi/text" "5.3.3" + "@pixi/text-bitmap" "5.3.3" + "@pixi/ticker" "5.3.3" + "@pixi/utils" "5.3.3" posix-character-classes@^0.1.0: version "0.1.1" @@ -2511,11 +2516,6 @@ source-map@^0.5.6, source-map@^0.5.7: resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= -source-map@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" - integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== - split-string@^3.0.1, split-string@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2" @@ -2574,10 +2574,10 @@ strip-ansi@^4.0.0: dependencies: ansi-regex "^3.0.0" -strip-json-comments@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.0.1.tgz#85713975a91fb87bf1b305cca77395e40d2a64a7" - integrity sha512-VTyMAUfdm047mwKl+u79WIdrZxtFtn+nBxHeb844XBQ9uMNTuTHdx2hc5RiAJYqwTj3wc/xe5HLSdJSkJ+WfZw== +strip-json-comments@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" + integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== strip-json-comments@~2.0.1: version "2.0.1" @@ -2657,19 +2657,21 @@ uc.micro@^1.0.1, uc.micro@^1.0.5: resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac" integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== -uglify-js@^3.7.2: - version "3.7.2" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.7.2.tgz#cb1a601e67536e9ed094a92dd1e333459643d3f9" - integrity sha512-uhRwZcANNWVLrxLfNFEdltoPNhECUR3lc+UdJoG9CBpMcSnKyWA94tc3eAujB1GcMY5Uwq8ZMp4qWpxWYDQmaA== - dependencies: - commander "~2.20.3" - source-map "~0.6.1" +uglify-js@^3.10.1: + version "3.10.1" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.10.1.tgz#dd14767eb7150de97f2573a5ff210db14fffe4ad" + integrity sha512-RjxApKkrPJB6kjJxQS3iZlf///REXWYxYJxO/MpmlQzVkDWVI3PSnCBWezMecmTU/TRkNxrl8bmsfFQCp+LO+Q== -underscore@^1.7.0, underscore@~1.9.1: +underscore@^1.7.0: version "1.9.1" resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.9.1.tgz#06dce34a0e68a7babc29b365b8e74b8925203961" integrity sha512-5/4etnCkd9c8gwgowi5/om/mYO5ajCaOgdzj/oW+0eQV9WxKBDZw5+ycmKmeaTXjInS/W0BzpGLo2xR2aBwZdg== +underscore@~1.10.2: + version "1.10.2" + resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.10.2.tgz#73d6aa3668f3188e4adb0f1943bd12cfd7efaaaf" + integrity sha512-N4P+Q/BuyuEKFJ43B9gYuOj4TQUHXX+j2FqguVOpjkssLUUrnJofCcBccJSCoeturDoZU6GorDTHSvUDlSQbTg== + union-value@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847" @@ -2735,10 +2737,10 @@ wrappy@1: resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= -xmlcreate@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/xmlcreate/-/xmlcreate-2.0.1.tgz#2ec38bd7b708d213fd1a90e2431c4af9c09f6a52" - integrity sha512-MjGsXhKG8YjTKrDCXseFo3ClbMGvUD4en29H2Cev1dv4P/chlpw6KdYmlCWDkhosBVKRDjM836+3e3pm1cBNJA== +xmlcreate@^2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/xmlcreate/-/xmlcreate-2.0.3.tgz#df9ecd518fd3890ab3548e1b811d040614993497" + integrity sha512-HgS+X6zAztGa9zIK3Y3LXuJes33Lz9x+YyTxgrkIdabu2vqcGOWwdfCpf1hWLRrd553wd4QCDf6BBO6FfdsRiQ== yallist@^3.0.0, yallist@^3.0.3: version "3.1.1"