/*!
 * pixi.js - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * pixi.js is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */
var PIXI = (function (exports) {
  'use strict';

  /**
   * @this {Promise}
   */
  function finallyConstructor(callback) {
    var constructor = this.constructor;
    return this.then(
      function(value) {
        // @ts-ignore
        return constructor.resolve(callback()).then(function() {
          return value;
        });
      },
      function(reason) {
        // @ts-ignore
        return constructor.resolve(callback()).then(function() {
          // @ts-ignore
          return constructor.reject(reason);
        });
      }
    );
  }

  function allSettled(arr) {
    var P = this;
    return new P(function(resolve, reject) {
      if (!(arr && typeof arr.length !== 'undefined')) {
        return reject(
          new TypeError(
            typeof arr +
              ' ' +
              arr +
              ' is not iterable(cannot read property Symbol(Symbol.iterator))'
          )
        );
      }
      var args = Array.prototype.slice.call(arr);
      if (args.length === 0) { return resolve([]); }
      var remaining = args.length;

      function res(i, val) {
        if (val && (typeof val === 'object' || typeof val === 'function')) {
          var then = val.then;
          if (typeof then === 'function') {
            then.call(
              val,
              function(val) {
                res(i, val);
              },
              function(e) {
                args[i] = { status: 'rejected', reason: e };
                if (--remaining === 0) {
                  resolve(args);
                }
              }
            );
            return;
          }
        }
        args[i] = { status: 'fulfilled', value: val };
        if (--remaining === 0) {
          resolve(args);
        }
      }

      for (var i = 0; i < args.length; i++) {
        res(i, args[i]);
      }
    });
  }

  // Store setTimeout reference so promise-polyfill will be unaffected by
  // other code modifying setTimeout (like sinon.useFakeTimers())
  var setTimeoutFunc = setTimeout;

  function isArray(x) {
    return Boolean(x && typeof x.length !== 'undefined');
  }

  function noop() {}

  // Polyfill for Function.prototype.bind
  function bind(fn, thisArg) {
    return function() {
      fn.apply(thisArg, arguments);
    };
  }

  /**
   * @constructor
   * @param {Function} fn
   */
  function Promise$1(fn) {
    if (!(this instanceof Promise$1))
      { throw new TypeError('Promises must be constructed via new'); }
    if (typeof fn !== 'function') { throw new TypeError('not a function'); }
    /** @type {!number} */
    this._state = 0;
    /** @type {!boolean} */
    this._handled = false;
    /** @type {Promise|undefined} */
    this._value = undefined;
    /** @type {!Array<!Function>} */
    this._deferreds = [];

    doResolve(fn, this);
  }

  function handle(self, deferred) {
    while (self._state === 3) {
      self = self._value;
    }
    if (self._state === 0) {
      self._deferreds.push(deferred);
      return;
    }
    self._handled = true;
    Promise$1._immediateFn(function() {
      var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
      if (cb === null) {
        (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
        return;
      }
      var ret;
      try {
        ret = cb(self._value);
      } catch (e) {
        reject(deferred.promise, e);
        return;
      }
      resolve(deferred.promise, ret);
    });
  }

  function resolve(self, newValue) {
    try {
      // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
      if (newValue === self)
        { throw new TypeError('A promise cannot be resolved with itself.'); }
      if (
        newValue &&
        (typeof newValue === 'object' || typeof newValue === 'function')
      ) {
        var then = newValue.then;
        if (newValue instanceof Promise$1) {
          self._state = 3;
          self._value = newValue;
          finale(self);
          return;
        } else if (typeof then === 'function') {
          doResolve(bind(then, newValue), self);
          return;
        }
      }
      self._state = 1;
      self._value = newValue;
      finale(self);
    } catch (e) {
      reject(self, e);
    }
  }

  function reject(self, newValue) {
    self._state = 2;
    self._value = newValue;
    finale(self);
  }

  function finale(self) {
    if (self._state === 2 && self._deferreds.length === 0) {
      Promise$1._immediateFn(function() {
        if (!self._handled) {
          Promise$1._unhandledRejectionFn(self._value);
        }
      });
    }

    for (var i = 0, len = self._deferreds.length; i < len; i++) {
      handle(self, self._deferreds[i]);
    }
    self._deferreds = null;
  }

  /**
   * @constructor
   */
  function Handler(onFulfilled, onRejected, promise) {
    this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
    this.onRejected = typeof onRejected === 'function' ? onRejected : null;
    this.promise = promise;
  }

  /**
   * Take a potentially misbehaving resolver function and make sure
   * onFulfilled and onRejected are only called once.
   *
   * Makes no guarantees about asynchrony.
   */
  function doResolve(fn, self) {
    var done = false;
    try {
      fn(
        function(value) {
          if (done) { return; }
          done = true;
          resolve(self, value);
        },
        function(reason) {
          if (done) { return; }
          done = true;
          reject(self, reason);
        }
      );
    } catch (ex) {
      if (done) { return; }
      done = true;
      reject(self, ex);
    }
  }

  Promise$1.prototype['catch'] = function(onRejected) {
    return this.then(null, onRejected);
  };

  Promise$1.prototype.then = function(onFulfilled, onRejected) {
    // @ts-ignore
    var prom = new this.constructor(noop);

    handle(this, new Handler(onFulfilled, onRejected, prom));
    return prom;
  };

  Promise$1.prototype['finally'] = finallyConstructor;

  Promise$1.all = function(arr) {
    return new Promise$1(function(resolve, reject) {
      if (!isArray(arr)) {
        return reject(new TypeError('Promise.all accepts an array'));
      }

      var args = Array.prototype.slice.call(arr);
      if (args.length === 0) { return resolve([]); }
      var remaining = args.length;

      function res(i, val) {
        try {
          if (val && (typeof val === 'object' || typeof val === 'function')) {
            var then = val.then;
            if (typeof then === 'function') {
              then.call(
                val,
                function(val) {
                  res(i, val);
                },
                reject
              );
              return;
            }
          }
          args[i] = val;
          if (--remaining === 0) {
            resolve(args);
          }
        } catch (ex) {
          reject(ex);
        }
      }

      for (var i = 0; i < args.length; i++) {
        res(i, args[i]);
      }
    });
  };

  Promise$1.allSettled = allSettled;

  Promise$1.resolve = function(value) {
    if (value && typeof value === 'object' && value.constructor === Promise$1) {
      return value;
    }

    return new Promise$1(function(resolve) {
      resolve(value);
    });
  };

  Promise$1.reject = function(value) {
    return new Promise$1(function(resolve, reject) {
      reject(value);
    });
  };

  Promise$1.race = function(arr) {
    return new Promise$1(function(resolve, reject) {
      if (!isArray(arr)) {
        return reject(new TypeError('Promise.race accepts an array'));
      }

      for (var i = 0, len = arr.length; i < len; i++) {
        Promise$1.resolve(arr[i]).then(resolve, reject);
      }
    });
  };

  // Use polyfill for setImmediate for performance gains
  Promise$1._immediateFn =
    // @ts-ignore
    (typeof setImmediate === 'function' &&
      function(fn) {
        // @ts-ignore
        setImmediate(fn);
      }) ||
    function(fn) {
      setTimeoutFunc(fn, 0);
    };

  Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) {
    if (typeof console !== 'undefined' && console) {
      console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
    }
  };

  /*
  object-assign
  (c) Sindre Sorhus
  @license MIT
  */

  '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;
  		}

  		return true;
  	} catch (err) {
  		// We don't expect any of the above to throw, but better to be safe.
  		return false;
  	}
  }

  var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  	var arguments$1 = arguments;

  	var from;
  	var to = toObject(target);
  	var symbols;

  	for (var s = 1; s < arguments.length; s++) {
  		from = Object(arguments$1[s]);

  		for (var key in from) {
  			if (hasOwnProperty.call(from, key)) {
  				to[key] = from[key];
  			}
  		}

  		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]];
  				}
  			}
  		}
  	}

  	return to;
  };

  /*!
   * @pixi/polyfill - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/polyfill is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  if (typeof globalThis === 'undefined') {
      if (typeof self !== 'undefined') {
          // covers browsers
          // @ts-expect-error not-writable ts(2540) error only on node
          self.globalThis = self;
      }
      else if (typeof global !== 'undefined') {
          // covers versions of Node < 12
          // @ts-expect-error not-writable ts(2540) error only on node
          global.globalThis = global;
      }
  }

  // Support for IE 9 - 11 which does not include Promises
  if (!globalThis.Promise) {
      globalThis.Promise = Promise$1;
  }

  // References:
  if (!Object.assign) {
      Object.assign = objectAssign;
  }

  // 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`, `globalThis`, 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 (!(globalThis.performance && globalThis.performance.now)) {
      var startTime_1 = Date.now();
      if (!globalThis.performance) {
          globalThis.performance = {};
      }
      globalThis.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 && !globalThis.requestAnimationFrame; ++x) {
      var p = vendors[x];
      globalThis.requestAnimationFrame = globalThis[p + "RequestAnimationFrame"];
      globalThis.cancelAnimationFrame = globalThis[p + "CancelAnimationFrame"]
          || globalThis[p + "CancelRequestAnimationFrame"];
  }
  if (!globalThis.requestAnimationFrame) {
      globalThis.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 globalThis.self.setTimeout(function () {
              lastTime = Date.now();
              callback(performance.now());
          }, delay);
      };
  }
  if (!globalThis.cancelAnimationFrame) {
      globalThis.cancelAnimationFrame = function (id) { return clearTimeout(id); };
  }

  // 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;
      };
  }

  // 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;
      };
  }

  if (!globalThis.ArrayBuffer) {
      globalThis.ArrayBuffer = Array;
  }
  if (!globalThis.Float32Array) {
      globalThis.Float32Array = Array;
  }
  if (!globalThis.Uint32Array) {
      globalThis.Uint32Array = Array;
  }
  if (!globalThis.Uint16Array) {
      globalThis.Uint16Array = Array;
  }
  if (!globalThis.Uint8Array) {
      globalThis.Uint8Array = Array;
  }
  if (!globalThis.Int32Array) {
      globalThis.Int32Array = Array;
  }

  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;
  }

  /*!
   * @pixi/settings - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/settings is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  // The ESM/CJS versions of ismobilejs only
  var isMobile$1 = isMobile(globalThis.navigator);

  /**
   * 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$1.tablet || isMobile$1.phone) {
          if (isMobile$1.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;
                  }
              }
          }
          if (isMobile$1.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;
                  }
              }
          }
      }
      return allowMax ? max : 4;
  }

  /**
   * 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$1.apple.device;
  }

  /*!
   * @pixi/constants - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/constants is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */
  /**
   * 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} RG=33319
   * @property {number} RED=6403
   * @property {number} RGBA_INTEGER=36249
   * @property {number} RGB_INTEGER=36248
   * @property {number} RG_INTEGER=33320
   * @property {number} RED_INTEGER=36244
   * @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["RG"] = 33319] = "RG";
      FORMATS[FORMATS["RED"] = 6403] = "RED";
      FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
      FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
      FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
      FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
      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} UNSIGNED_INT=5125
   * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
   * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
   * @property {number} UNSIGNED_INT_24_8=34042
   * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
   * @property {number} BYTE=5120
   * @property {number} SHORT=5122
   * @property {number} INT=5124
   * @property {number} FLOAT=5126
   * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
   * @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["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
      TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
      TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
      TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
      TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
      TYPES[TYPES["BYTE"] = 5120] = "BYTE";
      TYPES[TYPES["SHORT"] = 5122] = "SHORT";
      TYPES[TYPES["INT"] = 5124] = "INT";
      TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
      TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
      TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
  })(TYPES || (TYPES = {}));
  /**
   * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
   * WebGL1 works only with FLOAT.
   *
   * @memberof PIXI
   * @static
   * @name SAMPLER_TYPES
   * @enum {number}
   * @property {number} FLOAT=0
   * @property {number} INT=1
   * @property {number} UINT=2
   */
  var SAMPLER_TYPES;
  (function (SAMPLER_TYPES) {
      SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
      SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
      SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
  })(SAMPLER_TYPES || (SAMPLER_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
   * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
   *   that supports buffering each level-of-detail.
   */
  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["ON_MANUAL"] = 3] = "ON_MANUAL";
  })(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["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
  })(ALPHA_MODES || (ALPHA_MODES = {}));
  /**
   * Configure whether filter textures are cleared after binding.
   *
   * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
   * this and skip clearing as an optimization.
   *
   * @name CLEAR_MODES
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
   * @property {number} CLEAR - Always clear the filter texture.
   * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
   * @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 = {}));
  /**
   * Constants for various buffer types in Pixi
   *
   * @see PIXI.BUFFER_TYPE
   *
   * @name BUFFER_TYPE
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
   * @property {number} ARRAY_BUFFER - buffer type for using attribute data
   * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
   */
  var BUFFER_TYPE;
  (function (BUFFER_TYPE) {
      BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
      BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
      // NOT YET SUPPORTED
      BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
  })(BUFFER_TYPE || (BUFFER_TYPE = {}));

  /**
   * 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 = {
      /**
       * 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: MIPMAP_MODES.POW2,
      /**
       * 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,
      /**
       * Default resolution / device pixel ratio of the renderer.
       *
       * @static
       * @name RESOLUTION
       * @memberof PIXI.settings
       * @type {number}
       * @default 1
       */
      RESOLUTION: 1,
      /**
       * Default filter resolution.
       *
       * @static
       * @name FILTER_RESOLUTION
       * @memberof PIXI.settings
       * @type {number}
       * @default 1
       */
      FILTER_RESOLUTION: 1,
      /**
       * Default filter samples.
       *
       * @static
       * @name FILTER_MULTISAMPLE
       * @memberof PIXI.settings
       * @type {PIXI.MSAA_QUALITY}
       * @default PIXI.MSAA_QUALITY.NONE
       */
      FILTER_MULTISAMPLE: MSAA_QUALITY.NONE,
      /**
       * The maximum textures that this device supports.
       *
       * @static
       * @name SPRITE_MAX_TEXTURES
       * @memberof PIXI.settings
       * @type {number}
       * @default 32
       */
      SPRITE_MAX_TEXTURES: maxRecommendedTextures(32),
      // TODO: maybe change to SPRITE.BATCH_SIZE: 2000
      // TODO: maybe add PARTICLE.BATCH_SIZE: 15000
      /**
       * 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,
      /**
       * 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 {boolean} antialias=false
       * @property {boolean} autoDensity=false
       * @property {boolean} useContextAlpha=true
       * @property {number} backgroundColor=0x000000
       * @property {number} backgroundAlpha=1
       * @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,
          autoDensity: false,
          backgroundColor: 0x000000,
          backgroundAlpha: 1,
          useContextAlpha: true,
          clearBeforeRender: true,
          preserveDrawingBuffer: false,
          width: 800,
          height: 600,
          legacy: false,
      },
      /**
       * Default Garbage Collection mode.
       *
       * @static
       * @name GC_MODE
       * @memberof PIXI.settings
       * @type {PIXI.GC_MODES}
       * @default PIXI.GC_MODES.AUTO
       */
      GC_MODE: GC_MODES.AUTO,
      /**
       * Default Garbage Collection max idle.
       *
       * @static
       * @name GC_MAX_IDLE
       * @memberof PIXI.settings
       * @type {number}
       * @default 3600
       */
      GC_MAX_IDLE: 60 * 60,
      /**
       * 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,
      /**
       * 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: WRAP_MODES.CLAMP,
      /**
       * Default scale mode for textures.
       *
       * @static
       * @name SCALE_MODE
       * @memberof PIXI.settings
       * @type {PIXI.SCALE_MODES}
       * @default PIXI.SCALE_MODES.LINEAR
       */
      SCALE_MODE: SCALE_MODES.LINEAR,
      /**
       * Default specify float precision in vertex shader.
       *
       * @static
       * @name PRECISION_VERTEX
       * @memberof PIXI.settings
       * @type {PIXI.PRECISION}
       * @default PIXI.PRECISION.HIGH
       */
      PRECISION_VERTEX: PRECISION.HIGH,
      /**
       * 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$1.apple.device ? PRECISION.HIGH : PRECISION.MEDIUM,
      /**
       * 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(),
      /**
       * 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,
  };

  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

  function getDefaultExportFromCjs (x) {
  	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  }

  function createCommonjsModule(fn, basedir, module) {
  	return module = {
  		path: basedir,
  		exports: {},
  		require: function (path, base) {
  			return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  		}
  	}, fn(module, module.exports), module.exports;
  }

  function getDefaultExportFromNamespaceIfPresent (n) {
  	return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
  }

  function getDefaultExportFromNamespaceIfNotNamed (n) {
  	return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
  }

  function getAugmentedNamespace(n) {
  	if (n.__esModule) return n;
  	var a = Object.defineProperty({}, '__esModule', {value: true});
  	Object.keys(n).forEach(function (k) {
  		var d = Object.getOwnPropertyDescriptor(n, k);
  		Object.defineProperty(a, k, d.get ? d : {
  			enumerable: true,
  			get: function () {
  				return n[k];
  			}
  		});
  	});
  	return a;
  }

  function commonjsRequire () {
  	throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  }

  var eventemitter3 = createCommonjsModule(function (module) {
  '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 arguments$1 = arguments;

    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;
      }

      for (i = 1, args = new Array(len -1); i < len; i++) {
        args[i - 1] = arguments$1[i];
      }

      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$1[j];
            } }

            listeners[i].fn.apply(listeners[i].context, args);
        }
      }
    }

    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);
  };

  /**
   * Add a one-time 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.once = function once(event, fn, context) {
    return addListener(this, event, fn, context, true);
  };

  /**
   * 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
   */
  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.
   *
   * @param {(String|Symbol)} [event] The event name.
   * @returns {EventEmitter} `this`.
   * @public
   */
  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' !== 'object') {
    module.exports = EventEmitter;
  }
  });

  'use strict';

  var earcut_1 = earcut;
  var _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);

          // filter collinear points around the cuts
          filterPoints(outerNode, outerNode.next);
          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;
  };
  earcut_1.default = _default;

  var punycode = createCommonjsModule(function (module, exports) {
  /*! https://mths.be/punycode v1.3.2 by @mathias */
  ;(function(root) {

  	/** Detect free variables */
  	var freeExports = 'object' == 'object' && exports &&
  		!exports.nodeType && exports;
  	var freeModule = 'object' == 'object' && module &&
  		!module.nodeType && module;
  	var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
  	if (
  		freeGlobal.global === freeGlobal ||
  		freeGlobal.window === freeGlobal ||
  		freeGlobal.self === freeGlobal
  	) {
  		root = freeGlobal;
  	}

  	/**
  	 * The `punycode` object.
  	 * @name punycode
  	 * @type Object
  	 */
  	var punycode,

  	/** Highest positive signed 32-bit float value */
  	maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1

  	/** Bootstring parameters */
  	base = 36,
  	tMin = 1,
  	tMax = 26,
  	skew = 38,
  	damp = 700,
  	initialBias = 72,
  	initialN = 128, // 0x80
  	delimiter = '-', // '\x2D'

  	/** 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 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 <https://mathiasbynens.be/notes/javascript-encoding>
  	 * @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;
  	}

  	/**
  	 * 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);
  	}

  	/**
  	 * Bias adaptation function as per section 3.4 of RFC 3492.
  	 * http://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;

  		// 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.

  		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));
  		}

  		// Main decoding loop: start just after the last delimiter if any basic code
  		// points were copied; start at the beginning otherwise.

  		for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {

  			// `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 (index >= inputLength) {
  					error('invalid-input');
  				}

  				digit = basicToDigit(input.charCodeAt(index++));

  				if (digit >= base || digit > floor((maxInt - i) / w)) {
  					error('overflow');
  				}

  				i += digit * w;
  				t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);

  				if (digit < t) {
  					break;
  				}

  				baseMinusT = base - t;
  				if (w > floor(maxInt / baseMinusT)) {
  					error('overflow');
  				}

  				w *= baseMinusT;

  			}

  			out = output.length + 1;
  			bias = adapt(i - oldi, out, oldi == 0);

  			// `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');
  			}

  			n += floor(i / out);
  			i %= out;

  			// Insert `n` at position `i` of the output
  			output.splice(i++, 0, n);

  		}

  		return ucs2encode(output);
  	}

  	/**
  	 * 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;

  		// Convert the input in UCS-2 to Unicode
  		input = ucs2decode(input);

  		// Cache the length
  		inputLength = input.length;

  		// Initialize the state
  		n = initialN;
  		delta = 0;
  		bias = initialBias;

  		// Handle the basic code points
  		for (j = 0; j < inputLength; ++j) {
  			currentValue = input[j];
  			if (currentValue < 0x80) {
  				output.push(stringFromCharCode(currentValue));
  			}
  		}

  		handledCPCount = basicLength = output.length;

  		// `handledCPCount` is the number of code points that have been handled;
  		// `basicLength` is the number of basic code points.

  		// 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 <n,i> state to <m,0>,
  			// 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.3.2',
  		/**
  		 * An object of methods to convert from JavaScript's internal character
  		 * representation (UCS-2) to Unicode code points, and back.
  		 * @see <https://mathiasbynens.be/notes/javascript-encoding>
  		 * @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 undefined == 'function' &&
  		typeof undefined.amd == 'object' &&
  		undefined.amd
  	) {
  		undefined('punycode', function() {
  			return punycode;
  		});
  	} else if (freeExports && freeModule) {
  		if (module.exports == freeExports) { // in Node.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;
  	}

  }(commonjsGlobal));
  });

  'use strict';

  var util = {
    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;
    }
  };

  // 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$1(obj, prop) {
    return Object.prototype.hasOwnProperty.call(obj, prop);
  }

  var decode = function(qs, sep, eq, options) {
    sep = sep || '&';
    eq = eq || '=';
    var obj = {};

    if (typeof qs !== 'string' || qs.length === 0) {
      return obj;
    }

    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 = '';
      }

      k = decodeURIComponent(kstr);
      v = decodeURIComponent(vstr);

      if (!hasOwnProperty$1(obj, k)) {
        obj[k] = v;
      } else if (Array.isArray(obj[k])) {
        obj[k].push(v);
      } else {
        obj[k] = [obj[k], v];
      }
    }

    return obj;
  };

  // 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 stringifyPrimitive = function(v) {
    switch (typeof v) {
      case 'string':
        return v;

      case 'boolean':
        return v ? 'true' : 'false';

      case 'number':
        return isFinite(v) ? v : '';

      default:
        return '';
    }
  };

  var encode = function(obj, sep, eq, name) {
    sep = sep || '&';
    eq = eq || '=';
    if (obj === null) {
      obj = undefined;
    }

    if (typeof obj === 'object') {
      return Object.keys(obj).map(function(k) {
        var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
        if (Array.isArray(obj[k])) {
          return obj[k].map(function(v) {
            return ks + encodeURIComponent(stringifyPrimitive(v));
          }).join(sep);
        } else {
          return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
        }
      }).join(sep);

    }

    if (!name) { return ''; }
    return encodeURIComponent(stringifyPrimitive(name)) + eq +
           encodeURIComponent(stringifyPrimitive(obj));
  };

  var querystring = createCommonjsModule(function (module, exports) {
  'use strict';

  exports.decode = exports.parse = decode;
  exports.encode = exports.stringify = encode;
  });

  // 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 parse = urlParse;
  var resolve$1 = urlResolve;
  var resolveObject = urlResolveObject;
  var format = urlFormat;

  var Url_1 = 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
      };

  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);
          }
        } 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;
            }
          }
        }
      }

      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 = '';

    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;
      }
    }

    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);
  }

  Url.prototype.resolve = function(relative) {
    return this.resolveObject(urlParse(relative, false, true)).format();
  };

  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; }
  };

  var url = {
  	parse: parse,
  	resolve: resolve$1,
  	resolveObject: resolveObject,
  	format: format,
  	Url: Url_1
  };

  /*!
   * @pixi/constants - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/constants is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */
  /**
   * 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 = {}));
  /**
   * 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.
   */

  (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 = {}));
  /**
   * 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.
   */

  (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 = {}));
  /**
   * 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
   */

  (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 = {}));
  /**
   * 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
   */

  (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 = {}));
  /**
   * Various GL texture/resources formats.
   *
   * @memberof PIXI
   * @static
   * @name FORMATS
   * @enum {number}
   * @property {number} RGBA=6408
   * @property {number} RGB=6407
   * @property {number} RG=33319
   * @property {number} RED=6403
   * @property {number} RGBA_INTEGER=36249
   * @property {number} RGB_INTEGER=36248
   * @property {number} RG_INTEGER=33320
   * @property {number} RED_INTEGER=36244
   * @property {number} ALPHA=6406
   * @property {number} LUMINANCE=6409
   * @property {number} LUMINANCE_ALPHA=6410
   * @property {number} DEPTH_COMPONENT=6402
   * @property {number} DEPTH_STENCIL=34041
   */

  (function (FORMATS) {
      FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
      FORMATS[FORMATS["RGB"] = 6407] = "RGB";
      FORMATS[FORMATS["RG"] = 33319] = "RG";
      FORMATS[FORMATS["RED"] = 6403] = "RED";
      FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
      FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
      FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
      FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
      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 = {}));
  /**
   * 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
   */

  (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 = {}));
  /**
   * 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} UNSIGNED_INT=5125
   * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
   * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
   * @property {number} UNSIGNED_INT_24_8=34042
   * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
   * @property {number} BYTE=5120
   * @property {number} SHORT=5122
   * @property {number} INT=5124
   * @property {number} FLOAT=5126
   * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
   * @property {number} HALF_FLOAT=36193
   */

  (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["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
      TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
      TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
      TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
      TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
      TYPES[TYPES["BYTE"] = 5120] = "BYTE";
      TYPES[TYPES["SHORT"] = 5122] = "SHORT";
      TYPES[TYPES["INT"] = 5124] = "INT";
      TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
      TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
      TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
  })(exports.TYPES || (exports.TYPES = {}));
  /**
   * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
   * WebGL1 works only with FLOAT.
   *
   * @memberof PIXI
   * @static
   * @name SAMPLER_TYPES
   * @enum {number}
   * @property {number} FLOAT=0
   * @property {number} INT=1
   * @property {number} UINT=2
   */

  (function (SAMPLER_TYPES) {
      SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
      SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
      SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
  })(exports.SAMPLER_TYPES || (exports.SAMPLER_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
   */

  (function (SCALE_MODES) {
      SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
      SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
  })(exports.SCALE_MODES || (exports.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
   */

  (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 = {}));
  /**
   * 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
   * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
   *   that supports buffering each level-of-detail.
   */

  (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["ON_MANUAL"] = 3] = "ON_MANUAL";
  })(exports.MIPMAP_MODES || (exports.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.
   */

  (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["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
  })(exports.ALPHA_MODES || (exports.ALPHA_MODES = {}));
  /**
   * Configure whether filter textures are cleared after binding.
   *
   * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
   * this and skip clearing as an optimization.
   *
   * @name CLEAR_MODES
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
   * @property {number} CLEAR - Always clear the filter texture.
   * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
   * @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
   */

  (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 = {}));
  /**
   * 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
   */

  (function (GC_MODES) {
      GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
      GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
  })(exports.GC_MODES || (exports.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'
   */

  (function (PRECISION) {
      PRECISION["LOW"] = "lowp";
      PRECISION["MEDIUM"] = "mediump";
      PRECISION["HIGH"] = "highp";
  })(exports.PRECISION || (exports.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
   */

  (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 = {}));
  /**
   * 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
   */

  (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 = {}));
  /**
   * Constants for various buffer types in Pixi
   *
   * @see PIXI.BUFFER_TYPE
   *
   * @name BUFFER_TYPE
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
   * @property {number} ARRAY_BUFFER - buffer type for using attribute data
   * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
   */

  (function (BUFFER_TYPE) {
      BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
      BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
      // NOT YET SUPPORTED
      BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
  })(exports.BUFFER_TYPE || (exports.BUFFER_TYPE = {}));

  /*!
   * @pixi/utils - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/utils is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * This file contains redeclared types for Node `url` and `querystring` modules. These modules
   * don't provide their own typings but instead are a part of the full Node typings. The purpose of
   * this file is to redeclare the required types to avoid having the whole Node types as a
   * dependency.
   */
  var url$1 = {
      parse: parse,
      format: format,
      resolve: resolve$1,
  };

  /**
   * 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.RETINA_PREFIX = /@([0-9\.]+)x/;
  /**
   * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function.
   * If set to true, a WebGL renderer can fail to be created if the browser thinks there could be performance issues when
   * using WebGL.
   *
   * In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many scenarios as possible.
   * However, some users may have a poor experience, for example, if a user has a gpu or driver version blacklisted by the
   * browser.
   *
   * If your application requires high performance rendering, you may wish to set this to false.
   * We recommend one of two options if you decide to set this flag to false:
   *
   * 1: Use the `pixi.js-legacy` package, which includes a Canvas renderer as a fallback in case high performance WebGL is
   *    not supported.
   *
   * 2: Call `isWebGLSupported` (which if found in the PIXI.utils package) in your code before attempting to create a PixiJS
   *    renderer, and show an error message to the user if the function returns false, explaining that their device & browser
   *    combination does not support high performance WebGL.
   *    This is a much better strategy than trying to create a PixiJS renderer and finding it then fails.
   *
   * @static
   * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT
   * @memberof PIXI.settings
   * @type {boolean}
   * @default false
   */
  settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false;

  var saidHello = false;
  var VERSION = '6.3.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) {
      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 = globalThis.console).log.apply(_a, args);
      }
      else if (globalThis.console) {
          globalThis.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.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT,
              };
              try {
                  if (!globalThis.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;
  }

  var aliceblue = "#f0f8ff";
  var antiquewhite = "#faebd7";
  var aqua = "#00ffff";
  var aquamarine = "#7fffd4";
  var azure = "#f0ffff";
  var beige = "#f5f5dc";
  var bisque = "#ffe4c4";
  var black = "#000000";
  var blanchedalmond = "#ffebcd";
  var blue = "#0000ff";
  var blueviolet = "#8a2be2";
  var brown = "#a52a2a";
  var burlywood = "#deb887";
  var cadetblue = "#5f9ea0";
  var chartreuse = "#7fff00";
  var chocolate = "#d2691e";
  var coral = "#ff7f50";
  var cornflowerblue = "#6495ed";
  var cornsilk = "#fff8dc";
  var crimson = "#dc143c";
  var cyan = "#00ffff";
  var darkblue = "#00008b";
  var darkcyan = "#008b8b";
  var darkgoldenrod = "#b8860b";
  var darkgray = "#a9a9a9";
  var darkgreen = "#006400";
  var darkgrey = "#a9a9a9";
  var darkkhaki = "#bdb76b";
  var darkmagenta = "#8b008b";
  var darkolivegreen = "#556b2f";
  var darkorange = "#ff8c00";
  var darkorchid = "#9932cc";
  var darkred = "#8b0000";
  var darksalmon = "#e9967a";
  var darkseagreen = "#8fbc8f";
  var darkslateblue = "#483d8b";
  var darkslategray = "#2f4f4f";
  var darkslategrey = "#2f4f4f";
  var darkturquoise = "#00ced1";
  var darkviolet = "#9400d3";
  var deeppink = "#ff1493";
  var deepskyblue = "#00bfff";
  var dimgray = "#696969";
  var dimgrey = "#696969";
  var dodgerblue = "#1e90ff";
  var firebrick = "#b22222";
  var floralwhite = "#fffaf0";
  var forestgreen = "#228b22";
  var fuchsia = "#ff00ff";
  var gainsboro = "#dcdcdc";
  var ghostwhite = "#f8f8ff";
  var goldenrod = "#daa520";
  var gold = "#ffd700";
  var gray = "#808080";
  var green = "#008000";
  var greenyellow = "#adff2f";
  var grey = "#808080";
  var honeydew = "#f0fff0";
  var hotpink = "#ff69b4";
  var indianred = "#cd5c5c";
  var indigo = "#4b0082";
  var ivory = "#fffff0";
  var khaki = "#f0e68c";
  var lavenderblush = "#fff0f5";
  var lavender = "#e6e6fa";
  var lawngreen = "#7cfc00";
  var lemonchiffon = "#fffacd";
  var lightblue = "#add8e6";
  var lightcoral = "#f08080";
  var lightcyan = "#e0ffff";
  var lightgoldenrodyellow = "#fafad2";
  var lightgray = "#d3d3d3";
  var lightgreen = "#90ee90";
  var lightgrey = "#d3d3d3";
  var lightpink = "#ffb6c1";
  var lightsalmon = "#ffa07a";
  var lightseagreen = "#20b2aa";
  var lightskyblue = "#87cefa";
  var lightslategray = "#778899";
  var lightslategrey = "#778899";
  var lightsteelblue = "#b0c4de";
  var lightyellow = "#ffffe0";
  var lime = "#00ff00";
  var limegreen = "#32cd32";
  var linen = "#faf0e6";
  var magenta = "#ff00ff";
  var maroon = "#800000";
  var mediumaquamarine = "#66cdaa";
  var mediumblue = "#0000cd";
  var mediumorchid = "#ba55d3";
  var mediumpurple = "#9370db";
  var mediumseagreen = "#3cb371";
  var mediumslateblue = "#7b68ee";
  var mediumspringgreen = "#00fa9a";
  var mediumturquoise = "#48d1cc";
  var mediumvioletred = "#c71585";
  var midnightblue = "#191970";
  var mintcream = "#f5fffa";
  var mistyrose = "#ffe4e1";
  var moccasin = "#ffe4b5";
  var navajowhite = "#ffdead";
  var navy = "#000080";
  var oldlace = "#fdf5e6";
  var olive = "#808000";
  var olivedrab = "#6b8e23";
  var orange = "#ffa500";
  var orangered = "#ff4500";
  var orchid = "#da70d6";
  var palegoldenrod = "#eee8aa";
  var palegreen = "#98fb98";
  var paleturquoise = "#afeeee";
  var palevioletred = "#db7093";
  var papayawhip = "#ffefd5";
  var peachpuff = "#ffdab9";
  var peru = "#cd853f";
  var pink = "#ffc0cb";
  var plum = "#dda0dd";
  var powderblue = "#b0e0e6";
  var purple = "#800080";
  var rebeccapurple = "#663399";
  var red = "#ff0000";
  var rosybrown = "#bc8f8f";
  var royalblue = "#4169e1";
  var saddlebrown = "#8b4513";
  var salmon = "#fa8072";
  var sandybrown = "#f4a460";
  var seagreen = "#2e8b57";
  var seashell = "#fff5ee";
  var sienna = "#a0522d";
  var silver = "#c0c0c0";
  var skyblue = "#87ceeb";
  var slateblue = "#6a5acd";
  var slategray = "#708090";
  var slategrey = "#708090";
  var snow = "#fffafa";
  var springgreen = "#00ff7f";
  var steelblue = "#4682b4";
  var tan = "#d2b48c";
  var teal = "#008080";
  var thistle = "#d8bfd8";
  var tomato = "#ff6347";
  var turquoise = "#40e0d0";
  var violet = "#ee82ee";
  var wheat = "#f5deb3";
  var white = "#ffffff";
  var whitesmoke = "#f5f5f5";
  var yellow = "#ffff00";
  var yellowgreen = "#9acd32";
  var cssColorNames = {
  	aliceblue: aliceblue,
  	antiquewhite: antiquewhite,
  	aqua: aqua,
  	aquamarine: aquamarine,
  	azure: azure,
  	beige: beige,
  	bisque: bisque,
  	black: black,
  	blanchedalmond: blanchedalmond,
  	blue: blue,
  	blueviolet: blueviolet,
  	brown: brown,
  	burlywood: burlywood,
  	cadetblue: cadetblue,
  	chartreuse: chartreuse,
  	chocolate: chocolate,
  	coral: coral,
  	cornflowerblue: cornflowerblue,
  	cornsilk: cornsilk,
  	crimson: crimson,
  	cyan: cyan,
  	darkblue: darkblue,
  	darkcyan: darkcyan,
  	darkgoldenrod: darkgoldenrod,
  	darkgray: darkgray,
  	darkgreen: darkgreen,
  	darkgrey: darkgrey,
  	darkkhaki: darkkhaki,
  	darkmagenta: darkmagenta,
  	darkolivegreen: darkolivegreen,
  	darkorange: darkorange,
  	darkorchid: darkorchid,
  	darkred: darkred,
  	darksalmon: darksalmon,
  	darkseagreen: darkseagreen,
  	darkslateblue: darkslateblue,
  	darkslategray: darkslategray,
  	darkslategrey: darkslategrey,
  	darkturquoise: darkturquoise,
  	darkviolet: darkviolet,
  	deeppink: deeppink,
  	deepskyblue: deepskyblue,
  	dimgray: dimgray,
  	dimgrey: dimgrey,
  	dodgerblue: dodgerblue,
  	firebrick: firebrick,
  	floralwhite: floralwhite,
  	forestgreen: forestgreen,
  	fuchsia: fuchsia,
  	gainsboro: gainsboro,
  	ghostwhite: ghostwhite,
  	goldenrod: goldenrod,
  	gold: gold,
  	gray: gray,
  	green: green,
  	greenyellow: greenyellow,
  	grey: grey,
  	honeydew: honeydew,
  	hotpink: hotpink,
  	indianred: indianred,
  	indigo: indigo,
  	ivory: ivory,
  	khaki: khaki,
  	lavenderblush: lavenderblush,
  	lavender: lavender,
  	lawngreen: lawngreen,
  	lemonchiffon: lemonchiffon,
  	lightblue: lightblue,
  	lightcoral: lightcoral,
  	lightcyan: lightcyan,
  	lightgoldenrodyellow: lightgoldenrodyellow,
  	lightgray: lightgray,
  	lightgreen: lightgreen,
  	lightgrey: lightgrey,
  	lightpink: lightpink,
  	lightsalmon: lightsalmon,
  	lightseagreen: lightseagreen,
  	lightskyblue: lightskyblue,
  	lightslategray: lightslategray,
  	lightslategrey: lightslategrey,
  	lightsteelblue: lightsteelblue,
  	lightyellow: lightyellow,
  	lime: lime,
  	limegreen: limegreen,
  	linen: linen,
  	magenta: magenta,
  	maroon: maroon,
  	mediumaquamarine: mediumaquamarine,
  	mediumblue: mediumblue,
  	mediumorchid: mediumorchid,
  	mediumpurple: mediumpurple,
  	mediumseagreen: mediumseagreen,
  	mediumslateblue: mediumslateblue,
  	mediumspringgreen: mediumspringgreen,
  	mediumturquoise: mediumturquoise,
  	mediumvioletred: mediumvioletred,
  	midnightblue: midnightblue,
  	mintcream: mintcream,
  	mistyrose: mistyrose,
  	moccasin: moccasin,
  	navajowhite: navajowhite,
  	navy: navy,
  	oldlace: oldlace,
  	olive: olive,
  	olivedrab: olivedrab,
  	orange: orange,
  	orangered: orangered,
  	orchid: orchid,
  	palegoldenrod: palegoldenrod,
  	palegreen: palegreen,
  	paleturquoise: paleturquoise,
  	palevioletred: palevioletred,
  	papayawhip: papayawhip,
  	peachpuff: peachpuff,
  	peru: peru,
  	pink: pink,
  	plum: plum,
  	powderblue: powderblue,
  	purple: purple,
  	rebeccapurple: rebeccapurple,
  	red: red,
  	rosybrown: rosybrown,
  	royalblue: royalblue,
  	saddlebrown: saddlebrown,
  	salmon: salmon,
  	sandybrown: sandybrown,
  	seagreen: seagreen,
  	seashell: seashell,
  	sienna: sienna,
  	silver: silver,
  	skyblue: skyblue,
  	slateblue: slateblue,
  	slategray: slategray,
  	slategrey: slategrey,
  	snow: snow,
  	springgreen: springgreen,
  	steelblue: steelblue,
  	tan: tan,
  	teal: teal,
  	thistle: thistle,
  	tomato: tomato,
  	turquoise: turquoise,
  	violet: violet,
  	wheat: wheat,
  	white: white,
  	whitesmoke: whitesmoke,
  	yellow: yellow,
  	yellowgreen: yellowgreen
  };

  /**
   * 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) {
      if (out === void 0) { 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) {
      var hexString = hex.toString(16);
      hexString = '000000'.substring(0, 6 - hexString.length) + hexString;
      return "#" + hexString;
  }
  /**
   * Converts a string to a hexadecimal color number.
   * It can handle:
   *  hex strings starting with #: "#ffffff"
   *  hex strings starting with 0x: "0xffffff"
   *  hex strings without prefix: "ffffff"
   *  css colors: "black"
   *
   * @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.
   */
  function string2hex(string) {
      if (typeof string === 'string') {
          string = cssColorNames[string.toLowerCase()] || string;
          if (string[0] === '#') {
              string = string.slice(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
   * @return {Array<number[]>} Mapped modes.
   */
  function mapPremultipliedBlendModes() {
      var pm = [];
      var npm = [];
      for (var i = 0; i < 32; i++) {
          pm[i] = i;
          npm[i] = i;
      }
      pm[exports.BLEND_MODES.NORMAL_NPM] = exports.BLEND_MODES.NORMAL;
      pm[exports.BLEND_MODES.ADD_NPM] = exports.BLEND_MODES.ADD;
      pm[exports.BLEND_MODES.SCREEN_NPM] = exports.BLEND_MODES.SCREEN;
      npm[exports.BLEND_MODES.NORMAL] = exports.BLEND_MODES.NORMAL_NPM;
      npm[exports.BLEND_MODES.ADD] = exports.BLEND_MODES.ADD_NPM;
      npm[exports.BLEND_MODES.SCREEN] = exports.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<number[]>}
   */
  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;
  }

  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);
  }

  // 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 ? 1 : 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 ? 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
   *
   * @function removeItems
   * @memberof PIXI.utils
   * @param {Array<any>} 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;
  }

  /**
   * 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$1(n) {
      if (n === 0)
          { return 0; }
      return n < 0 ? -1 : 1;
  }

  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;
  }

  // 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;
  }

  /**
   * @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 width - the width for the newly created canvas
       * @param height - the height for the newly created canvas
       * @param {number} [resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the canvas
       */
      function CanvasRenderTarget(width, height, resolution) {
          this.canvas = document.createElement('canvas');
          this.context = this.canvas.getContext('2d');
          this.resolution = resolution || settings.RESOLUTION;
          this.resize(width, height);
      }
      /**
       * Clears the canvas that was created by the CanvasRenderTarget class.
       *
       * @private
       */
      CanvasRenderTarget.prototype.clear = function () {
          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 desiredWidth - the desired width of the canvas
       * @param desiredHeight - the desired height of the canvas
       */
      CanvasRenderTarget.prototype.resize = function (desiredWidth, desiredHeight) {
          this.canvas.width = Math.round(desiredWidth * this.resolution);
          this.canvas.height = Math.round(desiredHeight * this.resolution);
      };
      /** Destroys this canvas. */
      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 = Math.round(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 = Math.round(val);
          },
          enumerable: false,
          configurable: true
      });
      return CanvasRenderTarget;
  }());

  /**
   * 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,
      };
  }

  /**
   * 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;

  /**
   * @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.
   *
   * @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$1$1, loc) {
      if (loc === void 0) { loc = globalThis.location; }
      // data: and javascript: urls are considered same-origin
      if (url$1$1.indexOf('data:') === 0) {
          return '';
      }
      // default is window.location
      loc = loc || globalThis.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$1$1;
      var parsedUrl = url$1.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 '';
  }

  /**
   * 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.RETINA_PREFIX.exec(url);
      if (resolution) {
          return parseFloat(resolution[1]);
      }
      return defaultValue !== undefined ? defaultValue : 1;
  }

  var utils = {
    __proto__: null,
    BaseTextureCache: BaseTextureCache,
    CanvasRenderTarget: CanvasRenderTarget,
    DATA_URI: DATA_URI,
    ProgramCache: ProgramCache,
    TextureCache: TextureCache,
    clearTextureCache: clearTextureCache,
    correctBlendMode: correctBlendMode,
    createIndicesForQuads: createIndicesForQuads,
    decomposeDataUri: decomposeDataUri,
    deprecation: deprecation,
    destroyTextureCache: destroyTextureCache,
    determineCrossOrigin: determineCrossOrigin,
    getBufferType: getBufferType,
    getResolutionOfUrl: getResolutionOfUrl,
    hex2rgb: hex2rgb,
    hex2string: hex2string,
    interleaveTypedArrays: interleaveTypedArrays,
    isPow2: isPow2,
    isWebGLSupported: isWebGLSupported,
    log2: log2,
    nextPow2: nextPow2,
    premultiplyBlendMode: premultiplyBlendMode,
    premultiplyRgba: premultiplyRgba,
    premultiplyTint: premultiplyTint,
    premultiplyTintToRgba: premultiplyTintToRgba,
    removeItems: removeItems,
    rgb2hex: rgb2hex,
    sayHello: sayHello,
    sign: sign$1,
    skipHello: skipHello,
    string2hex: string2hex,
    trimCanvas: trimCanvas,
    uid: uid,
    url: url$1,
    isMobile: isMobile$1,
    EventEmitter: eventemitter3,
    earcut: earcut_1
  };

  /*!
   * @pixi/math - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/math is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */
  /**
   * Two Pi.
   *
   * @static
   * @member {number}
   * @memberof PIXI
   */
  var PI_2 = Math.PI * 2;
  /**
   * Conversion factor for converting radians to degrees.
   *
   * @static
   * @member {number} RAD_TO_DEG
   * @memberof PIXI
   */
  var RAD_TO_DEG = 180 / Math.PI;
  /**
   * Conversion factor for converting degrees to radians.
   *
   * @static
   * @member {number}
   * @memberof PIXI
   */
  var DEG_TO_RAD = Math.PI / 180;
  /**
   * Constants that identify shapes, mainly to prevent `instanceof` calls.
   *
   * @static
   * @memberof PIXI
   * @enum {number}
   * @property {number} POLY Polygon
   * @property {number} RECT Rectangle
   * @property {number} CIRC Circle
   * @property {number} ELIP Ellipse
   * @property {number} RREC Rounded Rectangle
   */

  (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 = {}));

  /**
   * The Point object represents a location in a two-dimensional coordinate system, where `x` represents
   * the position on the horizontal axis and `y` represents the position on the vertical axis
   *
   * @class
   * @memberof PIXI
   * @implements IPoint
   */
  var Point = /** @class */ (function () {
      /** Creates a new `Point`
       * @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 Point(x, y) {
          if (x === void 0) { x = 0; }
          if (y === void 0) { y = 0; }
          /** Position of the point on the x axis */
          this.x = 0;
          /** Position of the point on the y axis */
          this.y = 0;
          this.x = x;
          this.y = y;
      }
      /** Creates a clone of this point
       * @returns A clone of this point
       */
      Point.prototype.clone = function () {
          return new Point(this.x, this.y);
      };
      /**
       * Copies `x` and `y` from the given point into this point
       *
       * @param p - The point to copy from
       * @returns The point instance itself
       */
      Point.prototype.copyFrom = function (p) {
          this.set(p.x, p.y);
          return this;
      };
      /**
       * Copies this point's x and y into the given point (`p`).
       *
       * @param p - The point to copy to. Can be any of type that is or extends `IPointData`
       * @returns The point (`p`) with values updated
       */
      Point.prototype.copyTo = function (p) {
          p.set(this.x, this.y);
          return p;
      };
      /**
       * Accepts another point (`p`) and returns `true` if the given point is equal to this point
       *
       * @param p - The point to check
       * @returns Returns `true` if both `x` and `y` are equal
       */
      Point.prototype.equals = function (p) {
          return (p.x === this.x) && (p.y === 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 The point instance itself
       */
      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;
      };
      Point.prototype.toString = function () {
          return "[@pixi/math:Point x=" + this.x + " y=" + this.y + "]";
      };
      return Point;
  }());

  var tempPoints = [new Point(), new Point(), new Point(), new Point()];
  /**
   * Size object, contains width and height
   *
   * @memberof PIXI
   * @typedef {object} ISize
   */
  /**
   * 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.
   *
   * @memberof PIXI
   */
  var Rectangle = /** @class */ (function () {
      /**
       * @param x - The X coordinate of the upper-left corner of the rectangle
       * @param y - The Y coordinate of the upper-left corner of the rectangle
       * @param width - The overall width of the rectangle
       * @param height - The overall height of the 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; }
          this.x = Number(x);
          this.y = Number(y);
          this.width = Number(width);
          this.height = Number(height);
          this.type = exports.SHAPES.RECT;
      }
      Object.defineProperty(Rectangle.prototype, "left", {
          /** Returns the left edge of the rectangle. */
          get: function () {
              return this.x;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Rectangle.prototype, "right", {
          /** Returns the right edge of the rectangle. */
          get: function () {
              return this.x + this.width;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Rectangle.prototype, "top", {
          /** Returns the top edge of the rectangle. */
          get: function () {
              return this.y;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Rectangle.prototype, "bottom", {
          /** Returns the bottom edge of the rectangle. */
          get: function () {
              return this.y + this.height;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Rectangle, "EMPTY", {
          /** A constant empty rectangle. */
          get: function () {
              return new Rectangle(0, 0, 0, 0);
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Creates a clone of this Rectangle
       *
       * @return 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 rectangle - The rectangle to copy from.
       * @return 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 rectangle - The rectangle to copy to.
       * @return 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
       *
       * @param x - The X coordinate of the point to test
       * @param y - The Y coordinate of the point to test
       * @return Whether the x/y coordinates are within this Rectangle
       */
      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;
      };
      /**
       * Determines whether the `other` Rectangle transformed by `transform` intersects with `this` Rectangle object.
       * Returns true only if the area of the intersection is >0, this means that Rectangles
       * sharing a side are not overlapping. Another side effect is that an arealess rectangle
       * (width or height equal to zero) can't intersect any other rectangle.
       *
       * @param {Rectangle} other - The Rectangle to intersect with `this`.
       * @param {Matrix} transform - The transformation matrix of `other`.
       * @returns {boolean} A value of `true` if the transformed `other` Rectangle intersects with `this`; otherwise `false`.
       */
      Rectangle.prototype.intersects = function (other, transform) {
          if (!transform) {
              var x0_1 = this.x < other.x ? other.x : this.x;
              var x1_1 = this.right > other.right ? other.right : this.right;
              if (x1_1 <= x0_1) {
                  return false;
              }
              var y0_1 = this.y < other.y ? other.y : this.y;
              var y1_1 = this.bottom > other.bottom ? other.bottom : this.bottom;
              return y1_1 > y0_1;
          }
          var x0 = this.left;
          var x1 = this.right;
          var y0 = this.top;
          var y1 = this.bottom;
          if (x1 <= x0 || y1 <= y0) {
              return false;
          }
          var lt = tempPoints[0].set(other.left, other.top);
          var lb = tempPoints[1].set(other.left, other.bottom);
          var rt = tempPoints[2].set(other.right, other.top);
          var rb = tempPoints[3].set(other.right, other.bottom);
          if (rt.x <= lt.x || lb.y <= lt.y) {
              return false;
          }
          var s = Math.sign((transform.a * transform.d) - (transform.b * transform.c));
          if (s === 0) {
              return false;
          }
          transform.apply(lt, lt);
          transform.apply(lb, lb);
          transform.apply(rt, rt);
          transform.apply(rb, rb);
          if (Math.max(lt.x, lb.x, rt.x, rb.x) <= x0
              || Math.min(lt.x, lb.x, rt.x, rb.x) >= x1
              || Math.max(lt.y, lb.y, rt.y, rb.y) <= y0
              || Math.min(lt.y, lb.y, rt.y, rb.y) >= y1) {
              return false;
          }
          var nx = s * (lb.y - lt.y);
          var ny = s * (lt.x - lb.x);
          var n00 = (nx * x0) + (ny * y0);
          var n10 = (nx * x1) + (ny * y0);
          var n01 = (nx * x0) + (ny * y1);
          var n11 = (nx * x1) + (ny * y1);
          if (Math.max(n00, n10, n01, n11) <= (nx * lt.x) + (ny * lt.y)
              || Math.min(n00, n10, n01, n11) >= (nx * rb.x) + (ny * rb.y)) {
              return false;
          }
          var mx = s * (lt.y - rt.y);
          var my = s * (rt.x - lt.x);
          var m00 = (mx * x0) + (my * y0);
          var m10 = (mx * x1) + (my * y0);
          var m01 = (mx * x0) + (my * y1);
          var m11 = (mx * x1) + (my * y1);
          if (Math.max(m00, m10, m01, m11) <= (mx * lt.x) + (my * lt.y)
              || Math.min(m00, m10, m01, m11) >= (mx * rb.x) + (my * rb.y)) {
              return false;
          }
          return true;
      };
      /**
       * Pads the rectangle making it grow in all directions.
       * If paddingY is omitted, both paddingX and paddingY will be set to paddingX.
       *
       * @param paddingX - The horizontal padding amount.
       * @param paddingY - The vertical padding amount.
       * @return 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 rectangle - The rectangle to fit.
       * @return 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 resolution - resolution
       * @param eps - precision
       * @return 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 rectangle - The rectangle to include.
       * @return 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;
      };
      Rectangle.prototype.toString = function () {
          return "[@pixi/math:Rectangle x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]";
      };
      return Rectangle;
  }());

  /**
   * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects.
   *
   * @memberof PIXI
   */
  var Circle = /** @class */ (function () {
      /**
       * @param x - The X coordinate of the center of this circle
       * @param y - The Y coordinate of the center of this circle
       * @param radius - 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; }
          this.x = x;
          this.y = y;
          this.radius = radius;
          this.type = exports.SHAPES.CIRC;
      }
      /**
       * Creates a clone of this Circle instance
       *
       * @return 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 x - The X coordinate of the point to test
       * @param y - The Y coordinate of the point to test
       * @return 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 The framing rectangle
      */
      Circle.prototype.getBounds = function () {
          return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
      };
      Circle.prototype.toString = function () {
          return "[@pixi/math:Circle x=" + this.x + " y=" + this.y + " radius=" + this.radius + "]";
      };
      return Circle;
  }());

  /**
   * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects.
   *
   * @memberof PIXI
   */
  var Ellipse = /** @class */ (function () {
      /**
       * @param x - The X coordinate of the center of this ellipse
       * @param y - The Y coordinate of the center of this ellipse
       * @param halfWidth - The half width of this ellipse
       * @param halfHeight - 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; }
          this.x = x;
          this.y = y;
          this.width = halfWidth;
          this.height = halfHeight;
          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 x - The X coordinate of the point to test
       * @param y - The Y coordinate of the point to test
       * @return 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 The framing rectangle
       */
      Ellipse.prototype.getBounds = function () {
          return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height);
      };
      Ellipse.prototype.toString = function () {
          return "[@pixi/math:Ellipse x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]";
      };
      return Ellipse;
  }());

  /**
   * A class to define a shape via user defined coordinates.
   *
   * @memberof PIXI
   */
  var Polygon = /** @class */ (function () {
      /**
       * @param {PIXI.IPointData[]|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];
          }
          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;
          }
          this.points = flat;
          this.type = exports.SHAPES.POLY;
          this.closeStroke = true;
      }
      /**
       * Creates a clone of this polygon.
       *
       * @return - 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 x - The X coordinate of the point to test.
       * @param y - The Y coordinate of the point to test.
       * @return - 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;
      };
      Polygon.prototype.toString = function () {
          return "[@pixi/math:Polygon"
              + ("closeStroke=" + this.closeStroke)
              + ("points=" + this.points.reduce(function (pointsDesc, currentPoint) { return pointsDesc + ", " + currentPoint; }, '') + "]");
      };
      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.
   *
   * @memberof PIXI
   */
  var RoundedRectangle = /** @class */ (function () {
      /**
       * @param x - The X coordinate of the upper-left corner of the rounded rectangle
       * @param y - The Y coordinate of the upper-left corner of the rounded rectangle
       * @param width - The overall width of this rounded rectangle
       * @param height - The overall height of this rounded rectangle
       * @param radius - 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; }
          this.x = x;
          this.y = y;
          this.width = width;
          this.height = height;
          this.radius = radius;
          this.type = exports.SHAPES.RREC;
      }
      /**
       * Creates a clone of this Rounded Rectangle.
       *
       * @return - 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 x - The X coordinate of the point to test.
       * @param y - The Y coordinate of the point to test.
       * @return - 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;
          }
          if (x >= this.x && x <= this.x + this.width) {
              if (y >= this.y && y <= this.y + this.height) {
                  var radius = Math.max(0, Math.min(this.radius, Math.min(this.width, this.height) / 2));
                  if ((y >= this.y + radius && y <= this.y + this.height - radius)
                      || (x >= this.x + radius && x <= this.x + this.width - radius)) {
                      return true;
                  }
                  var dx = x - (this.x + radius);
                  var dy = y - (this.y + radius);
                  var radius2 = radius * radius;
                  if ((dx * dx) + (dy * dy) <= radius2) {
                      return true;
                  }
                  dx = x - (this.x + this.width - radius);
                  if ((dx * dx) + (dy * dy) <= radius2) {
                      return true;
                  }
                  dy = y - (this.y + this.height - radius);
                  if ((dx * dx) + (dy * dy) <= radius2) {
                      return true;
                  }
                  dx = x - (this.x + radius);
                  if ((dx * dx) + (dy * dy) <= radius2) {
                      return true;
                  }
              }
          }
          return false;
      };
      RoundedRectangle.prototype.toString = function () {
          return "[@pixi/math:RoundedRectangle x=" + this.x + " y=" + this.y
              + ("width=" + this.width + " height=" + this.height + " radius=" + this.radius + "]");
      };
      return RoundedRectangle;
  }());

  /**
   * The ObservablePoint object represents a location in a two-dimensional coordinate system, where `x` represents
   * the position on the horizontal axis and `y` represents the position on the vertical axis.
   *
   * An `ObservablePoint` is a point that triggers a callback when the point's position is changed.
   *
   * @memberof PIXI
   */
  var ObservablePoint = /** @class */ (function () {
      /**
       * Creates a new `ObservablePoint`
       *
       * @param cb - callback function triggered when `x` and/or `y` are changed
       * @param 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 overridden otherwise they will default
       * to the clone object's values.
       *
       * @override
       * @param cb - The callback function triggered when `x` and/or `y` are changed
       * @param scope - The owner of the callback
       * @return a copy of this observable 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 The observable point instance 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 (`p`)
       *
       * @param p - The point to copy from. Can be any of type that is or extends `IPointData`
       * @returns The observable point instance 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 this point's x and y into that of the given point (`p`)
       *
       * @param p - The point to copy to. Can be any of type that is or extends `IPointData`
       * @returns The point (`p`) with values updated
       */
      ObservablePoint.prototype.copyTo = function (p) {
          p.set(this._x, this._y);
          return p;
      };
      /**
       * Accepts another point (`p`) and returns `true` if the given point is equal to this point
       *
       * @param p - The point to check
       * @returns Returns `true` if both `x` and `y` are equal
       */
      ObservablePoint.prototype.equals = function (p) {
          return (p.x === this._x) && (p.y === this._y);
      };
      ObservablePoint.prototype.toString = function () {
          return "[@pixi/math:ObservablePoint x=" + 0 + " y=" + 0 + " scope=" + this.scope + "]";
      };
      Object.defineProperty(ObservablePoint.prototype, "x", {
          /** Position of the observable point on the x axis. */
          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", {
          /** Position of the observable point on the y axis. */
          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 |
   * ```
   *
   * @memberof PIXI
   */
  var Matrix = /** @class */ (function () {
      /**
       * @param a - x scale
       * @param b - y skew
       * @param c - x skew
       * @param d - y scale
       * @param tx - x translation
       * @param ty - 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;
          this.a = a;
          this.b = b;
          this.c = c;
          this.d = d;
          this.tx = tx;
          this.ty = ty;
      }
      /**
       * 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]
       *
       * @param array - The array that the matrix will be populated from.
       */
      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];
      };
      /**
       * Sets the matrix properties.
       *
       * @param a - Matrix component
       * @param b - Matrix component
       * @param c - Matrix component
       * @param d - Matrix component
       * @param tx - Matrix component
       * @param ty - Matrix component
       * @return This matrix. Good for chaining method calls.
       */
      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;
      };
      /**
       * Creates an array from the current Matrix object.
       *
       * @param transpose - Whether we need to transpose the matrix or not
       * @param [out=new Float32Array(9)] - If provided the array will be assigned to out
       * @return The newly created array which contains the matrix
       */
      Matrix.prototype.toArray = function (transpose, out) {
          if (!this.array) {
              this.array = new Float32Array(9);
          }
          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;
      };
      /**
       * 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 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
       */
      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;
      };
      /**
       * 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 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;
      };
      /**
       * Translates the matrix on the x and y.
       *
       * @param x - How much to translate x by
       * @param y - How much to translate y by
       * @return This matrix. Good for chaining method calls.
       */
      Matrix.prototype.translate = function (x, y) {
          this.tx += x;
          this.ty += y;
          return this;
      };
      /**
       * Applies a scale transformation to the matrix.
       *
       * @param x - The amount to scale horizontally
       * @param y - The amount to scale vertically
       * @return This matrix. Good for chaining method calls.
       */
      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;
      };
      /**
       * Applies a rotation transformation to the matrix.
       *
       * @param angle - The angle in radians.
       * @return This matrix. Good for chaining method calls.
       */
      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;
      };
      /**
       * Appends the given Matrix to this Matrix.
       *
       * @param matrix - The matrix to append.
       * @return This matrix. Good for chaining method calls.
       */
      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;
      };
      /**
       * Sets the matrix based on all the available properties
       *
       * @param x - Position on the x axis
       * @param y - Position on the y axis
       * @param pivotX - Pivot on the x axis
       * @param pivotY - Pivot on the y axis
       * @param scaleX - Scale on the x axis
       * @param scaleY - Scale on the y axis
       * @param rotation - Rotation in radians
       * @param skewX - Skew on the x axis
       * @param skewY - Skew on the y axis
       * @return This matrix. Good for chaining method calls.
       */
      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;
      };
      /**
       * Prepends the given Matrix to this Matrix.
       *
       * @param matrix - The matrix to prepend
       * @return This matrix. Good for chaining method calls.
       */
      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.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 transform - The transform to apply the properties to.
       * @return 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 pivot = transform.pivot;
          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;
          }
          else {
              transform.rotation = 0;
              transform.skew.x = skewX;
              transform.skew.y = skewY;
          }
          // 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 + ((pivot.x * a) + (pivot.y * c));
          transform.position.y = this.ty + ((pivot.x * b) + (pivot.y * d));
          return transform;
      };
      /**
       * Inverts this matrix
       *
       * @return This matrix. Good for chaining method calls.
       */
      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;
      };
      /**
       * Resets this Matrix to an identity (default) matrix.
       *
       * @return This matrix. Good for chaining method calls.
       */
      Matrix.prototype.identity = function () {
          this.a = 1;
          this.b = 0;
          this.c = 0;
          this.d = 1;
          this.tx = 0;
          this.ty = 0;
          return this;
      };
      /**
       * Creates a new Matrix object with the same values as this one.
       *
       * @return A copy of this matrix. Good for chaining method calls.
       */
      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;
      };
      /**
       * Changes the values of the given matrix to be the same as the ones in this matrix
       *
       * @param matrix - The matrix to copy to.
       * @return The matrix given in parameter with its values updated.
       */
      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;
      };
      /**
       * Changes the values of the matrix to be the same as the ones in given matrix
       *
       * @param {PIXI.Matrix} matrix - The matrix to copy from.
       * @return {PIXI.Matrix} this
       */
      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;
      };
      Matrix.prototype.toString = function () {
          return "[@pixi/math:Matrix a=" + this.a + " b=" + this.b + " c=" + this.c + " d=" + this.d + " tx=" + this.tx + " ty=" + this.ty + "]";
      };
      Object.defineProperty(Matrix, "IDENTITY", {
          /**
           * A default (identity) matrix
           *
           * @readonly
           */
          get: function () {
              return new Matrix();
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Matrix, "TEMP_MATRIX", {
          /**
           * A temp matrix
           *
           * @readonly
           */
          get: function () {
              return new Matrix();
          },
          enumerable: false,
          configurable: true
      });
      return Matrix;
  }());

  // 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;
                  }
              }
          }
      }
      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:**<br>
   *  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 = {
      /**
       * | Rotation | Direction |
       * |----------|-----------|
       * | 0°       | East      |
       *
       * @memberof PIXI.groupD8
       * @constant {PIXI.GD8Symmetry}
       */
      E: 0,
      /**
       * | Rotation | Direction |
       * |----------|-----------|
       * | 45°↻     | Southeast |
       *
       * @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,
      /**
       * | Rotation    | Direction    |
       * |-------------|--------------|
       * | -135°/225°↻ | Northwest    |
       *
       * @memberof PIXI.groupD8
       * @constant {PIXI.GD8Symmetry}
       */
      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.
   *
   * @memberof PIXI
   */
  var Transform = /** @class */ (function () {
      function Transform() {
          this.worldTransform = new Matrix();
          this.localTransform = new Matrix();
          this.position = new ObservablePoint(this.onChange, this, 0, 0);
          this.scale = new ObservablePoint(this.onChange, this, 1, 1);
          this.pivot = new ObservablePoint(this.onChange, this, 0, 0);
          this.skew = new ObservablePoint(this.updateSkew, this, 0, 0);
          this._rotation = 0;
          this._cx = 1;
          this._sx = 0;
          this._cy = 0;
          this._sy = 1;
          this._localID = 0;
          this._currentLocalID = 0;
          this._worldID = 0;
          this._parentID = 0;
      }
      /** Called when a value changes. */
      Transform.prototype.onChange = function () {
          this._localID++;
      };
      /** Called when the skew or the rotation changes. */
      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++;
      };
      Transform.prototype.toString = function () {
          return "[@pixi/math:Transform "
              + ("position=(" + this.position.x + ", " + this.position.y + ") ")
              + ("rotation=" + this.rotation + " ")
              + ("scale=(" + this.scale.x + ", " + this.scale.y + ") ")
              + ("skew=(" + this.skew.x + ", " + this.skew.y + ") ")
              + "]";
      };
      /** Updates the local transformation matrix. */
      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;
          }
      };
      /**
       * Updates the local and the world transformation matrices.
       *
       * @param parentTransform - The parent transform
       */
      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++;
          }
      };
      /**
       * Decomposes a matrix and sets the transforms properties based on it.
       *
       * @param matrix - The matrix to decompose
       */
      Transform.prototype.setFromMatrix = function (matrix) {
          matrix.decompose(this);
          this._localID++;
      };
      Object.defineProperty(Transform.prototype, "rotation", {
          /** The rotation of the object in radians. */
          get: function () {
              return this._rotation;
          },
          set: function (value) {
              if (this._rotation !== value) {
                  this._rotation = value;
                  this.updateSkew();
              }
          },
          enumerable: false,
          configurable: true
      });
      /** A default (identity) transform. */
      Transform.IDENTITY = new Transform();
      return Transform;
  }());

  /*!
   * @pixi/display - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/display is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * 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.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.
   *
   * @memberof PIXI
   */
  var Bounds = /** @class */ (function () {
      function Bounds() {
          this.minX = Infinity;
          this.minY = Infinity;
          this.maxX = -Infinity;
          this.maxY = -Infinity;
          this.rect = null;
          this.updateID = -1;
      }
      /**
       * Checks if bounds are empty.
       *
       * @return - True if empty.
       */
      Bounds.prototype.isEmpty = function () {
          return this.minX > this.maxX || this.minY > this.maxY;
      };
      /** Clears the bounds and resets. */
      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 rect - Temporary object will be used if AABB is not empty
       * @returns - A rectangle of the bounds
       */
      Bounds.prototype.getRectangle = function (rect) {
          if (this.minX > this.maxX || this.minY > this.maxY) {
              return Rectangle.EMPTY;
          }
          rect = rect || new 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 point - The point to add.
       */
      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);
      };
      /** Adds a point, after transformed. This should be inlined when its possible. */
      Bounds.prototype.addPointMatrix = function (matrix, point) {
          var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty;
          var x = (a * point.x) + (c * point.y) + tx;
          var y = (b * point.x) + (d * point.y) + ty;
          this.minX = Math.min(this.minX, x);
          this.maxX = Math.max(this.maxX, x);
          this.minY = Math.min(this.minY, y);
          this.maxY = Math.max(this.maxY, y);
      };
      /**
       * Adds a quad, not transformed
       *
       * @param vertices - The verts to add.
       */
      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;
      };
      /**
       * Adds sprite frame, transformed.
       *
       * @param transform - transform to apply
       * @param x0 - left X of frame
       * @param y0 - top Y of frame
       * @param x1 - right X of frame
       * @param y1 - bottom Y of frame
       */
      Bounds.prototype.addFrame = function (transform, x0, y0, x1, y1) {
          this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1);
      };
      /**
       * Adds sprite frame, multiplied by matrix
       *
       * @param matrix - matrix to apply
       * @param x0 - left X of frame
       * @param y0 - top Y of frame
       * @param x1 - right X of frame
       * @param y1 - bottom Y of frame
       */
      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;
      };
      /**
       * Adds screen vertices from array
       *
       * @param vertexData - calculated vertices
       * @param beginOffset - begin offset
       * @param endOffset - end offset, excluded
       */
      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 transform - mesh transform
       * @param vertices - mesh coordinates in array
       * @param beginOffset - begin offset
       * @param 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 matrix - mesh matrix
       * @param vertices - mesh coordinates in array
       * @param beginOffset - begin offset
       * @param endOffset - end offset, excluded
       * @param padX - x padding
       * @param padY - 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);
          }
          this.minX = minX;
          this.minY = minY;
          this.maxX = maxX;
          this.maxY = maxY;
      };
      /**
       * Adds other {@link Bounds}.
       *
       * @param bounds - The Bounds to be added
       */
      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;
      };
      /**
       * Adds other Bounds, masked with Bounds.
       *
       * @param bounds - The Bounds to be added.
       * @param mask - TODO
       */
      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;
          }
      };
      /**
       * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty.
       *
       * @param bounds - other bounds
       * @param matrix - multiplicator
       */
      Bounds.prototype.addBoundsMatrix = function (bounds, matrix) {
          this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
      };
      /**
       * Adds other Bounds, masked with Rectangle.
       *
       * @param bounds - TODO
       * @param area - TODO
       */
      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;
          }
      };
      /**
       * Pads bounds object, making it grow in all directions.
       * If paddingY is omitted, both paddingX and paddingY will be set to paddingX.
       *
       * @param paddingX - The horizontal padding amount.
       * @param paddingY - The vertical padding amount.
       */
      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 x0 - left X of frame
       * @param y0 - top Y of frame
       * @param x1 - right X of frame
       * @param y1 - bottom Y of frame
       * @param padX - padding X
       * @param 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;
  }());

  /*! *****************************************************************************
  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 base class for all objects that are rendered on the screen.
   *
   * This is an abstract class and can not be used on its own; rather it should be extended.
   *
   * ## Display objects implemented in PixiJS
   *
   * | Display Object                  | Description                                                           |
   * | ------------------------------- | --------------------------------------------------------------------- |
   * | {@link PIXI.Container}          | Adds support for `children` to DisplayObject                          |
   * | {@link PIXI.Graphics}           | Shape-drawing display object similar to the Canvas API                |
   * | {@link PIXI.Sprite}             | Draws textures (i.e. images)                                          |
   * | {@link PIXI.Text}               | Draws text using the Canvas API internally                            |
   * | {@link PIXI.BitmapText}         | More scaleable solution for text rendering, reusing glyph textures    |
   * | {@link PIXI.TilingSprite}       | Draws textures/images in a tiled fashion                              |
   * | {@link PIXI.AnimatedSprite}     | Draws an animation of multiple images                                 |
   * | {@link PIXI.Mesh}               | Provides a lower-level API for drawing meshes with custom data        |
   * | {@link PIXI.NineSlicePlane}     | Mesh-related                                                          |
   * | {@link PIXI.SimpleMesh}         | v4-compatible mesh                                                    |
   * | {@link PIXI.SimplePlane}        | Mesh-related                                                          |
   * | {@link PIXI.SimpleRope}         | Mesh-related                                                          |
   *
   * ## Transforms
   *
   * The [transform]{@link DisplayObject#transform} of a display object describes the projection from its
   * local coordinate space to its parent's local coordinate space. The following properties are derived
   * from the transform:
   *
   * <table>
   *   <thead>
   *     <tr>
   *       <th>Property</th>
   *       <th>Description</th>
   *     </tr>
   *   </thead>
   *   <tbody>
   *     <tr>
   *       <td>[pivot]{@link PIXI.DisplayObject#pivot}</td>
   *       <td>
   *         Invariant under rotation, scaling, and skewing. The projection of into the parent's space of the pivot
   *         is equal to position, regardless of the other three transformations. In other words, It is the center of
   *         rotation, scaling, and skewing.
   *       </td>
   *     </tr>
   *     <tr>
   *       <td>[position]{@link PIXI.DisplayObject#position}</td>
   *       <td>
   *         Translation. This is the position of the [pivot]{@link PIXI.DisplayObject#pivot} in the parent's local
   *         space. The default value of the pivot is the origin (0,0). If the top-left corner of your display object
   *         is (0,0) in its local space, then the position will be its top-left corner in the parent's local space.
   *       </td>
   *     </tr>
   *     <tr>
   *       <td>[scale]{@link PIXI.DisplayObject#scale}</td>
   *       <td>
   *         Scaling. This will stretch (or compress) the display object's projection. The scale factors are along the
   *         local coordinate axes. In other words, the display object is scaled before rotated or skewed. The center
   *         of scaling is the [pivot]{@link PIXI.DisplayObject#pivot}.
   *       </td>
   *     </tr>
   *     <tr>
   *       <td>[rotation]{@link PIXI.DisplayObject#rotation}</td>
   *       <td>
   *          Rotation. This will rotate the display object's projection by this angle (in radians).
   *       </td>
   *     </tr>
   *     <tr>
   *       <td>[skew]{@link PIXI.DisplayObject#skew}</td>
   *       <td>
   *         <p>Skewing. This can be used to deform a rectangular display object into a parallelogram.</p>
   *         <p>
   *         In PixiJS, skew has a slightly different behaviour than the conventional meaning. It can be
   *         thought of the net rotation applied to the coordinate axes (separately). For example, if "skew.x" is
   *         ⍺ and "skew.y" is β, then the line x = 0 will be rotated by ⍺ (y = -x*cot⍺) and the line y = 0 will be
   *         rotated by β (y = x*tanβ). A line y = x*tanϴ (i.e. a line at angle ϴ to the x-axis in local-space) will
   *         be rotated by an angle between ⍺ and β.
   *         </p>
   *         <p>
   *         It can be observed that if skew is applied equally to both axes, then it will be equivalent to applying
   *         a rotation. Indeed, if "skew.x" = -ϴ and "skew.y" = ϴ, it will produce an equivalent of "rotation" = ϴ.
   *         </p>
   *         <p>
   *         Another quite interesting observation is that "skew.x", "skew.y", rotation are communtative operations. Indeed,
   *         because rotation is essentially a careful combination of the two.
   *         </p>
   *       </td>
   *     </tr>
   *     <tr>
   *       <td>angle</td>
   *       <td>Rotation. This is an alias for [rotation]{@link PIXI.DisplayObject#rotation}, but in degrees.</td>
   *     </tr>
   *     <tr>
   *       <td>x</td>
   *       <td>Translation. This is an alias for position.x!</td>
   *     </tr>
   *     <tr>
   *       <td>y</td>
   *       <td>Translation. This is an alias for position.y!</td>
   *     </tr>
   *     <tr>
   *       <td>width</td>
   *       <td>
   *         Implemented in [Container]{@link PIXI.Container}. Scaling. The width property calculates scale.x by dividing
   *         the "requested" width by the local bounding box width. It is indirectly an abstraction over scale.x, and there
   *         is no concept of user-defined width.
   *       </td>
   *     </tr>
   *     <tr>
   *       <td>height</td>
   *       <td>
   *         Implemented in [Container]{@link PIXI.Container}. Scaling. The height property calculates scale.y by dividing
   *         the "requested" height by the local bounding box height. It is indirectly an abstraction over scale.y, and there
   *         is no concept of user-defined height.
   *       </td>
   *     </tr>
   *   </tbody>
   * </table>
   *
   * ## Bounds
   *
   * The bounds of a display object is defined by the minimum axis-aligned rectangle in world space that can fit
   * around it. The abstract `calculateBounds` method is responsible for providing it (and it should use the
   * `worldTransform` to calculate in world space).
   *
   * There are a few additional types of bounding boxes:
   *
   * | Bounds                | Description                                                                              |
   * | --------------------- | ---------------------------------------------------------------------------------------- |
   * | World Bounds          | This is synonymous is the regular bounds described above. See `getBounds()`.             |
   * | Local Bounds          | This the axis-aligned bounding box in the parent's local space. See `getLocalBounds()`.  |
   * | Render Bounds         | The bounds, but including extra rendering effects like filter padding.                   |
   * | Projected Bounds      | The bounds of the projected display object onto the screen. Usually equals world bounds. |
   * | Relative Bounds       | The bounds of a display object when projected onto a ancestor's (or parent's) space.     |
   * | Natural Bounds        | The bounds of an object in its own local space (not parent's space, like in local bounds)|
   * | Content Bounds        | The natural bounds when excluding all children of a `Container`.                         |
   *
   * ### calculateBounds
   *
   * [Container]{@link Container} already implements `calculateBounds` in a manner that includes children.
   *
   * But for a non-Container display object, the `calculateBounds` method must be overridden in order for `getBounds` and
   * `getLocalBounds` to work. This method must write the bounds into `this._bounds`.
   *
   * Generally, the following technique works for most simple cases: take the list of points
   * forming the "hull" of the object (i.e. outline of the object's shape), and then add them
   * using {@link PIXI.Bounds#addPointMatrix}.
   *
   * ```js
   * calculateBounds(): void
   * {
   *     const points = [...];
   *
   *     for (let i = 0, j = points.length; i < j; i++)
   *     {
   *         this._bounds.addPointMatrix(this.worldTransform, points[i]);
   *     }
   * }
   * ```
   *
   * You can optimize this for a large number of points by using {@link PIXI.Bounds#addVerticesMatrix} to pass them
   * in one array together.
   *
   * ## Alpha
   *
   * This alpha sets a display object's **relative opacity** w.r.t its parent. For example, if the alpha of a display
   * object is 0.5 and its parent's alpha is 0.5, then it will be rendered with 25% opacity (assuming alpha is not
   * applied on any ancestor further up the chain).
   *
   * The alpha with which the display object will be rendered is called the [worldAlpha]{@link PIXI.DisplayObject#worldAlpha}.
   *
   * ## Renderable vs Visible
   *
   * The `renderable` and `visible` properties can be used to prevent a display object from being rendered to the
   * screen. However, there is a subtle difference between the two. When using `renderable`, the transforms  of the display
   * object (and its children subtree) will continue to be calculated. When using `visible`, the transforms will not
   * be calculated.
   *
   * It is recommended that applications use the `renderable` property for culling. See
   * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} or
   * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull} for more details.
   *
   * Otherwise, to prevent an object from rendering in the general-purpose sense - `visible` is the property to use. This
   * one is also better in terms of performance.
   *
   * @memberof PIXI
   */
  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
          _this.transform = new Transform();
          _this.alpha = 1;
          _this.visible = true;
          _this.renderable = true;
          _this.cullable = false;
          _this.cullArea = null;
          _this.parent = null;
          _this.worldAlpha = 1;
          _this._lastSortedIndex = 0;
          _this._zIndex = 0;
          _this.filterArea = null;
          _this.filters = null;
          _this._enabledFilters = null;
          _this._bounds = new Bounds();
          _this._localBounds = null;
          _this._boundsID = 0;
          _this._boundsRect = null;
          _this._localBoundsRect = null;
          _this._mask = null;
          _this._maskRefCount = 0;
          _this._destroyed = false;
          _this.isSprite = false;
          _this.isMask = false;
          return _this;
      }
      /**
       * Mixes all enumerable properties and methods from a source object to DisplayObject.
       *
       * @param source - The source of properties and methods to mix in.
       */
      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));
          }
      };
      Object.defineProperty(DisplayObject.prototype, "destroyed", {
          /**
           * Fired when this DisplayObject is added to a Container.
           *
           * @instance
           * @event added
           * @param {PIXI.Container} container - The container added to.
           */
          /**
           * Fired when this DisplayObject is removed from a Container.
           *
           * @instance
           * @event removed
           * @param {PIXI.Container} container - The container removed from.
           */
          /**
           * Fired when this DisplayObject is destroyed.
           *
           * @instance
           * @event destroyed
           */
          /** Readonly flag for destroyed display objects. */
          get: function () {
              return this._destroyed;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Recursively updates transform of all objects from the root to this one
       * internal function for toLocal()
       */
      DisplayObject.prototype._recursivePostUpdateTransform = function () {
          if (this.parent) {
              this.parent._recursivePostUpdateTransform();
              this.transform.updateTransform(this.parent.transform);
          }
          else {
              this.transform.updateTransform(this._tempDisplayObjectParent.transform);
          }
      };
      /**
       * Updates the object transform for rendering.
       *
       * TODO - Optimization pass!
       */
      DisplayObject.prototype.updateTransform = function () {
          this._boundsID++;
          this.transform.updateTransform(this.parent.transform);
          // multiply the alphas..
          this.worldAlpha = this.alpha * this.parent.worldAlpha;
      };
      /**
       * Calculates and returns the (world) bounds of the display object as a [Rectangle]{@link PIXI.Rectangle}.
       *
       * This method is expensive on containers with a large subtree (like the stage). This is because the bounds
       * of a container depend on its children's bounds, which recursively causes all bounds in the subtree to
       * be recalculated. The upside, however, is that calling `getBounds` once on a container will indeed update
       * the bounds of all children (the whole subtree, in fact). This side effect should be exploited by using
       * `displayObject._bounds.getRectangle()` when traversing through all the bounds in a scene graph. Otherwise,
       * calling `getBounds` on each object in a subtree will cause the total cost to increase quadratically as
       * its height increases.
       *
       * * The transforms of all objects in a container's **subtree** and of all **ancestors** are updated.
       * * The world bounds of all display objects in a container's **subtree** will also be recalculated.
       *
       * The `_bounds` object stores the last calculation of the bounds. You can use to entirely skip bounds
       * calculation if needed.
       *
       * ```js
       * const lastCalculatedBounds = displayObject._bounds.getRectangle(optionalRect);
       * ```
       *
       * Do know that usage of `getLocalBounds` can corrupt the `_bounds` of children (the whole subtree, actually). This
       * is a known issue that has not been solved. See [getLocalBounds]{@link PIXI.DisplayObject#getLocalBounds} for more
       * details.
       *
       * `getBounds` should be called with `skipUpdate` equal to `true` in a render() call. This is because the transforms
       * are guaranteed to be update-to-date. In fact, recalculating inside a render() call may cause corruption in certain
       * cases.
       *
       * @param 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 rect - Optional rectangle to store the result of the bounds calculation.
       * @return - The minimum axis-aligned rectangle in world space that fits around this object.
       */
      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 Rectangle();
              }
              rect = this._boundsRect;
          }
          return this._bounds.getRectangle(rect);
      };
      /**
       * Retrieves the local bounds of the displayObject as a rectangle object.
       *
       * @param rect - Optional rectangle to store the result of the bounds calculation.
       * @return - The rectangular bounding area.
       */
      DisplayObject.prototype.getLocalBounds = function (rect) {
          if (!rect) {
              if (!this._localBoundsRect) {
                  this._localBoundsRect = new 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;
      };
      /**
       * Calculates the global position of the display object.
       *
       * @param position - The world origin to calculate from.
       * @param point - A Point object in which to store the value, optional
       *  (otherwise will create a new Point).
       * @param skipUpdate - Should we skip the update transform.
       * @return - A point object representing the position of this object.
       */
      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);
      };
      /**
       * Calculates the local position of the display object relative to another point.
       *
       * @param position - The world origin to calculate from.
       * @param from - The DisplayObject to calculate the global position from.
       * @param point - A Point object in which to store the value, optional
       *  (otherwise will create a new Point).
       * @param skipUpdate - Should we skip the update transform
       * @return - A point object representing the position of this object
       */
      DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) {
          if (from) {
              position = from.toGlobal(position, point, skipUpdate);
          }
          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();
              }
          }
          // simply apply the matrix..
          return this.worldTransform.applyInverse(position, point);
      };
      /**
       * Set the parent Container of this DisplayObject.
       *
       * @param container - The Container to add this DisplayObject to.
       * @return - The Container that this DisplayObject was added to.
       */
      DisplayObject.prototype.setParent = function (container) {
          if (!container || !container.addChild) {
              throw new Error('setParent: Argument must be a Container');
          }
          container.addChild(this);
          return container;
      };
      /**
       * Convenience function to set the position, scale, skew and pivot at once.
       *
       * @param x - The X position
       * @param y - The Y position
       * @param scaleX - The X scale value
       * @param scaleY - The Y scale value
       * @param rotation - The rotation
       * @param skewX - The X skew value
       * @param skewY - The Y skew value
       * @param pivotX - The X pivot value
       * @param pivotY - The Y pivot value
       * @return - The DisplayObject instance
       */
      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;
      };
      /**
       * 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()`.
       */
      DisplayObject.prototype.destroy = function (_options) {
          if (this.parent) {
              this.parent.removeChild(this);
          }
          this.emit('destroyed');
          this.removeAllListeners();
          this.transform = null;
          this.parent = null;
          this._bounds = null;
          this.mask = null;
          this.cullArea = 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 @typescript-eslint/no-use-before-define
                  this.tempDisplayObjectParent = new TemporaryDisplayObject();
              }
              return this.tempDisplayObjectParent;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Used in Renderer, cacheAsBitmap and other places where you call an `updateTransform` on root
       *
       * ```
       * const cacheParent = elem.enableTempParent();
       * elem.updateTransform();
       * elem.disableTempParent(cacheParent);
       * ```
       *
       * @returns - current parent
       */
      DisplayObject.prototype.enableTempParent = function () {
          var myParent = this.parent;
          this.parent = this._tempDisplayObjectParent;
          return myParent;
      };
      /**
       * Pair method for `enableTempParent`
       *
       * @param cacheParent - Actual parent of element
       */
      DisplayObject.prototype.disableTempParent = function (cacheParent) {
          this.parent = cacheParent;
      };
      Object.defineProperty(DisplayObject.prototype, "x", {
          /**
           * The position of the displayObject on the x axis relative to the local coordinates of the parent.
           * An alias to position.x
           */
          get: function () {
              return this.position.x;
          },
          set: function (value) {
              this.transform.position.x = value;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(DisplayObject.prototype, "y", {
          /**
           * The position of the displayObject on the y axis relative to the local coordinates of the parent.
           * An alias to position.y
           */
          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.
           *
           * @readonly
           */
          get: function () {
              return this.transform.worldTransform;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(DisplayObject.prototype, "localTransform", {
          /**
           * Current transform of the object based on local factors: position, scale, other stuff.
           *
           * @readonly
           */
          get: function () {
              return this.transform.localTransform;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(DisplayObject.prototype, "position", {
          /**
           * The coordinate of the object relative to the local coordinates of the parent.
           *
           * @since PixiJS 4
           */
          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 factors of this object along the local coordinate axes.
           *
           * The default scale is (1, 1).
           *
           * @since PixiJS 4
           */
          get: function () {
              return this.transform.scale;
          },
          set: function (value) {
              this.transform.scale.copyFrom(value);
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(DisplayObject.prototype, "pivot", {
          /**
           * The center of rotation, scaling, and skewing for this display object in its local space. The `position`
           * is the projection of `pivot` in the parent's local space.
           *
           * By default, the pivot is the origin (0, 0).
           *
           * @since PixiJS 4
           */
          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.
           *
           * @since PixiJS 4
           */
          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.
           */
          get: function () {
              return this.transform.rotation;
          },
          set: function (value) {
              this.transform.rotation = value;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(DisplayObject.prototype, "angle", {
          /**
           * 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.
           */
          get: function () {
              return this.transform.rotation * RAD_TO_DEG;
          },
          set: function (value) {
              this.transform.rotation = value * DEG_TO_RAD;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(DisplayObject.prototype, "zIndex", {
          /**
           * 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 display objects within the same container.
           *
           * @see PIXI.Container#sortableChildren
           */
          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", {
          /**
           * Indicates if the object is globally visible.
           *
           * @readonly
           */
          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.
           */
          get: function () {
              return this._mask;
          },
          set: function (value) {
              if (this._mask === value) {
                  return;
              }
              if (this._mask) {
                  var maskObject = (this._mask.maskObject || this._mask);
                  maskObject._maskRefCount--;
                  if (maskObject._maskRefCount === 0) {
                      maskObject.renderable = true;
                      maskObject.isMask = false;
                  }
              }
              this._mask = value;
              if (this._mask) {
                  var maskObject = (this._mask.maskObject || this._mask);
                  if (maskObject._maskRefCount === 0) {
                      maskObject.renderable = false;
                      maskObject.isMask = true;
                  }
                  maskObject._maskRefCount++;
              }
          },
          enumerable: false,
          configurable: true
      });
      return DisplayObject;
  }(eventemitter3));
  /**
   * @private
   */
  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#
   * @method displayObjectUpdateTransform
   */
  DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform;

  /*!
   * @pixi/constants - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/constants is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */
  /**
   * 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$1;
  (function (ENV) {
      ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY";
      ENV[ENV["WEBGL"] = 1] = "WEBGL";
      ENV[ENV["WEBGL2"] = 2] = "WEBGL2";
  })(ENV$1 || (ENV$1 = {}));
  /**
   * 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$1;
  (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$1 || (RENDERER_TYPE$1 = {}));
  /**
   * 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$1;
  (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$1 || (BUFFER_BITS$1 = {}));
  /**
   * 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$1;
  (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$1 || (BLEND_MODES$1 = {}));
  /**
   * 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$1;
  (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$1 || (DRAW_MODES$1 = {}));
  /**
   * Various GL texture/resources formats.
   *
   * @memberof PIXI
   * @static
   * @name FORMATS
   * @enum {number}
   * @property {number} RGBA=6408
   * @property {number} RGB=6407
   * @property {number} RG=33319
   * @property {number} RED=6403
   * @property {number} RGBA_INTEGER=36249
   * @property {number} RGB_INTEGER=36248
   * @property {number} RG_INTEGER=33320
   * @property {number} RED_INTEGER=36244
   * @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$1;
  (function (FORMATS) {
      FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
      FORMATS[FORMATS["RGB"] = 6407] = "RGB";
      FORMATS[FORMATS["RG"] = 33319] = "RG";
      FORMATS[FORMATS["RED"] = 6403] = "RED";
      FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
      FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
      FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
      FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
      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$1 || (FORMATS$1 = {}));
  /**
   * 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$1;
  (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$1 || (TARGETS$1 = {}));
  /**
   * 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} UNSIGNED_INT=5125
   * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
   * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
   * @property {number} UNSIGNED_INT_24_8=34042
   * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
   * @property {number} BYTE=5120
   * @property {number} SHORT=5122
   * @property {number} INT=5124
   * @property {number} FLOAT=5126
   * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
   * @property {number} HALF_FLOAT=36193
   */
  var TYPES$1;
  (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["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
      TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
      TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
      TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
      TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
      TYPES[TYPES["BYTE"] = 5120] = "BYTE";
      TYPES[TYPES["SHORT"] = 5122] = "SHORT";
      TYPES[TYPES["INT"] = 5124] = "INT";
      TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
      TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
      TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
  })(TYPES$1 || (TYPES$1 = {}));
  /**
   * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
   * WebGL1 works only with FLOAT.
   *
   * @memberof PIXI
   * @static
   * @name SAMPLER_TYPES
   * @enum {number}
   * @property {number} FLOAT=0
   * @property {number} INT=1
   * @property {number} UINT=2
   */
  var SAMPLER_TYPES$1;
  (function (SAMPLER_TYPES) {
      SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
      SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
      SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
  })(SAMPLER_TYPES$1 || (SAMPLER_TYPES$1 = {}));
  /**
   * 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$1;
  (function (SCALE_MODES) {
      SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
      SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
  })(SCALE_MODES$1 || (SCALE_MODES$1 = {}));
  /**
   * 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$1;
  (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$1 || (WRAP_MODES$1 = {}));
  /**
   * 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
   * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
   *   that supports buffering each level-of-detail.
   */
  var MIPMAP_MODES$1;
  (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["ON_MANUAL"] = 3] = "ON_MANUAL";
  })(MIPMAP_MODES$1 || (MIPMAP_MODES$1 = {}));
  /**
   * 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$1;
  (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["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
  })(ALPHA_MODES$1 || (ALPHA_MODES$1 = {}));
  /**
   * Configure whether filter textures are cleared after binding.
   *
   * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
   * this and skip clearing as an optimization.
   *
   * @name CLEAR_MODES
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
   * @property {number} CLEAR - Always clear the filter texture.
   * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
   * @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$1;
  (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$1 || (CLEAR_MODES$1 = {}));
  /**
   * 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$1;
  (function (GC_MODES) {
      GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
      GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
  })(GC_MODES$1 || (GC_MODES$1 = {}));
  /**
   * 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$1;
  (function (PRECISION) {
      PRECISION["LOW"] = "lowp";
      PRECISION["MEDIUM"] = "mediump";
      PRECISION["HIGH"] = "highp";
  })(PRECISION$1 || (PRECISION$1 = {}));
  /**
   * 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$1;
  (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$1 || (MASK_TYPES$1 = {}));
  /**
   * 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$1;
  (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$1 || (MSAA_QUALITY$1 = {}));
  /**
   * Constants for various buffer types in Pixi
   *
   * @see PIXI.BUFFER_TYPE
   *
   * @name BUFFER_TYPE
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
   * @property {number} ARRAY_BUFFER - buffer type for using attribute data
   * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
   */
  var BUFFER_TYPE$1;
  (function (BUFFER_TYPE) {
      BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
      BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
      // NOT YET SUPPORTED
      BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
  })(BUFFER_TYPE$1 || (BUFFER_TYPE$1 = {}));

  function sortChildren(a, b) {
      if (a.zIndex === b.zIndex) {
          return a._lastSortedIndex - b._lastSortedIndex;
      }
      return a.zIndex - b.zIndex;
  }
  /**
   * Container is a general-purpose display object that holds children. It also adds built-in support for advanced
   * rendering features like masking and filtering.
   *
   * It is the base class of all display objects that act as a container for other objects, including Graphics
   * and Sprite.
   *
   * ```js
   * import { BlurFilter } from '@pixi/filter-blur';
   * import { Container } from '@pixi/display';
   * import { Graphics } from '@pixi/graphics';
   * import { Sprite } from '@pixi/sprite';
   *
   * let container = new Container();
   * let sprite = Sprite.from("https://s3-us-west-2.amazonaws.com/s.cdpn.io/693612/IaUrttj.png");
   *
   * sprite.width = 512;
   * sprite.height = 512;
   *
   * // Adds a sprite as a child to this container. As a result, the sprite will be rendered whenever the container
   * // is rendered.
   * container.addChild(sprite);
   *
   * // Blurs whatever is rendered by the container
   * container.filters = [new BlurFilter()];
   *
   * // Only the contents within a circle at the center should be rendered onto the screen.
   * container.mask = new Graphics()
   *  .beginFill(0xffffff)
   *  .drawCircle(sprite.width / 2, sprite.height / 2, Math.min(sprite.width, sprite.height) / 2)
   *  .endFill();
   * ```
   *
   * @memberof PIXI
   */
  var Container = /** @class */ (function (_super) {
      __extends(Container, _super);
      function Container() {
          var _this = _super.call(this) || this;
          _this.children = [];
          _this.sortableChildren = settings.SORTABLE_CHILDREN;
          _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
           */
      }
      /** Overridable method that can be used by Container subclasses whenever the children array is modified. */
      Container.prototype.onChildrenChange = function (_length) {
          /* empty */
      };
      /**
       * Adds one or more children to the container.
       *
       * 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.
       */
      Container.prototype.addChild = 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 array and add all children
              for (var i = 0; i < children.length; i++) {
                  // eslint-disable-next-line prefer-rest-params
                  this.addChild(children[i]);
              }
          }
          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];
      };
      /**
       * 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.
       */
      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);
          }
          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.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 child - First display object to swap
       * @param child2 - Second display object to swap
       */
      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);
      };
      /**
       * Returns the index position of a child DisplayObject instance
       *
       * @param child - The DisplayObject instance to identify
       * @return - The index position of the child display object to identify
       */
      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;
      };
      /**
       * Changes the position of an existing child in the display object container
       *
       * @param child - The child DisplayObject instance for which you want to change the index number
       * @param index - The resulting index number for the child display object
       */
      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);
          removeItems(this.children, currentIndex, 1); // remove from old position
          this.children.splice(index, 0, child); // add at new position
          this.onChildrenChange(index);
      };
      /**
       * Returns the child at the specified index
       *
       * @param index - The index to get the child at
       * @return - The child at the given index, if any.
       */
      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];
      };
      /**
       * Removes one or more children from the container.
       *
       * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to remove
       * @return {PIXI.DisplayObject} The first child that was removed.
       */
      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;
              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];
      };
      /**
       * Removes a child from the specified index position.
       *
       * @param index - The index to get the child from
       * @return The child that was removed.
       */
      Container.prototype.removeChildAt = function (index) {
          var child = this.getChildAt(index);
          // ensure child transform will be recalculated..
          child.parent = null;
          child.transform._parentID = -1;
          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 beginIndex - The beginning position.
       * @param endIndex - The ending position. Default value is size of the container.
       * @returns - 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 (range === 0 && this.children.length === 0) {
              return [];
          }
          throw new RangeError('removeChildren: numeric values are outside the acceptable range.');
      };
      /** Sorts children by zIndex. Previous order is maintained for 2 children with the same zIndex. */
      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;
      };
      /** Updates the transform on all children of this container for rendering. */
      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();
              }
          }
      };
      /**
       * Recalculates the bounds of the container.
       *
       * This implementation will automatically fit the children's bounds into the calculation. Each child's bounds
       * is limited to its mask's bounds or filterArea, if any is applied.
       */
      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;
      };
      /**
       * Retrieves the local bounds of the displayObject as a rectangle object.
       *
       * Calling `getLocalBounds` may invalidate the `_bounds` of the whole subtree below. If using it inside a render()
       * call, it is advised to call `getBounds()` immediately after to recalculate the world bounds of the subtree.
       *
       * @param rect - Optional rectangle to store the result of the bounds calculation.
       * @param skipChildrenUpdate - 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 - The rectangular bounding area.
       */
      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;
      };
      /**
       * Recalculates the content bounds of this object. This should be overriden to
       * calculate the bounds of this specific object (not including children).
       *
       * @protected
       */
      Container.prototype._calculateBounds = function () {
          // FILL IN//
      };
      /**
       * Renders this object and its children with culling.
       *
       * @protected
       * @param {PIXI.Renderer} renderer - The renderer
       */
      Container.prototype._renderWithCulling = function (renderer) {
          var sourceFrame = renderer.renderTexture.sourceFrame;
          // If the source frame is empty, stop rendering.
          if (!(sourceFrame.width > 0 && sourceFrame.height > 0)) {
              return;
          }
          // Render the content of the container only if its bounds intersect with the source frame.
          // All filters are on the stack at this point, and the filter source frame is bound:
          // therefore, even if the bounds to non intersect the filter frame, the filter
          // is still applied and any filter padding that is in the frame is rendered correctly.
          var bounds;
          var transform;
          // If cullArea is set, we use this rectangle instead of the bounds of the object. The cullArea
          // rectangle must completely contain the container and its children including filter padding.
          if (this.cullArea) {
              bounds = this.cullArea;
              transform = this.worldTransform;
          }
          // If the container doesn't override _render, we can skip the bounds calculation and intersection test.
          else if (this._render !== Container.prototype._render) {
              bounds = this.getBounds(true);
          }
          // Render the container if the source frame intersects the bounds.
          if (bounds && sourceFrame.intersects(bounds, transform)) {
              this._render(renderer);
          }
          // If the bounds are defined by cullArea and do not intersect with the source frame, stop rendering.
          else if (this.cullArea) {
              return;
          }
          // Unless cullArea is set, we cannot skip the children if the bounds of the container do not intersect
          // the source frame, because the children might have filters with nonzero padding, which may intersect
          // with the source frame while the bounds do not: filter padding is not included in the bounds.
          // If cullArea is not set, render the children with culling temporarily enabled so that they are not rendered
          // if they are out of frame; otherwise, render the children normally.
          for (var i = 0, j = this.children.length; i < j; ++i) {
              var child = this.children[i];
              var childCullable = child.cullable;
              child.cullable = childCullable || !this.cullArea;
              child.render(renderer);
              child.cullable = childCullable;
          }
      };
      /**
       * Renders the object using the WebGL renderer.
       *
       * The [_render]{@link PIXI.Container#_render} method is be overriden for rendering the contents of the
       * container itself. This `render` method will invoke it, and also invoke the `render` methods of all
       * children afterward.
       *
       * If `renderable` or `visible` is false or if `worldAlpha` is not positive or if `cullable` is true and
       * the bounds of this object are out of frame, this implementation will entirely skip rendering.
       * See {@link PIXI.DisplayObject} for choosing between `renderable` or `visible`. Generally,
       * setting alpha to zero is not recommended for purely skipping rendering.
       *
       * When your scene becomes large (especially when it is larger than can be viewed in a single screen), it is
       * advised to employ **culling** to automatically skip rendering objects outside of the current screen.
       * See [cullable]{@link PIXI.DisplayObject#cullable} and [cullArea]{@link PIXI.DisplayObject#cullArea}.
       * Other culling methods might be better suited for a large number static objects; see
       * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} and
       * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull}.
       *
       * The [renderAdvanced]{@link PIXI.Container#renderAdvanced} method is internally used when when masking or
       * filtering is applied on a container. This does, however, break batching and can affect performance when
       * masking and filtering is applied extensively throughout the scene graph.
       *
       * @param renderer - The renderer
       */
      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;
          }
          // 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 if (this.cullable) {
              this._renderWithCulling(renderer);
          }
          else {
              this._render(renderer);
              for (var i = 0, j = this.children.length; i < j; ++i) {
                  this.children[i].render(renderer);
              }
          }
      };
      /**
       * Render the object using the WebGL renderer and advanced features.
       *
       * @param renderer - The renderer
       */
      Container.prototype.renderAdvanced = function (renderer) {
          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]);
                  }
              }
          }
          var flush = (filters && this._enabledFilters && this._enabledFilters.length)
              || (mask && (!mask.isMaskData
                  || (mask.enabled && (mask.autoDetect || mask.type !== MASK_TYPES$1.NONE))));
          if (flush) {
              renderer.batch.flush();
          }
          if (filters && this._enabledFilters && this._enabledFilters.length) {
              renderer.filter.push(this, this._enabledFilters);
          }
          if (mask) {
              renderer.mask.push(this, this._mask);
          }
          if (this.cullable) {
              this._renderWithCulling(renderer);
          }
          else {
              this._render(renderer);
              for (var i = 0, j = this.children.length; i < j; ++i) {
                  this.children[i].render(renderer);
              }
          }
          if (flush) {
              renderer.batch.flush();
          }
          if (mask) {
              renderer.mask.pop(this);
          }
          if (filters && this._enabledFilters && this._enabledFilters.length) {
              renderer.filter.pop();
          }
      };
      /**
       * To be overridden by the subclasses.
       *
       * @param renderer - The renderer
       */
      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 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. */
          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. */
          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#
   * @method containerUpdateTransform
   */
  Container.prototype.containerUpdateTransform = Container.prototype.updateTransform;

  /*!
   * @pixi/accessibility - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/accessibility is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * 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,
  };

  // add some extra variables to the container..
  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) {
          /** Setting this to true will visually show the divs. */
          this.debug = false;
          /** Internal variable, see isActive getter. */
          this._isActive = false;
          /** Internal variable, see isMobileAccessibility getter. */
          this._isMobileAccessibility = false;
          /** A simple pool for storing divs. */
          this.pool = [];
          /** This is a tick used to check if an object is no longer being rendered. */
          this.renderId = 0;
          /** The array of currently active accessible items. */
          this.children = [];
          /** Count to throttle div updates on android devices. */
          this.androidUpdateCount = 0;
          /**  The frequency to update the div elements. */
          this.androidUpdateFrequency = 500; // 2fps
          this._hookDiv = null;
          if (isMobile$1.tablet || isMobile$1.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.div = div;
          this.renderer = renderer;
          /**
           * 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);
          // let listen for tab.. once pressed we can fire up and show the accessibility layer
          globalThis.addEventListener('keydown', this._onKeyDown, false);
      }
      Object.defineProperty(AccessibilityManager.prototype, "isActive", {
          /**
           * Value of `true` if accessibility is currently active and accessibility layers are showing.
           * @member {boolean}
           * @readonly
           */
          get: function () {
              return this._isActive;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", {
          /**
           * Value of `true` if accessibility is enabled for touch devices.
           * @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 accessibility 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 () {
          var _a;
          if (this._isActive) {
              return;
          }
          this._isActive = true;
          globalThis.document.addEventListener('mousemove', this._onMouseMove, true);
          globalThis.removeEventListener('keydown', this._onKeyDown, false);
          this.renderer.on('postrender', this.update, this);
          (_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.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 () {
          var _a;
          if (!this._isActive || this._isMobileAccessibility) {
              return;
          }
          this._isActive = false;
          globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
          globalThis.addEventListener('keydown', this._onKeyDown, false);
          this.renderer.off('postrender', this.update);
          (_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.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;
          if (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 (isMobile$1.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);
          }
          var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height;
          var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution;
          var sx = (width / viewWidth) * resolution;
          var sy = (height / viewHeight) * resolution;
          var div = this.div;
          div.style.left = left + "px";
          div.style.top = top + "px";
          div.style.width = viewWidth + "px";
          div.style.height = viewHeight + "px";
          for (var i = 0; i < this.children.length; i++) {
              var child = this.children[i];
              if (child.renderId !== this.renderId) {
                  child._accessibleActive = false;
                  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 + "</br> title : " + div.title + "</br> 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;
          }
          var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height;
          if (hitArea.x + hitArea.width > viewWidth) {
              hitArea.width = viewWidth - hitArea.x;
          }
          if (hitArea.y + hitArea.height > viewHeight) {
              hitArea.height = viewHeight - 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) {
          var interactionManager = this.renderer.plugins.interaction;
          var displayObject = e.target.displayObject;
          var eventData = interactionManager.eventData;
          interactionManager.dispatchEvent(displayObject, 'click', eventData);
          interactionManager.dispatchEvent(displayObject, 'pointertap', eventData);
          interactionManager.dispatchEvent(displayObject, 'tap', 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');
          }
          var interactionManager = this.renderer.plugins.interaction;
          var displayObject = e.target.displayObject;
          var eventData = interactionManager.eventData;
          interactionManager.dispatchEvent(displayObject, 'mouseover', 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');
          }
          var interactionManager = this.renderer.plugins.interaction;
          var displayObject = e.target.displayObject;
          var eventData = interactionManager.eventData;
          interactionManager.dispatchEvent(displayObject, 'mouseout', 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;
          globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
          globalThis.removeEventListener('keydown', this._onKeyDown);
          this.pool = null;
          this.children = null;
          this.renderer = null;
      };
      return AccessibilityManager;
  }());

  /*!
   * @pixi/ticker - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/ticker is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * Target frames per millisecond.
   *
   * @static
   * @name TARGET_FPMS
   * @memberof PIXI.settings
   * @type {number}
   * @default 0.06
   */
  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.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.
   */

  (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 fn - The listener function to be added for one update
       * @param context - The listener context
       * @param priority - The priority for emitting
       * @param once - 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 next item in chain. */
          this.next = null;
          /** The previous item in chain. */
          this.previous = null;
          /** `true` if this listener has been destroyed already. */
          this._destroyed = false;
          this.fn = fn;
          this.context = context;
          this.priority = priority;
          this.once = once;
      }
      /**
       * Simple compare function to figure out if a function and context match.
       * @private
       * @param fn - The listener function to be added for one update
       * @param context - The listener context
       * @return `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 deltaTime - time since the last emit.
       * @return 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 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 hard - `true` to remove the `next` reference, this
       *        is considered a hard destroy. Soft destroy maintains the next reference.
       * @return 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;
          /**
           * Whether or not this ticker should invoke the method
           * {@link PIXI.Ticker#start} automatically
           * when a listener is added.
           */
          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.
           */
          this.deltaTime = 1;
          /**
           * 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.
           */
          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;
           */
          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.
           */
          this.started = false;
          /** Internal current frame request ID */
          this._requestId = null;
          /**
           * Internal value managed by minFPS property setter and getter.
           * This is the maximum allowed milliseconds between updates.
           */
          this._maxElapsedMS = 100;
          /**
           * Internal value managed by minFPS property setter and getter.
           * This is the minimum allowed milliseconds between updates.
           */
          this._minElapsedMS = 0;
          /** If enabled, deleting is disabled.*/
          this._protected = false;
          /**
           * The last time keyframe was executed.
           * Maintains a relatively fixed interval with the previous value.
           */
          this._lastFrame = -1;
          this._head = new TickerListener(null, null, Infinity);
          this.deltaMS = 1 / settings.TARGET_FPMS;
          this.elapsedMS = 1 / settings.TARGET_FPMS;
          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 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 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 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 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 listener - Current listener being added.
       * @returns 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 fn - The listener function to be removed
       * @param context - The listener context to be removed
       * @returns 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;
      };
      Object.defineProperty(Ticker.prototype, "count", {
          /**
           * The number of listeners on this ticker, calculated by walking through linked list
           *
           * @readonly
           * @member {number}
           */
          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
      });
      /**
       * 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.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: 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.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;
  }());

  /**
   * 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
           * @memberof PIXI.Application
           * @instance
           */
          this.stop = function () {
              _this._ticker.stop();
          };
          /**
           * Convenience method for starting the render.
           *
           * @method
           * @memberof PIXI.Application
           * @instance
           */
          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;
  }());

  /*!
   * @pixi/interaction - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/interaction is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * Holds all information related to an Interaction event
   *
   * @memberof PIXI
   */
  var InteractionData = /** @class */ (function () {
      function InteractionData() {
          /**
           * 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
           */
          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
           */
          this.rotationAngle = 0;
          /**
           * Twist of a stylus pointer.
           *
           * @see https://w3c.github.io/pointerevents/#pointerevent-interface
           */
          this.twist = 0;
          /**
           * Barrel pressure on a stylus pointer.
           *
           * @see https://w3c.github.io/pointerevents/#pointerevent-interface
           */
          this.tangentialPressure = 0;
          this.global = new Point();
          this.target = null;
          this.originalEvent = null;
          this.identifier = null;
          this.isPrimary = false;
          this.button = 0;
          this.buttons = 0;
          this.width = 0;
          this.height = 0;
          this.tiltX = 0;
          this.tiltY = 0;
          this.pointerType = null;
          this.pressure = 0;
          this.rotationAngle = 0;
          this.twist = 0;
          this.tangentialPressure = 0;
      }
      Object.defineProperty(InteractionData.prototype, "pointerId", {
          /**
           * The unique identifier of the pointer. It will be the same as `identifier`.
           *
           * @readonly
           * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
           */
          get: function () {
              return this.identifier;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * This will return the local coordinates of the specified displayObject for this InteractionData
       *
       * @param displayObject - The DisplayObject that you would like the local
       *  coords off
       * @param point - A Point object in which to store the value, optional (otherwise
       *  will create a new point)
       * @param globalPos - A Point object containing your custom global coords, optional
       *  (otherwise will use the current global coords)
       * @return - A point containing the coordinates of the InteractionData position relative
       *  to the DisplayObject
       */
      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;
  }());

  /*! *****************************************************************************
  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$1 = function(d, b) {
      extendStatics$1 = 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$1(d, b);
  };

  function __extends$1(d, b) {
      extendStatics$1(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  /**
   * Event class that mimics native DOM events.
   *
   * @memberof PIXI
   */
  var InteractionEvent = /** @class */ (function () {
      function InteractionEvent() {
          this.stopped = false;
          this.stopsPropagatingAt = null;
          this.stopPropagationHint = false;
          this.target = null;
          this.currentTarget = null;
          this.type = null;
          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;
  }());

  /**
   * DisplayObjects with the {@link PIXI.interactiveTarget} mixin use this class to track interactions
   *
   * @class
   * @private
   * @memberof PIXI
   */
  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 {
              this._flags = this._flags & (~flag);
          }
      };
      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;
  }());

  /**
   * Strategy how to search through stage tree for interactive objects
   *
   * @memberof PIXI
   */
  var TreeSearch = /** @class */ (function () {
      function TreeSearch() {
          this._tempPoint = new Point();
      }
      /**
       * Recursive implementation for findHit
       *
       * @private
       * @param interactionEvent - event containing the point that
       *  is tested for collision
       * @param displayObject - the displayObject
       *  that will be hit test (recursively crawls its children)
       * @param func - the function that will be called on each interactive object. The
       *  interactionEvent, displayObject and hit will be passed to the function
       * @param hitTest - this indicates if the objects inside should be hit test against the point
       * @param interactive - Whether the displayObject is interactive
       * @return - Returns true if the displayObject hit the point
       */
      TreeSearch.prototype.recursiveFindHit = function (interactionEvent, displayObject, func, hitTest, interactive) {
          if (!displayObject || !displayObject.visible) {
              return false;
          }
          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;
          }
          // 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 interactionEvent - event containing the point that
       *  is tested for collision
       * @param displayObject - the displayObject
       *  that will be hit test (recursively crawls its children)
       * @param func - the function that will be called on each interactive object. The
       *  interactionEvent, displayObject and hit will be passed to the function
       * @param hitTest - this indicates if the objects inside should be hit test against the point
       * @return - Returns true if the displayObject hit the point
       */
      TreeSearch.prototype.findHit = function (interactionEvent, displayObject, func, hitTest) {
          this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false);
      };
      return TreeSearch;
  }());

  /**
   * 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
   */
  /**
   * 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 = {
      interactive: false,
      interactiveChildren: true,
      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<number, InteractionTrackingData>}
       * @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<number, InteractionTrackingData>}
       */
      _trackedPointers: undefined,
  };

  // Mix interactiveTarget into DisplayObject.prototype
  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.
   *
   * 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`
   *
   * @memberof PIXI
   */
  var InteractionManager = /** @class */ (function (_super) {
      __extends$1(InteractionManager, _super);
      /**
       * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
       * @param 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 frequency (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 || {};
          _this.renderer = renderer;
          _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true;
          _this.interactionFrequency = options.interactionFrequency || 10;
          _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.activeInteractionData = {};
          _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse;
          _this.interactionDataPool = [];
          _this.eventData = new InteractionEvent();
          _this.interactionDOMElement = null;
          _this.moveWhenInside = false;
          _this.eventsAdded = false;
          _this.tickerAdded = false;
          _this.mouseOverRenderer = !('PointerEvent' in globalThis);
          _this.supportsTouchEvents = 'ontouchstart' in globalThis;
          _this.supportsPointerEvents = !!globalThis.PointerEvent;
          // this will make it so that you don't have to call bind all the time
          _this.onPointerUp = _this.onPointerUp.bind(_this);
          _this.processPointerUp = _this.processPointerUp.bind(_this);
          _this.onPointerCancel = _this.onPointerCancel.bind(_this);
          _this.processPointerCancel = _this.processPointerCancel.bind(_this);
          _this.onPointerDown = _this.onPointerDown.bind(_this);
          _this.processPointerDown = _this.processPointerDown.bind(_this);
          _this.onPointerMove = _this.onPointerMove.bind(_this);
          _this.processPointerMove = _this.processPointerMove.bind(_this);
          _this.onPointerOut = _this.onPointerOut.bind(_this);
          _this.processPointerOverOut = _this.processPointerOverOut.bind(_this);
          _this.onPointerOver = _this.onPointerOver.bind(_this);
          _this.cursorStyles = {
              default: 'inherit',
              pointer: 'pointer',
          };
          _this.currentCursorMode = null;
          _this.cursor = null;
          _this.resolution = 1;
          _this.delayedEvents = [];
          _this.search = new TreeSearch();
          _this._tempDisplayObject = new TemporaryDisplayObject();
          _this._eventListenerOptions = { capture: true, passive: false };
          /**
           * 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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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.
           *
           * This comes from the @pixi/interaction package.
           *
           * @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;
      }
      Object.defineProperty(InteractionManager.prototype, "useSystemTicker", {
          /**
           * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}.
           *
           * @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
           */
          get: function () {
              return this.renderer._lastObjectRendered || this._tempDisplayObject;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Hit tests a point against the display tree, returning the first interactive object that is hit.
       *
       * @param globalPoint - A point to hit test with, in global space.
       * @param root - The root display object to start from. If omitted, defaults
       * to the last rendered root of the associated renderer.
       * @return - The hit display object, if any.
       */
      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;
          }
          // 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.
       *
       * @param element - the DOM element which will receive mouse and touch events.
       * @param resolution - The resolution / device pixel ratio of the new element (relative to the canvas).
       */
      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();
      };
      /** Adds the ticker listener. */
      InteractionManager.prototype.addTickerListener = function () {
          if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) {
              return;
          }
          Ticker.system.add(this.tickerUpdate, this, exports.UPDATE_PRIORITY.INTERACTION);
          this.tickerAdded = true;
      };
      /** Removes the ticker listener. */
      InteractionManager.prototype.removeTickerListener = function () {
          if (!this.tickerAdded) {
              return;
          }
          Ticker.system.remove(this.tickerUpdate, this);
          this.tickerAdded = false;
      };
      /** Registers all the DOM events. */
      InteractionManager.prototype.addEvents = function () {
          if (this.eventsAdded || !this.interactionDOMElement) {
              return;
          }
          var style = this.interactionDOMElement.style;
          if (globalThis.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) {
              globalThis.document.addEventListener('pointermove', this.onPointerMove, this._eventListenerOptions);
              this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions);
              // 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, this._eventListenerOptions);
              this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, this._eventListenerOptions);
              globalThis.addEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions);
              globalThis.addEventListener('pointerup', this.onPointerUp, this._eventListenerOptions);
          }
          else {
              globalThis.document.addEventListener('mousemove', this.onPointerMove, this._eventListenerOptions);
              this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, this._eventListenerOptions);
              this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, this._eventListenerOptions);
              this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, this._eventListenerOptions);
              globalThis.addEventListener('mouseup', this.onPointerUp, this._eventListenerOptions);
          }
          // 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, this._eventListenerOptions);
              this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions);
              this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, this._eventListenerOptions);
              this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, this._eventListenerOptions);
          }
          this.eventsAdded = true;
      };
      /** Removes all the DOM events that were previously registered. */
      InteractionManager.prototype.removeEvents = function () {
          if (!this.eventsAdded || !this.interactionDOMElement) {
              return;
          }
          var style = this.interactionDOMElement.style;
          if (globalThis.navigator.msPointerEnabled) {
              style.msContentZooming = '';
              style.msTouchAction = '';
          }
          else if (this.supportsPointerEvents) {
              style.touchAction = '';
          }
          if (this.supportsPointerEvents) {
              globalThis.document.removeEventListener('pointermove', this.onPointerMove, this._eventListenerOptions);
              this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions);
              this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions);
              this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, this._eventListenerOptions);
              globalThis.removeEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions);
              globalThis.removeEventListener('pointerup', this.onPointerUp, this._eventListenerOptions);
          }
          else {
              globalThis.document.removeEventListener('mousemove', this.onPointerMove, this._eventListenerOptions);
              this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, this._eventListenerOptions);
              this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, this._eventListenerOptions);
              this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, this._eventListenerOptions);
              globalThis.removeEventListener('mouseup', this.onPointerUp, this._eventListenerOptions);
          }
          if (this.supportsTouchEvents) {
              this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, this._eventListenerOptions);
              this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions);
              this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, this._eventListenerOptions);
              this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, this._eventListenerOptions);
          }
          this.interactionDOMElement = null;
          this.eventsAdded = false;
      };
      /**
       * Updates the state of interactive objects if at least {@link interactionFrequency}
       * milliseconds have passed since the last invocation.
       *
       * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}.
       *
       * @param deltaTime - time delta since the last call
       */
      InteractionManager.prototype.tickerUpdate = function (deltaTime) {
          this._deltaTime += deltaTime;
          if (this._deltaTime < this.interactionFrequency) {
              return;
          }
          this._deltaTime = 0;
          this.update();
      };
      /** Updates the state of interactive objects. */
      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);
      };
      /**
       * Sets the current cursor mode, handling any callbacks or CSS style changes.
       *
       * @param mode - cursor mode, a key from the cursorStyles dictionary
       */
      InteractionManager.prototype.setCursorMode = function (mode) {
          mode = mode || 'default';
          var applyStyles = true;
          // offscreen canvas does not support setting styles, but cursor modes can be functions,
          // in order to handle pixi rendered cursors, so we can't bail
          if (globalThis.OffscreenCanvas && this.interactionDOMElement instanceof OffscreenCanvas) {
              applyStyles = false;
          }
          // 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
                      if (applyStyles) {
                          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
                      if (applyStyles) {
                          Object.assign(this.interactionDOMElement.style, style);
                      }
                      break;
              }
          }
          else if (applyStyles && 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;
          }
      };
      /**
       * Dispatches an event on the display object that was interacted with.
       *
       * @param displayObject - the display object in question
       * @param eventString - the name of the event (e.g, mousedown)
       * @param eventData - the event data object
       */
      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);
              }
          }
      };
      /**
       * Puts a event on a queue to be dispatched later. This is used to guarantee correct
       * ordering of over/out events.
       *
       * @param displayObject - the display object in question
       * @param eventString - the name of the event (e.g, mousedown)
       * @param eventData - the event data object
       */
      InteractionManager.prototype.delayDispatchEvent = function (displayObject, eventString, eventData) {
          this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData });
      };
      /**
       * 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 point - the point that the result will be stored in
       * @param x - the x coord of the position to map
       * @param y - the y coord of the position to map
       */
      InteractionManager.prototype.mapPositionToPoint = function (point, x, y) {
          var rect;
          // IE 11 fix
          if (!this.interactionDOMElement.parentElement) {
              rect = {
                  x: 0,
                  y: 0,
                  width: this.interactionDOMElement.width,
                  height: this.interactionDOMElement.height,
                  left: 0,
                  top: 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;
      };
      /**
       * 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 interactionEvent - event containing the point that
       *  is tested for collision
       * @param displayObject - the displayObject
       *  that will be hit test (recursively crawls its children)
       * @param func - the function that will be called on each interactive object. The
       *  interactionEvent, displayObject and hit will be passed to the function
       * @param hitTest - indicates whether we want to calculate hits
       *  or just iterate through all interactive objects
       */
      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;
      };
      /**
       * Is called when the pointer button is pressed down on the renderer element
       *
       * @param originalEvent - The DOM event of a pointer button being pressed down
       */
      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);
              }
          }
      };
      /**
       * Processes the result of the pointer down check and dispatches the event if need be
       *
       * @param interactionEvent - The interaction event wrapping the DOM event
       * @param displayObject - The display object that was tested
       * @param hit - the result of the hit test on the display object
       */
      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);
              }
          }
      };
      /**
       * Is called when the pointer button is released on the renderer element
       *
       * @param originalEvent - The DOM event of a pointer button being released
       * @param cancelled - true if the pointer is cancelled
       * @param 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);
              }
          }
      };
      /**
       * Is called when the pointer button is cancelled
       *
       * @param event - The DOM event of a pointer button being released
       */
      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);
      };
      /**
       * Processes the result of the pointer cancel check and dispatches the event if need be
       *
       * @param interactionEvent - The interaction event wrapping the DOM event
       * @param displayObject - The display object that was tested
       */
      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);
              }
          }
      };
      /**
       * Is called when the pointer button is released on the renderer element
       *
       * @param event - The DOM event of a pointer button being released
       */
      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);
      };
      /**
       * Processes the result of the pointer up check and dispatches the event if need be
       *
       * @param interactionEvent - The interaction event wrapping the DOM event
       * @param displayObject - The display object that was tested
       * @param 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 originalEvent - The DOM event of a pointer moving
       */
      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)
          }
      };
      /**
       * Processes the result of the pointer move check and dispatches the event if need be
       *
       * @param interactionEvent - The interaction event wrapping the DOM event
       * @param displayObject - The display object that was tested
       * @param 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
       *
       * @private
       * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out
       */
      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);
          }
      };
      /**
       * Processes the result of the pointer over/out check and dispatches the event if need be.
       *
       * @param interactionEvent - The interaction event wrapping the DOM event
       * @param displayObject - The display object that was tested
       * @param hit - the result of the hit test on the display object
       */
      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];
              }
          }
      };
      /**
       * Is called when the pointer is moved into the renderer element.
       *
       * @param originalEvent - The DOM event of a pointer button being moved into the renderer view.
       */
      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);
          }
      };
      /**
       * Get InteractionData for a given pointerId. Store that data as well.
       *
       * @param event - Normalized pointer event, output from normalizeToPointerData.
       * @return - 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;
      };
      /**
       * Return unused InteractionData to the pool, for a given pointerId
       *
       * @param 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
       *
       * @param interactionEvent - The event to be configured
       * @param pointerEvent - The DOM event that will be paired with the InteractionEvent
       * @param interactionData - The InteractionData that will be paired
       *        with the InteractionEvent
       * @return - the interaction event that was passed in
       */
      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;
      };
      /**
       * Ensures that the original event object contains all data that a regular pointer event would have
       *
       * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event
       * @return - 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 (!globalThis.MouseEvent
              || (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof globalThis.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;
  }(eventemitter3));

  /*!
   * @pixi/runner - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/runner is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */
  /**
   * 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.loaded.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(gameObject);
   *
   * myGame.update.emit(time);
   * ```
   *
   * @memberof PIXI
   */
  var Runner = /** @class */ (function () {
      /**
       * @param 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
       */
      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.
       */
      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 listener that you would like to remove.
       */
      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 */
      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
           *
           * @readonly
           */
          get: function () {
              return this.items.length === 0;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Runner.prototype, "name", {
          /**
           * The name of the runner.
           *
           * @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 },
  });

  /*!
   * @pixi/core - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/core is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * 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.PREFER_ENV = isMobile$1.any ? exports.ENV.WEBGL : exports.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.STRICT_TEXTURE_CACHE = false;

  /**
   * Collection of installed resource types, class must extend {@link PIXI.Resource}.
   * @example
   * class CustomResource extends PIXI.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.INSTALLED.push(CustomResource);
   *
   * @memberof PIXI
   * @type {Array<PIXI.IResourcePlugin>}
   * @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.ImageResource}
   *  - {@link PIXI.CanvasResource}
   *  - {@link PIXI.VideoResource}
   *  - {@link PIXI.SVGResource}
   *  - {@link PIXI.BufferResource}
   * @static
   * @memberof PIXI
   * @function 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.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');
  }

  /*! *****************************************************************************
  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$2 = function(d, b) {
      extendStatics$2 = 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$2(d, b);
  };

  function __extends$2(d, b) {
      extendStatics$2(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  var __assign = function() {
      __assign = Object.assign || function __assign(t) {
          var arguments$1 = arguments;

          for (var s, i = 1, n = arguments.length; i < n; i++) {
              s = arguments$1[i];
              for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } }
          }
          return t;
      };
      return __assign.apply(this, arguments);
  };

  function __rest(s, e) {
      var t = {};
      for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
          { t[p] = s[p]; } }
      if (s != null && typeof Object.getOwnPropertySymbols === "function")
          { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0)
              { t[p[i]] = s[p[i]]; } } }
      return t;
  }

  /**
   * Base resource class for textures that manages validation and uploading, depending on its type.
   *
   * Uploading of a base texture to the GPU is required.
   *
   * @memberof PIXI
   */
  var Resource = /** @class */ (function () {
      /**
       * @param width - Width of the resource
       * @param height - Height of the resource
       */
      function Resource(width, height) {
          if (width === void 0) { width = 0; }
          if (height === void 0) { height = 0; }
          this._width = width;
          this._height = height;
          this.destroyed = false;
          this.internal = false;
          this.onResize = new Runner('setRealSize');
          this.onUpdate = new Runner('update');
          this.onError = new Runner('onError');
      }
      /**
       * Bind to a parent BaseTexture
       *
       * @param 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);
          }
      };
      /**
       * Unbind to a parent BaseTexture
       *
       * @param 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 width - X dimension
       * @param 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);
          }
      };
      Object.defineProperty(Resource.prototype, "valid", {
          /**
           * Has been validated
           *
           * @readonly
           */
          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 Handle the validate event
       */
      Resource.prototype.load = function () {
          return Promise.resolve(this);
      };
      Object.defineProperty(Resource.prototype, "width", {
          /**
           * The width of the resource.
           *
           * @readonly
           */
          get: function () {
              return this._width;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Resource.prototype, "height", {
          /**
           * The height of the resource.
           *
           * @readonly
           */
          get: function () {
              return this._height;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Set the style, optional to override
       *
       * @param renderer - yeah, renderer!
       * @param baseTexture - the texture
       * @param glTexture - texture instance for this webgl context
       * @returns - `true` is success
       */
      Resource.prototype.style = function (_renderer, _baseTexture, _glTexture) {
          return false;
      };
      /** Clean up anything, this happens when destroying is ready. */
      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.
       *
       * @param {*} source - The source object
       * @param {string} extension - The extension of source, if set
       */
      Resource.test = function (_source, _extension) {
          return false;
      };
      return Resource;
  }());

  /**
   * @interface SharedArrayBuffer
   */
  /**
   * Buffer resource with data of typed array.
   *
   * @memberof PIXI
   */
  var BufferResource = /** @class */ (function (_super) {
      __extends$2(BufferResource, _super);
      /**
       * @param source - Source buffer
       * @param 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;
          _this.data = source;
          return _this;
      }
      /**
       * Upload the texture to the GPU.
       *
       * @param renderer - Upload to the renderer
       * @param baseTexture - Reference to parent texture
       * @param glTexture - glTexture
       * @returns - true is success
       */
      BufferResource.prototype.upload = function (renderer, baseTexture, glTexture) {
          var gl = renderer.gl;
          gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK);
          var width = baseTexture.realWidth;
          var height = baseTexture.realHeight;
          if (glTexture.width === width && glTexture.height === height) {
              gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data);
          }
          else {
              glTexture.width = width;
              glTexture.height = height;
              gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data);
          }
          return true;
      };
      /** Destroy and don't use after this. */
      BufferResource.prototype.dispose = function () {
          this.data = null;
      };
      /**
       * Used to auto-detect the type of resource.
       *
       * @param {*} source - The source object
       * @return {boolean} `true` if <canvas>
       */
      BufferResource.test = function (source) {
          return source instanceof Float32Array
              || source instanceof Uint8Array
              || source instanceof Uint32Array;
      };
      return BufferResource;
  }(Resource));

  var defaultBufferOptions = {
      scaleMode: exports.SCALE_MODES.NEAREST,
      format: exports.FORMATS.RGBA,
      alphaMode: exports.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
   *
   * @memberof PIXI
   * @typeParam R - The BaseTexture's Resource type.
   * @typeParam RO - The options for constructing resource.
   */
  var BaseTexture = /** @class */ (function (_super) {
      __extends$2(BaseTexture, _super);
      /**
       * @param {PIXI.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 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=PIXI.settings.RESOLUTION] - Resolution of the base texture
       * @param {object} [options.resourceOptions] - Optional resource options,
       *        see {@link PIXI.autoDetectResource autoDetectResource}
       */
      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.resolution = resolution || settings.RESOLUTION;
          _this.width = Math.round((width || 0) * _this.resolution) / _this.resolution;
          _this.height = Math.round((height || 0) * _this.resolution) / _this.resolution;
          _this._mipmap = mipmap !== undefined ? mipmap : settings.MIPMAP_TEXTURES;
          _this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings.ANISOTROPIC_LEVEL;
          _this._wrapMode = wrapMode || settings.WRAP_MODE;
          _this._scaleMode = scaleMode !== undefined ? scaleMode : settings.SCALE_MODE;
          _this.format = format || exports.FORMATS.RGBA;
          _this.type = type || exports.TYPES.UNSIGNED_BYTE;
          _this.target = target || exports.TARGETS.TEXTURE_2D;
          _this.alphaMode = alphaMode !== undefined ? alphaMode : exports.ALPHA_MODES.UNPACK;
          _this.uid = uid();
          _this.touched = 0;
          _this.isPowerOfTwo = false;
          _this._refreshPOT();
          _this._glTextures = {};
          _this.dirtyId = 0;
          _this.dirtyStyleId = 0;
          _this.cacheId = null;
          _this.valid = width > 0 && height > 0;
          _this.textureCacheIds = [];
          _this.destroyed = false;
          _this.resource = null;
          _this._batchEnabled = 0;
          _this._batchLocation = 0;
          _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
           */
          get: function () {
              return Math.round(this.width * this.resolution);
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BaseTexture.prototype, "realHeight", {
          /**
           * Pixel height of the source of this texture
           *
           * @readonly
           */
          get: function () {
              return Math.round(this.height * this.resolution);
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BaseTexture.prototype, "mipmap", {
          /**
           * Mipmap mode of the texture, affects downscaled images
           *
           * @default PIXI.settings.MIPMAP_TEXTURES
           */
          get: function () {
              return this._mipmap;
          },
          set: function (value) {
              if (this._mipmap !== value) {
                  this._mipmap = value;
                  this.dirtyStyleId++;
              }
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BaseTexture.prototype, "scaleMode", {
          /**
           * The scale mode to apply when scaling this texture
           *
           * @default PIXI.settings.SCALE_MODE
           */
          get: function () {
              return this._scaleMode;
          },
          set: function (value) {
              if (this._scaleMode !== value) {
                  this._scaleMode = value;
                  this.dirtyStyleId++;
              }
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BaseTexture.prototype, "wrapMode", {
          /**
           * How the texture wraps
           *
           * @default PIXI.settings.WRAP_MODE
           */
          get: function () {
              return this._wrapMode;
          },
          set: function (value) {
              if (this._wrapMode !== value) {
                  this._wrapMode = value;
                  this.dirtyStyleId++;
              }
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Changes style options of BaseTexture
       *
       * @param scaleMode - Pixi scalemode
       * @param mipmap - enable mipmaps
       * @returns - this
       */
      BaseTexture.prototype.setStyle = function (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++;
          }
          return this;
      };
      /**
       * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero.
       *
       * @param desiredWidth - Desired visual width
       * @param desiredHeight - Desired visual height
       * @param resolution - Optionally set resolution
       * @returns - this
       */
      BaseTexture.prototype.setSize = function (desiredWidth, desiredHeight, resolution) {
          resolution = resolution || this.resolution;
          return this.setRealSize(desiredWidth * resolution, desiredHeight * resolution, resolution);
      };
      /**
       * Sets real size of baseTexture, preserves current resolution.
       *
       * @param realWidth - Full rendered width
       * @param realHeight - Full rendered height
       * @param resolution - Optionally set resolution
       * @returns - this
       */
      BaseTexture.prototype.setRealSize = function (realWidth, realHeight, resolution) {
          this.resolution = resolution || this.resolution;
          this.width = Math.round(realWidth) / this.resolution;
          this.height = Math.round(realHeight) / this.resolution;
          this._refreshPOT();
          this.update();
          return this;
      };
      /**
       * Refresh check for isPowerOfTwo texture based on size
       *
       * @private
       */
      BaseTexture.prototype._refreshPOT = function () {
          this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight);
      };
      /**
       * Changes resolution
       *
       * @param resolution - res
       * @returns - this
       */
      BaseTexture.prototype.setResolution = function (resolution) {
          var oldResolution = this.resolution;
          if (oldResolution === resolution) {
              return this;
          }
          this.resolution = resolution;
          if (this.valid) {
              this.width = Math.round(this.width * oldResolution) / resolution;
              this.height = Math.round(this.height * oldResolution) / resolution;
              this.emit('update', this);
          }
          this._refreshPOT();
          return this;
      };
      /**
       * Sets the resource if it wasn't set. Throws error if resource already present
       *
       * @param resource - that is managing this BaseTexture
       * @returns - this
       */
      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;
      };
      /** Invalidates the object. Texture becomes valid if width and height are greater than zero. */
      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);
              }
          }
          else {
              this.dirtyId++;
              this.dirtyStyleId++;
              this.emit('update', this);
          }
      };
      /**
       * Handle errors with resources.
       *
       * @private
       * @param event - Error event emitted.
       */
      BaseTexture.prototype.onError = function (event) {
          this.emit('error', this, event);
      };
      /**
       * Destroys this base texture.
       * The method stops if resource doesn't want this texture to be destroyed.
       * Removes texture from all caches.
       */
      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;
          }
          if (this.cacheId) {
              delete BaseTextureCache[this.cacheId];
              delete TextureCache[this.cacheId];
              this.cacheId = null;
          }
          // finally let the WebGL renderer know..
          this.dispose();
          BaseTexture.removeFromCache(this);
          this.textureCacheIds = null;
          this.destroyed = true;
      };
      /**
       * 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
       */
      BaseTexture.prototype.dispose = function () {
          this.emit('dispose', this);
      };
      /** Utility function for BaseTexture|Texture cast. */
      BaseTexture.prototype.castToBaseTexture = function () {
          return this;
      };
      /**
       * 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 options - See {@link PIXI.BaseTexture}'s constructor for options.
       * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id
       * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}.
       * @returns {PIXI.BaseTexture} The new base texture.
       */
      BaseTexture.from = function (source, options, strict) {
          if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; }
          var isFrame = typeof source === 'string';
          var cacheId = null;
          if (isFrame) {
              cacheId = source;
          }
          else {
              if (!source._pixiId) {
                  var prefix = (options && options.pixiIdPrefix) || 'pixiid';
                  source._pixiId = prefix + "_" + uid();
              }
              cacheId = source._pixiId;
          }
          var baseTexture = 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;
      };
      /**
       * Create a new BaseTexture with a BufferResource from a Float32Array.
       * RGBA values are floats from 0 to 1.
       *
       * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data
       *        is provided, a new Float32Array is created.
       * @param width - Width of the resource
       * @param height - Height of the resource
       * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
       * @return - The resulting new BaseTexture
       */
      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 ? exports.TYPES.FLOAT : exports.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.
       *
       *
       * @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 (BaseTextureCache[id]) {
                  // eslint-disable-next-line no-console
                  console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry");
              }
              BaseTextureCache[id] = baseTexture;
          }
      };
      /**
       * Remove a BaseTexture from the global BaseTextureCache.
       *
       * @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 = BaseTextureCache[baseTexture];
              if (baseTextureFromCache) {
                  var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture);
                  if (index > -1) {
                      baseTextureFromCache.textureCacheIds.splice(index, 1);
                  }
                  delete BaseTextureCache[baseTexture];
                  return baseTextureFromCache;
              }
          }
          else if (baseTexture && baseTexture.textureCacheIds) {
              for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) {
                  delete BaseTextureCache[baseTexture.textureCacheIds[i]];
              }
              baseTexture.textureCacheIds.length = 0;
              return baseTexture;
          }
          return null;
      };
      /** Global number of the texture batch, used by multi-texture renderers. */
      BaseTexture._globalBatch = 0;
      return BaseTexture;
  }(eventemitter3));

  /**
   * Resource that can manage several resource (items) inside.
   * All resources need to have the same pixel size.
   * Parent class for CubeResource and ArrayResource
   *
   * @memberof PIXI
   */
  var AbstractMultiResource = /** @class */ (function (_super) {
      __extends$2(AbstractMultiResource, _super);
      /**
       * @param length
       * @param options - Options to for Resource constructor
       * @param {number} [options.width] - Width of the resource
       * @param {number} [options.height] - Height of the resource
       */
      function AbstractMultiResource(length, options) {
          var _this = this;
          var _a = options || {}, width = _a.width, height = _a.height;
          _this = _super.call(this, width, height) || this;
          _this.items = [];
          _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);
          }
          _this.length = length;
          _this._load = null;
          _this.baseTexture = null;
          return _this;
      }
      /**
       * Used from ArrayResource and CubeResource constructors.
       *
       * @param resources - Can be resources, image elements, canvas, etc. ,
       *  length should be same as constructor length
       * @param options - Detect options for resources
       */
      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);
              }
          }
      };
      /** Destroy this BaseImageResource. */
      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;
      };
      /**
       * Set a resource by ID
       *
       * @param resource
       * @param index - Zero-based index of resource to set
       * @return - Instance for chaining
       */
      AbstractMultiResource.prototype.addResourceAt = function (resource, index) {
          if (!this.items[index]) {
              throw new Error("Index " + index + " is out of bounds");
          }
          // Inherit the first resource dimensions
          if (resource.valid && !this.valid) {
              this.resize(resource.width, resource.height);
          }
          this.items[index].setResource(resource);
          return this;
      };
      /** Set the parent base texture. */
      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);
          }
      };
      /** Unset the parent base texture. */
      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);
          }
      };
      /**
       * Load all the resources simultaneously
       *
       * @return - When load is resolved
       */
      AbstractMultiResource.prototype.load = function () {
          var _this = this;
          if (this._load) {
              return this._load;
          }
          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));

  /**
   * A resource that contains a number of sources.
   *
   * @memberof PIXI
   */
  var ArrayResource = /** @class */ (function (_super) {
      __extends$2(ArrayResource, _super);
      /**
       * @param source - Number of items in array or the collection
       *        of image URLs to use. Can also be resources, image elements, canvas, etc.
       * @param options - Options to apply to {@link PIXI.autoDetectResource}
       * @param {number} [options.width] - Width of the resource
       * @param {number} [options.height] - Height of the resource
       */
      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;
          }
          else {
              length = source;
          }
          _this = _super.call(this, length, { width: width, height: height }) || this;
          if (urls) {
              _this.initFromArray(urls, options);
          }
          return _this;
      }
      /**
       * Set a baseTexture by ID,
       * ArrayResource just takes resource from it, nothing more
       *
       * @param baseTexture
       * @param index - Zero-based index of resource to set
       * @return - Instance for chaining
       */
      ArrayResource.prototype.addBaseTextureAt = function (baseTexture, index) {
          if (baseTexture.resource) {
              this.addResourceAt(baseTexture.resource, index);
          }
          else {
              throw new Error('ArrayResource does not support RenderTexture');
          }
          return this;
      };
      /** Add binding */
      ArrayResource.prototype.bind = function (baseTexture) {
          _super.prototype.bind.call(this, baseTexture);
          baseTexture.target = exports.TARGETS.TEXTURE_2D_ARRAY;
      };
      /**
       * Upload the resources to the GPU.
       *
       * @param renderer
       * @param texture
       * @param glTexture
       * @returns - whether texture was uploaded
       */
      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, glTexture.internalFormat, this._width, this._height, length, 0, texture.format, glTexture.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, glTexture.type, item.resource.source);
                  }
              }
          }
          return true;
      };
      return ArrayResource;
  }(AbstractMultiResource));

  /**
   * Base for all the image/canvas resources.
   *
   * @memberof PIXI
   */
  var BaseImageResource = /** @class */ (function (_super) {
      __extends$2(BaseImageResource, _super);
      /**
       * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source
       */
      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;
          _this.source = source;
          _this.noSubImage = false;
          return _this;
      }
      /**
       * Set cross origin based detecting the url and the crossorigin
       *
       * @param element - Element to apply crossOrigin
       * @param url - URL to check
       * @param crossorigin - Cross origin value to use
       */
      BaseImageResource.crossOrigin = function (element, url, crossorigin) {
          if (crossorigin === undefined && url.indexOf('data:') !== 0) {
              element.crossOrigin = determineCrossOrigin(url);
          }
          else if (crossorigin !== false) {
              element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous';
          }
      };
      /**
       * Upload the texture to the GPU.
       *
       * @param renderer - Upload to the renderer
       * @param baseTexture - Reference to parent texture
       * @param glTexture
       * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] - (optional)
       * @returns - 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;
          if (source instanceof HTMLImageElement) {
              if (!source.complete || source.naturalWidth === 0) {
                  return false;
              }
          }
          else if (source instanceof HTMLVideoElement) {
              if (source.readyState <= 1) {
                  return false;
              }
          }
          gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.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, glTexture.type, source);
          }
          else {
              glTexture.width = width;
              glTexture.height = height;
              gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.format, glTexture.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 {@link BaseImageResource} */
      BaseImageResource.prototype.dispose = function () {
          this.source = null;
      };
      return BaseImageResource;
  }(Resource));

  /**
   * @interface OffscreenCanvas
   */
  /**
   * Resource type for HTMLCanvasElement.
   *
   * @memberof PIXI
   */
  var CanvasResource = /** @class */ (function (_super) {
      __extends$2(CanvasResource, _super);
      /**
       * @param source - Canvas element to use
       */
      // eslint-disable-next-line @typescript-eslint/no-useless-constructor
      function CanvasResource(source) {
          return _super.call(this, source) || this;
      }
      /**
       * Used to auto-detect the type of resource.
       *
       * @param {*} source - The source object
       * @return {boolean} `true` if source is HTMLCanvasElement or OffscreenCanvas
       */
      CanvasResource.test = function (source) {
          var OffscreenCanvas = globalThis.OffscreenCanvas;
          // Check for browsers that don't yet support OffscreenCanvas
          if (OffscreenCanvas && source instanceof OffscreenCanvas) {
              return true;
          }
          return globalThis.HTMLCanvasElement && source instanceof HTMLCanvasElement;
      };
      return CanvasResource;
  }(BaseImageResource));

  /**
   * Resource for a CubeTexture which contains six resources.
   *
   * @memberof PIXI
   */
  var CubeResource = /** @class */ (function (_super) {
      __extends$2(CubeResource, _super);
      /**
       * @param {Array<string|PIXI.Resource>} [source] - Collection of URLs or resources
       *        to use as the sides of the cube.
       * @param 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
       */
      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 = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i;
          }
          _this.linkBaseTexture = linkBaseTexture !== false;
          if (source) {
              _this.initFromArray(source, options);
          }
          if (autoLoad !== false) {
              _this.load();
          }
          return _this;
      }
      /**
       * Add binding.
       *
       * @param baseTexture - parent base texture
       */
      CubeResource.prototype.bind = function (baseTexture) {
          _super.prototype.bind.call(this, baseTexture);
          baseTexture.target = exports.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 = exports.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;
      };
      /**
       * Upload the resource
       *
       * @returns {boolean} true is success
       */
      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;
      };
      /**
       * Used to auto-detect the type of resource.
       *
       * @param {*} source - The source object
       * @return {boolean} `true` if source is an array of 6 elements
       */
      CubeResource.test = function (source) {
          return Array.isArray(source) && source.length === CubeResource.SIDES;
      };
      /** Number of texture sides to store for CubeResources. */
      CubeResource.SIDES = 6;
      return CubeResource;
  }(AbstractMultiResource));

  /**
   * Resource type for HTMLImageElement.
   *
   * @memberof PIXI
   */
  var ImageResource = /** @class */ (function (_super) {
      __extends$2(ImageResource, _super);
      /**
       * @param source - image source or URL
       * @param 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
       */
      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;
          }
          _this.url = source.src;
          _this._process = null;
          _this.preserveBitmap = false;
          _this.createBitmap = (options.createBitmap !== undefined
              ? options.createBitmap : settings.CREATE_IMAGE_BITMAP) && !!globalThis.createImageBitmap;
          _this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null;
          _this.bitmap = null;
          _this._load = null;
          if (options.autoLoad !== false) {
              _this.load();
          }
          return _this;
      }
      /**
       * Returns a promise when image will be loaded and processed.
       *
       * @param createBitmap - whether process image into bitmap
       */
      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;
      };
      /**
       * Called when we need to convert image into BitmapImage.
       * Can be called multiple times, real promise is cached inside.
       *
       * @return - Cached promise to fill that bitmap
       */
      ImageResource.prototype.process = function () {
          var _this = this;
          var source = this.source;
          if (this._process !== null) {
              return this._process;
          }
          if (this.bitmap !== null || !globalThis.createImageBitmap) {
              return Promise.resolve(this);
          }
          var createImageBitmap = globalThis.createImageBitmap;
          var cors = !source.crossOrigin || source.crossOrigin === 'anonymous';
          this._process = fetch(source.src, {
              mode: cors ? 'cors' : 'no-cors'
          })
              .then(function (r) { return r.blob(); })
              .then(function (blob) { return createImageBitmap(blob, 0, 0, source.width, source.height, {
              premultiplyAlpha: _this.alphaMode === exports.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;
      };
      /**
       * Upload the image resource to GPU.
       *
       * @param renderer - Renderer to upload to
       * @param baseTexture - BaseTexture for this resource
       * @param glTexture - GLTexture to use
       * @returns {boolean} true is success
       */
      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 resource. */
      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.
       *
       * @param {*} 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));

  /**
   * Resource type for SVG elements and graphics.
   *
   * @memberof PIXI
   */
  var SVGResource = /** @class */ (function (_super) {
      __extends$2(SVGResource, _super);
      /**
       * @param sourceBase64 - 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.
       */
      function SVGResource(sourceBase64, options) {
          var _this = this;
          options = options || {};
          _this = _super.call(this, document.createElement('canvas')) || this;
          _this._width = 0;
          _this._height = 0;
          _this.svg = sourceBase64;
          _this.scale = options.scale || 1;
          _this._overrideWidth = options.width;
          _this._overrideHeight = options.height;
          _this._resolve = null;
          _this._crossorigin = options.crossorigin;
          _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 (SVGResource.SVG_XML.test(_this.svg.trim())) {
                  if (!btoa) {
                      throw new Error('Your browser doesn\'t support base64 conversions.');
                  }
                  _this.svg = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(_this.svg)));
              }
              _this._loadSvg();
          });
          return this._load;
      };
      /** Loads an SVG image from `imageUrl` or `data URL`. */
      SVGResource.prototype._loadSvg = function () {
          var _this = this;
          var tempImage = new Image();
          BaseImageResource.crossOrigin(tempImage, this.svg, this._crossorigin);
          tempImage.src = this.svg;
          tempImage.onerror = function (event) {
              if (!_this._resolve) {
                  return;
              }
              tempImage.onerror = null;
              _this.onError.emit(event);
          };
          tempImage.onload = function () {
              if (!_this._resolve) {
                  return;
              }
              var svgWidth = tempImage.width;
              var svgHeight = tempImage.height;
              if (!svgWidth || !svgHeight) {
                  throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.');
              }
              // Set render size
              var width = svgWidth * _this.scale;
              var height = svgHeight * _this.scale;
              if (_this._overrideWidth || _this._overrideHeight) {
                  width = _this._overrideWidth || _this._overrideHeight / svgHeight * svgWidth;
                  height = _this._overrideHeight || _this._overrideWidth / svgWidth * svgHeight;
              }
              width = Math.round(width);
              height = Math.round(height);
              // Create a canvas element
              var canvas = _this.source;
              canvas.width = width;
              canvas.height = height;
              canvas._pixiId = "canvas_" + uid();
              // Draw the Svg to the canvas
              canvas
                  .getContext('2d')
                  .drawImage(tempImage, 0, 0, svgWidth, svgHeight, 0, 0, width, height);
              _this._resolve();
              _this._resolve = null;
          };
      };
      /**
       * Get size from an svg string using a regular expression.
       *
       * @param svgString - a serialized svg element
       * @return - image extension
       */
      SVGResource.getSize = function (svgString) {
          var sizeMatch = SVGResource.SVG_SIZE.exec(svgString);
          var size = {};
          if (sizeMatch) {
              size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3]));
              size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7]));
          }
          return size;
      };
      /** Destroys this texture. */
      SVGResource.prototype.dispose = function () {
          _super.prototype.dispose.call(this);
          this._resolve = null;
          this._crossorigin = null;
      };
      /**
       * Used to auto-detect the type of resource.
       *
       * @param {*} source - The source object
       * @param {string} extension - The extension of source, if set
       * @return {boolean} - If the source is a SVG source or data file
       */
      SVGResource.test = function (source, extension) {
          // url file extension is SVG
          return extension === 'svg'
              // source is SVG data-uri
              || (typeof source === 'string' && (/^data:image\/svg\+xml(;(charset=utf8|utf8))?;base64/).test(source))
              // source is SVG inline
              || (typeof source === 'string' && SVGResource.SVG_XML.test(source));
      };
      /**
       * Regular expression for SVG XML document.
       *
       * @example &lt;?xml version="1.0" encoding="utf-8" ?&gt;&lt;!-- image/svg --&gt;&lt;svg
       * @readonly
       */
      SVGResource.SVG_XML = /^(<\?xml[^?]+\?>)?\s*(<!--[^(-->)]*-->)?\s*\<svg/m;
      /**
       * Regular expression for SVG size.
       *
       * @example &lt;svg width="100" height="100"&gt;&lt;/svg&gt;
       * @readonly
       */
      SVGResource.SVG_SIZE = /<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len
      return SVGResource;
  }(BaseImageResource));

  /**
   * Resource type for {@code HTMLVideoElement}.
   *
   * @memberof PIXI
   */
  var VideoResource = /** @class */ (function (_super) {
      __extends$2(VideoResource, _super);
      /**
       * @param {HTMLVideoElement|object|string|Array<string|object>} 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
       */
      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.slice(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;
          _this._autoUpdate = true;
          _this._isConnectedToTicker = false;
          _this._updateFPS = options.updateFPS || 0;
          _this._msToNextUpdate = 0;
          _this.autoPlay = options.autoPlay !== false;
          _this._load = null;
          _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 deltaTime - time delta since last tick
       */
      VideoResource.prototype.update = function (_deltaTime) {
          if (!this.destroyed) {
              // account for if video has had its playbackRate changed
              var elapsedMS = 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.
       *
       * @return {Promise<void>} 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;
      };
      /** Handle video error events. */
      VideoResource.prototype._onError = function (event) {
          this.source.removeEventListener('error', this._onError, true);
          this.onError.emit(event);
      };
      /**
       * Returns true if the underlying source is playing.
       *
       * @return - True if playing.
       */
      VideoResource.prototype._isSourcePlaying = function () {
          var source = this.source;
          return (source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2);
      };
      /**
       * Returns true if the underlying source is ready for playing.
       *
       * @return - True if ready.
       */
      VideoResource.prototype._isSourceReady = function () {
          var source = this.source;
          return source.readyState === 3 || source.readyState === 4;
      };
      /** Runs the update loop when the video is ready to play. */
      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.shared.add(this.update, this);
              this._isConnectedToTicker = true;
          }
      };
      /** Fired when a pause event is triggered, stops the update loop. */
      VideoResource.prototype._onPlayStop = function () {
          if (this._isConnectedToTicker) {
              Ticker.shared.remove(this.update, this);
              this._isConnectedToTicker = false;
          }
      };
      /** Fired when the video is loaded and ready to play. */
      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();
          }
      };
      /** Destroys this texture. */
      VideoResource.prototype.dispose = function () {
          if (this._isConnectedToTicker) {
              Ticker.shared.remove(this.update, this);
              this._isConnectedToTicker = false;
          }
          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. */
          get: function () {
              return this._autoUpdate;
          },
          set: function (value) {
              if (value !== this._autoUpdate) {
                  this._autoUpdate = value;
                  if (!this._autoUpdate && this._isConnectedToTicker) {
                      Ticker.shared.remove(this.update, this);
                      this._isConnectedToTicker = false;
                  }
                  else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) {
                      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.
           */
          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.
       *
       * @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 (globalThis.HTMLVideoElement && source instanceof HTMLVideoElement)
              || VideoResource.TYPES.indexOf(extension) > -1;
      };
      /**
       * List of common video file extensions supported by VideoResource.
       *
       * @readonly
       */
      VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov'];
      /**
       * Map of video MIME types that can't be directly derived from file extensions.
       *
       * @readonly
       */
      VideoResource.MIME_TYPES = {
          ogv: 'video/ogg',
          mov: 'video/quicktime',
          m4v: 'video/mp4',
      };
      return VideoResource;
  }(BaseImageResource));

  /**
   * Resource type for ImageBitmap.
   *
   * @memberof PIXI
   */
  var ImageBitmapResource = /** @class */ (function (_super) {
      __extends$2(ImageBitmapResource, _super);
      /**
       * @param source - Image element to use
       */
      // eslint-disable-next-line @typescript-eslint/no-useless-constructor
      function ImageBitmapResource(source) {
          return _super.call(this, source) || this;
      }
      /**
       * Used to auto-detect the type of resource.
       *
       * @param {*} source - The source object
       * @return {boolean} `true` if source is an ImageBitmap
       */
      ImageBitmapResource.test = function (source) {
          return !!globalThis.createImageBitmap && source instanceof ImageBitmap;
      };
      return ImageBitmapResource;
  }(BaseImageResource));

  INSTALLED.push(ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource);

  var _resources = {
      __proto__: null,
      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
  };

  /**
   * Resource type for DepthTexture.
   *
   * @memberof PIXI
   */
  var DepthResource = /** @class */ (function (_super) {
      __extends$2(DepthResource, _super);
      function DepthResource() {
          return _super !== null && _super.apply(this, arguments) || this;
      }
      /**
       * Upload the texture to the GPU.
       *
       * @param renderer - Upload to the renderer
       * @param baseTexture - Reference to parent texture
       * @param glTexture - glTexture
       * @return - true is success
       */
      DepthResource.prototype.upload = function (renderer, baseTexture, glTexture) {
          var gl = renderer.gl;
          gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK);
          var width = baseTexture.realWidth;
          var height = baseTexture.realHeight;
          if (glTexture.width === width && glTexture.height === height) {
              gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data);
          }
          else {
              glTexture.width = width;
              glTexture.height = height;
              gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data);
          }
          return true;
      };
      return DepthResource;
  }(BufferResource));

  /**
   * A framebuffer can be used to render contents off of the screen. {@link PIXI.BaseRenderTexture} uses
   * one internally to render into itself. You can attach a depth or stencil buffer to a framebuffer.
   *
   * On WebGL 2 machines, shaders can output to multiple textures simultaneously with GLSL 300 ES.
   *
   * @memberof PIXI
   */
  var Framebuffer = /** @class */ (function () {
      /**
       * @param width - Width of the frame buffer
       * @param height - Height of the frame buffer
       */
      function Framebuffer(width, height) {
          this.width = Math.round(width || 100);
          this.height = Math.round(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('disposeFramebuffer');
          this.multisample = exports.MSAA_QUALITY.NONE;
      }
      Object.defineProperty(Framebuffer.prototype, "colorTexture", {
          /**
           * Reference to the colorTexture.
           *
           * @readonly
           */
          get: function () {
              return this.colorTextures[0];
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Add texture to the colorTexture array.
       *
       * @param index - Index of the array to add the texture to
       * @param 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: exports.SCALE_MODES.NEAREST,
              resolution: 1,
              mipmap: exports.MIPMAP_MODES.OFF,
              width: this.width,
              height: this.height,
          });
          this.dirtyId++;
          this.dirtyFormat++;
          return this;
      };
      /**
       * Add a depth texture to the frame buffer.
       *
       * @param 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: exports.SCALE_MODES.NEAREST,
              resolution: 1,
              width: this.width,
              height: this.height,
              mipmap: exports.MIPMAP_MODES.OFF,
              format: exports.FORMATS.DEPTH_COMPONENT,
              type: exports.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 width - Width of the frame buffer to resize to
       * @param height - Height of the frame buffer to resize to
       */
      Framebuffer.prototype.resize = function (width, height) {
          width = Math.round(width);
          height = Math.round(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 account the fact the texture may have a different resolution..
              texture.setSize(width / resolution, height / resolution);
          }
          if (this.depthTexture) {
              var resolution = this.depthTexture.resolution;
              this.depthTexture.setSize(width / resolution, height / resolution);
          }
      };
      /** 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;
          }
      };
      return Framebuffer;
  }());

  /**
   * 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
   * ```
   *
   * @memberof PIXI
   */
  var BaseRenderTexture = /** @class */ (function (_super) {
      __extends$2(BaseRenderTexture, _super);
      /**
       * @param 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=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES}
       *   for possible values.
       * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio
       *   of the texture being generated.
       * @param {PIXI.MSAA_QUALITY} [options.multisample=PIXI.MSAA_QUALITY.NONE] - The number of samples of the frame buffer.
       */
      function BaseRenderTexture(options) {
          if (options === void 0) { options = {}; }
          var _this = this;
          if (typeof options === 'number') {
              /* eslint-disable prefer-rest-params */
              // Backward compatibility of signature
              var width = arguments[0];
              var height = arguments[1];
              var scaleMode = arguments[2];
              var resolution = arguments[3];
              options = { width: width, height: height, scaleMode: scaleMode, resolution: resolution };
              /* eslint-enable prefer-rest-params */
          }
          options.width = options.width || 100;
          options.height = options.height || 100;
          options.multisample = options.multisample !== undefined ? options.multisample : exports.MSAA_QUALITY.NONE;
          _this = _super.call(this, null, options) || this;
          // Set defaults
          _this.mipmap = exports.MIPMAP_MODES.OFF;
          _this.valid = true;
          _this.clearColor = [0, 0, 0, 0];
          _this.framebuffer = new Framebuffer(_this.realWidth, _this.realHeight)
              .addColorTexture(0, _this);
          _this.framebuffer.multisample = options.multisample;
          // TODO - could this be added the systems?
          _this.maskStack = [];
          _this.filterStack = [{}];
          return _this;
      }
      /**
       * Resizes the BaseRenderTexture.
       *
       * @param desiredWidth - The desired width to resize to.
       * @param desiredHeight - The desired height to resize to.
       */
      BaseRenderTexture.prototype.resize = function (desiredWidth, desiredHeight) {
          this.framebuffer.resize(desiredWidth * this.resolution, desiredHeight * this.resolution);
          this.setRealSize(this.framebuffer.width, this.framebuffer.height);
      };
      /**
       * 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
       */
      BaseRenderTexture.prototype.dispose = function () {
          this.framebuffer.dispose();
          _super.prototype.dispose.call(this);
      };
      /** Destroys this texture. */
      BaseRenderTexture.prototype.destroy = function () {
          _super.prototype.destroy.call(this);
          this.framebuffer.destroyDepthTexture();
          this.framebuffer = null;
      };
      return BaseRenderTexture;
  }(BaseTexture));

  /**
   * 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)`   |
   *
   * @protected
   * @memberof PIXI
   */
  var TextureUvs = /** @class */ (function () {
      function TextureUvs() {
          this.x0 = 0;
          this.y0 = 0;
          this.x1 = 1;
          this.y1 = 0;
          this.x2 = 1;
          this.y2 = 1;
          this.x3 = 0;
          this.y3 = 1;
          this.uvsFloat32 = new Float32Array(8);
      }
      /**
       * Sets the texture Uvs based on the given frame information.
       *
       * @protected
       * @param frame - The frame of the texture
       * @param baseFrame - The base frame of the texture
       * @param 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 = groupD8.add(rotate, groupD8.NW); // NW is top-left corner
              this.x0 = cX + (w2 * groupD8.uX(rotate));
              this.y0 = cY + (h2 * groupD8.uY(rotate));
              rotate = groupD8.add(rotate, 2); // rotate 90 degrees clockwise
              this.x1 = cX + (w2 * groupD8.uX(rotate));
              this.y1 = cY + (h2 * groupD8.uY(rotate));
              rotate = groupD8.add(rotate, 2);
              this.x2 = cX + (w2 * groupD8.uX(rotate));
              this.y2 = cY + (h2 * groupD8.uY(rotate));
              rotate = groupD8.add(rotate, 2);
              this.x3 = cX + (w2 * groupD8.uX(rotate));
              this.y3 = cY + (h2 * 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;
      };
      TextureUvs.prototype.toString = function () {
          return "[@pixi/core:TextureUvs "
              + ("x0=" + this.x0 + " y0=" + this.y0 + " ")
              + ("x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " ")
              + ("y2=" + this.y2 + " x3=" + this.x3 + " y3=" + this.y3)
              + "]";
      };
      return TextureUvs;
  }());

  var DEFAULT_UVS = new TextureUvs();
  /**
   * 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.
   *
   * @memberof PIXI
   * @typeParam R - The BaseTexture's Resource type.
   */
  var Texture = /** @class */ (function (_super) {
      __extends$2(Texture, _super);
      /**
       * @param baseTexture - The base texture source to create the texture from
       * @param frame - The rectangle frame of the texture to show
       * @param orig - The area of original texture
       * @param trim - Trimmed rectangle of original texture
       * @param rotate - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8}
       * @param anchor - Default anchor point used for sprite placement / rotation
       */
      function Texture(baseTexture, frame, orig, trim, rotate, anchor) {
          var _this = _super.call(this) || this;
          _this.noFrame = false;
          if (!frame) {
              _this.noFrame = true;
              frame = new Rectangle(0, 0, 1, 1);
          }
          if (baseTexture instanceof Texture) {
              baseTexture = baseTexture.baseTexture;
          }
          _this.baseTexture = baseTexture;
          _this._frame = frame;
          _this.trim = trim;
          _this.valid = false;
          _this._uvs = DEFAULT_UVS;
          _this.uvMatrix = null;
          _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.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0);
          _this._updateID = 0;
          _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;
      }
      /**
       * Updates this texture on the gpu.
       *
       * Calls the TextureResource update.
       *
       * If you adjusted `frame` manually, please call `updateUvs()` instead.
       */
      Texture.prototype.update = function () {
          if (this.baseTexture.resource) {
              this.baseTexture.resource.update();
          }
      };
      /**
       * Called when the base texture is updated
       *
       * @protected
       * @param baseTexture - The base texture.
       */
      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();
          }
          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.emit('update', this);
      };
      /**
       * Destroys this texture
       *
       * @param [destroyBase=false] - Whether to destroy the base texture as well
       */
      Texture.prototype.destroy = function (destroyBase) {
          if (this.baseTexture) {
              if (destroyBase) {
                  var resource = this.baseTexture.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 && resource.url && TextureCache[resource.url]) {
                      Texture.removeFromCache(resource.url);
                  }
                  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;
      };
      /**
       * Creates a new texture object that acts the same as this one.
       *
       * @return - The new texture
       */
      Texture.prototype.clone = function () {
          var clonedFrame = this._frame.clone();
          var clonedOrig = this._frame === this.orig ? clonedFrame : this.orig.clone();
          var clonedTexture = new Texture(this.baseTexture, !this.noFrame && clonedFrame, clonedOrig, this.trim && this.trim.clone(), this.rotate, this.defaultAnchor);
          if (this.noFrame) {
              clonedTexture._frame = clonedFrame;
          }
          return clonedTexture;
      };
      /**
       * 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();
          }
          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
       *
       * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source -
       *        Source to create texture from
       * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
       * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id
       * @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.STRICT_TEXTURE_CACHE; }
          var isFrame = typeof source === 'string';
          var cacheId = null;
          if (isFrame) {
              cacheId = source;
          }
          else if (source instanceof BaseTexture) {
              if (!source.cacheId) {
                  var prefix = (options && options.pixiIdPrefix) || 'pixiid';
                  source.cacheId = prefix + "-" + uid();
                  BaseTexture.addToCache(source, source.cacheId);
              }
              cacheId = source.cacheId;
          }
          else {
              if (!source._pixiId) {
                  var prefix = (options && options.pixiIdPrefix) || 'pixiid';
                  source._pixiId = prefix + "_" + uid();
              }
              cacheId = source._pixiId;
          }
          var texture = TextureCache[cacheId];
          // Strict-mode rejects invalid cacheIds
          if (isFrame && strict && !texture) {
              throw new Error("The cacheId \"" + cacheId + "\" does not exist in TextureCache.");
          }
          if (!texture && !(source instanceof BaseTexture)) {
              if (!options.resolution) {
                  options.resolution = getResolutionOfUrl(source);
              }
              texture = new Texture(new BaseTexture(source, options));
              texture.baseTexture.cacheId = cacheId;
              BaseTexture.addToCache(texture.baseTexture, cacheId);
              Texture.addToCache(texture, cacheId);
          }
          else if (!texture && (source instanceof BaseTexture)) {
              texture = new Texture(source);
              Texture.addToCache(texture, cacheId);
          }
          // lets assume its a base texture!
          return texture;
      };
      /**
       * 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 url - The remote URL to load.
       * @param options - Optional options to include
       * @return - A Promise that resolves to a Texture.
       */
      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);
          }
          // Manually load the texture, this should allow users to handle load errors
          return resource.load().then(function () { return Promise.resolve(texture); });
      };
      /**
       * Create a new Texture with a BufferResource from a Float32Array.
       * RGBA values are floats from 0 to 1.
       *
       * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data
       *        is provided, a new Float32Array is created.
       * @param width - Width of the resource
       * @param height - Height of the resource
       * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
       * @return - The resulting new BaseTexture
       */
      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.
       *
       * @param {HTMLImageElement|HTMLCanvasElement|string} source - The input source.
       * @param imageUrl - File name of texture, for cache and resolving resolution.
       * @param name - Human readable name for the texture cache. If no name is
       *        specified, only `imageUrl` will be used as the cache ID.
       * @return - Output texture
       */
      Texture.fromLoader = function (source, imageUrl, name, options) {
          var baseTexture = new BaseTexture(source, Object.assign({
              scaleMode: settings.SCALE_MODE,
              resolution: getResolutionOfUrl(imageUrl),
          }, options));
          var resource = baseTexture.resource;
          if (resource instanceof ImageResource) {
              resource.url = imageUrl;
          }
          var texture = new Texture(baseTexture);
          // No name, use imageUrl instead
          if (!name) {
              name = imageUrl;
          }
          // 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);
          }
          // Generally images are valid right away
          if (texture.baseTexture.valid) {
              return Promise.resolve(texture);
          }
          // SVG assets need to be parsed async, let's wait
          return new Promise(function (resolve) {
              texture.baseTexture.once('loaded', function () { return resolve(texture); });
          });
      };
      /**
       * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object.
       *
       * @param texture - The Texture to add to the cache.
       * @param id - The id that the Texture will be stored against.
       */
      Texture.addToCache = function (texture, id) {
          if (id) {
              if (texture.textureCacheIds.indexOf(id) === -1) {
                  texture.textureCacheIds.push(id);
              }
              if (TextureCache[id]) {
                  // eslint-disable-next-line no-console
                  console.warn("Texture added to the cache with an id [" + id + "] that already had an entry");
              }
              TextureCache[id] = texture;
          }
      };
      /**
       * Remove a Texture from the global TextureCache.
       *
       * @param texture - id of a Texture to be removed, or a Texture instance itself
       * @return - The Texture that was removed
       */
      Texture.removeFromCache = function (texture) {
          if (typeof texture === 'string') {
              var textureFromCache = TextureCache[texture];
              if (textureFromCache) {
                  var index = textureFromCache.textureCacheIds.indexOf(texture);
                  if (index > -1) {
                      textureFromCache.textureCacheIds.splice(index, 1);
                  }
                  delete 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 (TextureCache[texture.textureCacheIds[i]] === texture) {
                      delete TextureCache[texture.textureCacheIds[i]];
                  }
              }
              texture.textureCacheIds.length = 0;
              return texture;
          }
          return null;
      };
      Object.defineProperty(Texture.prototype, "resolution", {
          /**
           * Returns resolution of baseTexture
           *
           * @readonly
           */
          get: function () {
              return this.baseTexture.resolution;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Texture.prototype, "frame", {
          /**
           * The frame specifies the region of the base texture that this texture uses.
           * Please call `updateUvs()` after you change coordinates of `frame` manually.
           */
          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", {
          /**
           * 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
           */
          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 width of the Texture in pixels. */
          get: function () {
              return this.orig.width;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Texture.prototype, "height", {
          /** The height of the Texture in pixels. */
          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;
  }(eventemitter3));
  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);

  /**
   * 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});
   * ```
   * Note that you should not create a new renderer, but reuse the same one as the rest of the 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
   *
   * ```js
   *
   * sprite.setTransform()
   *
   * let renderTexture = new PIXI.RenderTexture.create({ width: 100, height: 100 });
   *
   * renderer.render(sprite, {renderTexture});  // Renders to center of RenderTexture
   * ```
   *
   * @memberof PIXI
   */
  var RenderTexture = /** @class */ (function (_super) {
      __extends$2(RenderTexture, _super);
      /**
       * @param baseRenderTexture - The base texture object that this texture uses.
       * @param frame - The rectangle frame of the texture to show.
       */
      function RenderTexture(baseRenderTexture, frame) {
          var _this = _super.call(this, baseRenderTexture, frame) || this;
          _this.valid = true;
          _this.filterFrame = null;
          _this.filterPoolKey = null;
          _this.updateUvs();
          return _this;
      }
      Object.defineProperty(RenderTexture.prototype, "framebuffer", {
          /**
           * Shortcut to `this.baseTexture.framebuffer`, saves baseTexture cast.
           *
           * @readonly
           */
          get: function () {
              return this.baseTexture.framebuffer;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(RenderTexture.prototype, "multisample", {
          /**
           * Shortcut to `this.framebuffer.multisample`.
           *
           * @default PIXI.MSAA_QUALITY.NONE
           */
          get: function () {
              return this.framebuffer.multisample;
          },
          set: function (value) {
              this.framebuffer.multisample = value;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Resizes the RenderTexture.
       *
       * @param desiredWidth - The desired width to resize to.
       * @param desiredHeight - The desired height to resize to.
       * @param resizeBaseTexture - Should the baseTexture.width and height values be resized as well?
       */
      RenderTexture.prototype.resize = function (desiredWidth, desiredHeight, resizeBaseTexture) {
          if (resizeBaseTexture === void 0) { resizeBaseTexture = true; }
          var resolution = this.baseTexture.resolution;
          var width = Math.round(desiredWidth * resolution) / resolution;
          var height = Math.round(desiredHeight * resolution) / resolution;
          // 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();
      };
      /**
       * Changes the resolution of baseTexture, but does not change framebuffer size.
       *
       * @param resolution - The new resolution to apply to RenderTexture
       */
      RenderTexture.prototype.setResolution = function (resolution) {
          var baseTexture = this.baseTexture;
          if (baseTexture.resolution === resolution) {
              return;
          }
          baseTexture.setResolution(resolution);
          this.resize(baseTexture.width, baseTexture.height, false);
      };
      RenderTexture.create = function (options) {
          var arguments$1 = arguments;

          var rest = [];
          for (var _i = 1; _i < arguments.length; _i++) {
              rest[_i - 1] = arguments$1[_i];
          }
          // @deprecated fallback, old-style: create(width, height, scaleMode, resolution)
          if (typeof options === 'number') {
              deprecation('6.0.0', 'Arguments (width, height, scaleMode, resolution) have been deprecated.');
              /* eslint-disable prefer-rest-params */
              options = {
                  width: options,
                  height: rest[0],
                  scaleMode: rest[1],
                  resolution: rest[2],
              };
              /* eslint-enable prefer-rest-params */
          }
          return new RenderTexture(new BaseRenderTexture(options));
      };
      return RenderTexture;
  }(Texture));

  /**
   * 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
   *
   * @memberof PIXI
   */
  var RenderTexturePool = /** @class */ (function () {
      /**
       * @param 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 || {};
          this.enableFullScreen = false;
          this._pixelsWidth = 0;
          this._pixelsHeight = 0;
      }
      /**
       * Creates texture with params that were specified in pool constructor.
       *
       * @param realWidth - Width of texture in pixels.
       * @param realHeight - Height of texture in pixels.
       * @param multisample - Number of samples of the framebuffer.
       */
      RenderTexturePool.prototype.createTexture = function (realWidth, realHeight, multisample) {
          if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; }
          var baseRenderTexture = new BaseRenderTexture(Object.assign({
              width: realWidth,
              height: realHeight,
              resolution: 1,
              multisample: multisample,
          }, this.textureOptions));
          return new RenderTexture(baseRenderTexture);
      };
      /**
       * Gets a Power-of-Two render texture or fullScreen texture
       *
       * @param minWidth - The minimum width of the render texture.
       * @param minHeight - The minimum height of the render texture.
       * @param resolution - The resolution of the render texture.
       * @param multisample - Number of samples of the render texture.
       * @return The new render texture.
       */
      RenderTexturePool.prototype.getOptimalTexture = function (minWidth, minHeight, resolution, multisample) {
          if (resolution === void 0) { resolution = 1; }
          if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; }
          var key;
          minWidth = Math.ceil((minWidth * resolution) - 1e-6);
          minHeight = Math.ceil((minHeight * resolution) - 1e-6);
          if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) {
              minWidth = nextPow2(minWidth);
              minHeight = nextPow2(minHeight);
              key = (((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF)) >>> 0;
              if (multisample > 1) {
                  key += multisample * 0x100000000;
              }
          }
          else {
              key = multisample > 1 ? -multisample : -1;
          }
          if (!this.texturePool[key]) {
              this.texturePool[key] = [];
          }
          var renderTexture = this.texturePool[key].pop();
          if (!renderTexture) {
              renderTexture = this.createTexture(minWidth, minHeight, multisample);
          }
          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 input - renderTexture from which size and resolution will be copied
       * @param resolution - override resolution of the renderTexture
       *  It overrides, it does not multiply
       * @param multisample - number of samples of the renderTexture
       * @returns
       */
      RenderTexturePool.prototype.getFilterTexture = function (input, resolution, multisample) {
          var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE);
          filterTexture.filterFrame = input.filterFrame;
          return filterTexture;
      };
      /**
       * Place a render texture back into the pool.
       *
       * @param renderTexture - The renderTexture to free
       */
      RenderTexturePool.prototype.returnTexture = function (renderTexture) {
          var key = renderTexture.filterPoolKey;
          renderTexture.filterFrame = null;
          this.texturePool[key].push(renderTexture);
      };
      /**
       * Alias for returnTexture, to be compliant with FilterSystem interface.
       *
       * @param renderTexture - The renderTexture to free
       */
      RenderTexturePool.prototype.returnFilterTexture = function (renderTexture) {
          this.returnTexture(renderTexture);
      };
      /**
       * Clears the pool.
       *
       * @param destroyTextures - Destroy all stored textures.
       */
      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);
                      }
                  }
              }
          }
          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 size - Initial size of screen.
       */
      RenderTexturePool.prototype.setScreenSize = function (size) {
          if (size.width === this._pixelsWidth
              && size.height === this._pixelsHeight) {
              return;
          }
          this.enableFullScreen = size.width > 0 && size.height > 0;
          for (var i in this.texturePool) {
              if (!(Number(i) < 0)) {
                  continue;
              }
              var textures = this.texturePool[i];
              if (textures) {
                  for (var j = 0; j < textures.length; j++) {
                      textures[j].destroy(true);
                  }
              }
              this.texturePool[i] = [];
          }
          this._pixelsWidth = size.width;
          this._pixelsHeight = size.height;
      };
      /**
       * Key that is used to store fullscreen renderTextures in a pool
       *
       * @constant
       */
      RenderTexturePool.SCREEN_KEY = -1;
      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.
   *
   * @memberof PIXI
   */
  var Attribute = /** @class */ (function () {
      /**
       * @param buffer - the id of the buffer that this attribute will look for
       * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2.
       * @param normalized - should the data be normalized.
       * @param {PIXI.TYPES} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available
       * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data)
       * @param [start=0] - How far into the array to start reading values (used for interleaving data)
       * @param [instance=false] - Whether the geometry is instanced.
       */
      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 = exports.TYPES.FLOAT; }
          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 () {
          this.buffer = null;
      };
      /**
       * Helper function that creates an Attribute based on the information provided
       *
       * @param buffer - the id of the buffer that this attribute will look for
       * @param [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
       * @param [normalized=false] - should the data be normalized.
       * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available
       * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data)
       * @returns - A new {@link PIXI.Attribute} based on the information provided
       */
      Attribute.from = function (buffer, size, normalized, type, stride) {
          return new Attribute(buffer, size, normalized, type, stride);
      };
      return Attribute;
  }());

  var UID = 0;
  /**
   * A wrapper for data so that it can be used and uploaded by WebGL
   *
   * @memberof PIXI
   */
  var Buffer = /** @class */ (function () {
      /**
       * @param {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} data - the data to store in the buffer.
       * @param _static - `true` for static buffer
       * @param index - `true` for index buffer
       */
      function Buffer(data, _static, index) {
          if (_static === void 0) { _static = true; }
          if (index === void 0) { index = false; }
          this.data = (data || new Float32Array(1));
          this._glBuffers = {};
          this._updateID = 0;
          this.index = index;
          this.static = _static;
          this.id = UID++;
          this.disposeRunner = new Runner('disposeBuffer');
      }
      // TODO could explore flagging only a partial upload?
      /**
       * Flags this buffer as requiring an upload to the GPU.
       * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView|number[]} [data] - the data to update in the buffer.
       */
      Buffer.prototype.update = function (data) {
          if (data instanceof Array) {
              data = new Float32Array(data);
          }
          this.data = data || this.data;
          this._updateID++;
      };
      /** Disposes WebGL resources that are connected to this geometry. */
      Buffer.prototype.dispose = function () {
          this.disposeRunner.emit(this, false);
      };
      /** Destroys the buffer. */
      Buffer.prototype.destroy = function () {
          this.dispose();
          this.data = null;
      };
      Object.defineProperty(Buffer.prototype, "index", {
          get: function () {
              return this.type === exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
          },
          /**
           * Flags whether this is an index buffer.
           *
           * Index buffers are of type `ELEMENT_ARRAY_BUFFER`. Note that setting this property to false will make
           * the buffer of type `ARRAY_BUFFER`.
           *
           * For backwards compatibility.
           */
          set: function (value) {
              this.type = value ? exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER : exports.BUFFER_TYPE.ARRAY_BUFFER;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Helper function that creates a buffer based on an array or TypedArray
       *
       * @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 - A new Buffer based on the data provided.
       */
      Buffer.from = function (data) {
          if (data instanceof Array) {
              data = new Float32Array(data);
          }
          return new Buffer(data);
      };
      return Buffer;
  }());

  /* eslint-disable object-shorthand */
  var map$1 = {
      Float32Array: Float32Array,
      Uint32Array: Uint32Array,
      Int32Array: Int32Array,
      Uint8Array: Uint8Array,
  };
  function interleaveTypedArrays$1(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$1[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$1 = {
      Float32Array: Float32Array,
      Uint32Array: Uint32Array,
      Int32Array: Int32Array,
      Uint8Array: Uint8Array,
      Uint16Array: Uint16Array,
  };
  /* eslint-disable max-len */
  /**
   * 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();
   *
   * 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])
   * ```
   *
   * @memberof PIXI
   */
  var Geometry = /** @class */ (function () {
      /**
       * @param buffers - An array of buffers. optional.
       * @param 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;
          this.glVertexArrayObjects = {};
          this.id = UID$1++;
          this.instanced = false;
          this.instanceCount = 1;
          this.disposeRunner = new Runner('disposeGeometry');
          this.refCount = 0;
      }
      /**
       *
       * Adds an attribute to the geometry
       * Note: `stride` and `start` should be `undefined` if you dont know them, not 0!
       *
       * @param 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 size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
       * @param normalized - should the data be normalized.
       * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {PIXI.TYPES} to see the ones available
       * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data)
       * @param [start=0] - How far into the array to start reading values (used for interleaving data)
       * @param instance - Instancing flag
       * @return - 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;
          }
          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;
      };
      /**
       * Returns the requested attribute.
       *
       * @param id - The name of the attribute required
       * @return - The attribute requested.
       */
      Geometry.prototype.getAttribute = function (id) {
          return this.attributes[id];
      };
      /**
       * Returns the requested buffer.
       *
       * @param id - The name of the buffer required.
       * @return - The buffer requested.
       */
      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 - 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);
          }
          buffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
          this.indexBuffer = buffer;
          if (this.buffers.indexOf(buffer) === -1) {
              this.buffers.push(buffer);
          }
          return this;
      };
      /**
       * Returns the index buffer
       *
       * @return - The index buffer.
       */
      Geometry.prototype.getIndex = function () {
          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
       *
       * @return - Returns self, useful for chaining.
       */
      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$1(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;
      };
      /** Get the size of the geometries, in vertices. */
      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;
      };
      /** Disposes WebGL resources that are connected to this geometry. */
      Geometry.prototype.dispose = function () {
          this.disposeRunner.emit(this, false);
      };
      /** Destroys the geometry. */
      Geometry.prototype.destroy = function () {
          this.dispose();
          this.buffers = null;
          this.indexBuffer = null;
          this.attributes = null;
      };
      /**
       * Returns a clone of the geometry.
       *
       * @returns - 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.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
          }
          return geometry;
      };
      /**
       * Merges an array of geometries into a new single one.
       *
       * Geometry attribute styles must match for this operation to work.
       *
       * @param geometries - array of geometries to merge
       * @return - 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$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.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
              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 += geometries[i].buffers[bufferIndexToCount].data.length / (stride);
                  offset2 += indexBufferData.length;
              }
          }
          return geometryOut;
      };
      return Geometry;
  }());

  /**
   * Helper class to create a quad
   *
   * @memberof PIXI
   */
  var Quad = /** @class */ (function (_super) {
      __extends$2(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;
      }
      return Quad;
  }(Geometry));

  /**
   * Helper class to create a quad with uvs like in v4
   *
   * @memberof PIXI
   */
  var QuadUv = /** @class */ (function (_super) {
      __extends$2(QuadUv, _super);
      function QuadUv() {
          var _this = _super.call(this) || this;
          _this.vertices = new Float32Array([
              -1, -1,
              1, -1,
              1, 1,
              -1, 1 ]);
          _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;
      }
      /**
       * Maps two Rectangle to the quad.
       *
       * @param targetTextureFrame - The first rectangle
       * @param destinationFrame - The second rectangle
       * @return - Returns itself.
       */
      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;
      };
      /**
       * Legacy upload method, just marks buffers dirty.
       *
       * @returns - Returns itself.
       */
      QuadUv.prototype.invalidate = function () {
          this.vertexBuffer._updateID++;
          this.uvBuffer._updateID++;
          return this;
      };
      return QuadUv;
  }(Geometry));

  var UID$2 = 0;
  /**
   * Uniform group holds uniform map and some ID's for work
   *
   * `UniformGroup` has two modes:
   *
   * 1: Normal mode
   * Normal mode will upload the uniforms with individual function calls as required
   *
   * 2: Uniform buffer mode
   * This mode will treat the uniforms as a uniform buffer. You can pass in either a buffer that you manually handle, or
   * or a generic object that PixiJS will automatically map to a buffer for you.
   * For maximum benefits, make Ubo UniformGroups static, and only update them each frame.
   *
   * Rules of UBOs:
   * - UBOs only work with WebGL2, so make sure you have a fallback!
   * - Only floats are supported (including vec[2,3,4], mat[2,3,4])
   * - Samplers cannot be used in ubo's (a GPU limitation)
   * - You must ensure that the object you pass in exactly matches in the shader ubo structure.
   * Otherwise, weirdness will ensue!
   * - The name of the ubo object added to the group must match exactly the name of the ubo in the shader.
   *
   * ```
   * // ubo in shader:
   * uniform myCoolData { // declaring a ubo..
   * mat4 uCoolMatrix;
   * float uFloatyMcFloatFace
   *
   *
   * // a new uniform buffer object..
   * const myCoolData = new UniformBufferGroup({
   *   uCoolMatrix: new Matrix(),
   *   uFloatyMcFloatFace: 23,
   * }}
   *
   * // build a shader...
   * const shader = Shader.from(srcVert, srcFrag, {
   *   myCoolData // name matches the ubo name in the shader. will be processed accordingly.
   * })
   *
   *  ```
   *
   * @memberof PIXI
   */
  var UniformGroup = /** @class */ (function () {
      /**
       * @param {object | Buffer} [uniforms] - Custom uniforms to use to augment the built-in ones. Or a pixi buffer.
       * @param isStatic - Uniforms wont be changed after creation.
       * @param isUbo - If true, will treat this uniform group as a uniform buffer object.
       */
      function UniformGroup(uniforms, isStatic, isUbo) {
          this.group = true;
          // lets generate this when the shader ?
          this.syncUniforms = {};
          this.dirtyId = 0;
          this.id = UID$2++;
          this.static = !!isStatic;
          this.ubo = !!isUbo;
          if (uniforms instanceof Buffer) {
              this.buffer = uniforms;
              this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER;
              this.autoManage = false;
              this.ubo = true;
          }
          else {
              this.uniforms = uniforms;
              if (this.ubo) {
                  this.buffer = new Buffer(new Float32Array(1));
                  this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER;
                  this.autoManage = true;
              }
          }
      }
      UniformGroup.prototype.update = function () {
          this.dirtyId++;
          if (!this.autoManage && this.buffer) {
              this.buffer.update();
          }
      };
      UniformGroup.prototype.add = function (name, uniforms, _static) {
          if (!this.ubo) {
              this.uniforms[name] = new UniformGroup(uniforms, _static);
          }
          else {
              // eslint-disable-next-line max-len
              throw new Error('[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them');
          }
      };
      UniformGroup.from = function (uniforms, _static, _ubo) {
          return new UniformGroup(uniforms, _static, _ubo);
      };
      /**
       * A short hand function for creating a static UBO UniformGroup.
       *
       * @param uniforms - the ubo item
       * @param _static - should this be updated each time it is used? defaults to true here!
       */
      UniformGroup.uboFrom = function (uniforms, _static) {
          return new UniformGroup(uniforms, _static !== null && _static !== void 0 ? _static : true, true);
      };
      return UniformGroup;
  }());

  /**
   * System plugin to the renderer to manage filter states.
   *
   * @ignore
   */
  var FilterState = /** @class */ (function () {
      function FilterState() {
          this.renderTexture = null;
          this.target = null;
          this.legacy = false;
          this.resolution = 1;
          this.multisample = exports.MSAA_QUALITY.NONE;
          // next three fields are created only for root
          // re-assigned for everything else
          this.sourceFrame = new Rectangle();
          this.destinationFrame = new Rectangle();
          this.bindingSourceFrame = new Rectangle();
          this.bindingDestinationFrame = new Rectangle();
          this.filters = [];
          this.transform = null;
      }
      /** Clears the state */
      FilterState.prototype.clear = function () {
          this.target = null;
          this.filters = null;
          this.renderTexture = null;
      };
      return FilterState;
  }());

  var tempPoints$1 = [new Point(), new Point(), new Point(), new Point()];
  var tempMatrix = new Matrix();
  /**
   * System plugin to the renderer to manage filters.
   *
   * ## Pipeline
   *
   * The FilterSystem executes the filtering pipeline by rendering the display-object into a texture, applying its
   * [filters]{@link PIXI.Filter} in series, and the last filter outputs into the final render-target.
   *
   * The filter-frame is the rectangle in world space being filtered, and those contents are mapped into
   * `(0, 0, filterFrame.width, filterFrame.height)` into the filter render-texture. The filter-frame is also called
   * the source-frame, as it is used to bind the filter render-textures. The last filter outputs to the `filterFrame`
   * in the final render-target.
   *
   * ## Usage
   *
   * {@link PIXI.Container#renderAdvanced} is an example of how to use the filter system. It is a 3 step process:
   *
   * * **push**: Use {@link PIXI.FilterSystem#push} to push the set of filters to be applied on a filter-target.
   * * **render**: Render the contents to be filtered using the renderer. The filter-system will only capture the contents
   *      inside the bounds of the filter-target. NOTE: Using {@link PIXI.Renderer#render} is
   *      illegal during an existing render cycle, and it may reset the filter system.
   * * **pop**: Use {@link PIXI.FilterSystem#pop} to pop & execute the filters you initially pushed. It will apply them
   *      serially and output to the bounds of the filter-target.
   *
   * @memberof PIXI
   */
  var FilterSystem = /** @class */ (function () {
      /**
       * @param renderer - The renderer this System works for.
       */
      function FilterSystem(renderer) {
          this.renderer = renderer;
          this.defaultFilterStack = [{}];
          this.texturePool = new RenderTexturePool();
          this.texturePool.setScreenSize(renderer.view);
          this.statePool = [];
          this.quad = new Quad();
          this.quadUv = new QuadUv();
          this.tempRect = new Rectangle();
          this.activeState = {};
          this.globalUniforms = new UniformGroup({
              outputFrame: new Rectangle(),
              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.forceClear = false;
          this.useMaxPadding = false;
      }
      /**
       * Pushes a set of filters to be applied later to the system. This will redirect further rendering into an
       * input render-texture for the rest of the filtering pipeline.
       *
       * @param {PIXI.DisplayObject} target - The target of the filter to render.
       * @param filters - The filters to apply.
       */
      FilterSystem.prototype.push = function (target, filters) {
          var _a, _b;
          var renderer = this.renderer;
          var filterStack = this.defaultFilterStack;
          var state = this.statePool.pop() || new FilterState();
          var renderTextureSystem = this.renderer.renderTexture;
          var resolution = filters[0].resolution;
          var multisample = filters[0].multisample;
          var padding = filters[0].padding;
          var autoFit = filters[0].autoFit;
          // We don't know whether it's a legacy filter until it was bound for the first time,
          // therefore we have to assume that it is if legacy is undefined.
          var legacy = (_a = filters[0].legacy) !== null && _a !== void 0 ? _a : true;
          for (var i = 1; i < filters.length; i++) {
              var filter = filters[i];
              // let's use the lowest resolution
              resolution = Math.min(resolution, filter.resolution);
              // let's use the lowest number of samples
              multisample = Math.min(multisample, filter.multisample);
              // 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 || ((_b = filter.legacy) !== null && _b !== void 0 ? _b : true);
          }
          if (filterStack.length === 1) {
              this.defaultFilterStack[0].renderTexture = renderTextureSystem.current;
          }
          filterStack.push(state);
          state.resolution = resolution;
          state.multisample = multisample;
          state.legacy = legacy;
          state.target = target;
          state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true));
          state.sourceFrame.pad(padding);
          if (autoFit) {
              var sourceFrameProjected = this.tempRect.copyFrom(renderTextureSystem.sourceFrame);
              // Project source frame into world space (if projection is applied)
              if (renderer.projection.transform) {
                  this.transformAABB(tempMatrix.copyFrom(renderer.projection.transform).invert(), sourceFrameProjected);
              }
              state.sourceFrame.fit(sourceFrameProjected);
          }
          // Round sourceFrame in screen space based on render-texture.
          this.roundFrame(state.sourceFrame, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform);
          state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution, multisample);
          state.filters = filters;
          state.destinationFrame.width = state.renderTexture.width;
          state.destinationFrame.height = state.renderTexture.height;
          var destinationFrame = this.tempRect;
          destinationFrame.x = 0;
          destinationFrame.y = 0;
          destinationFrame.width = state.sourceFrame.width;
          destinationFrame.height = state.sourceFrame.height;
          state.renderTexture.filterFrame = state.sourceFrame;
          state.bindingSourceFrame.copyFrom(renderTextureSystem.sourceFrame);
          state.bindingDestinationFrame.copyFrom(renderTextureSystem.destinationFrame);
          state.transform = renderer.projection.transform;
          renderer.projection.transform = null;
          renderTextureSystem.bind(state.renderTexture, state.sourceFrame, destinationFrame);
          renderer.framebuffer.clear(0, 0, 0, 0);
      };
      /** Pops off the filter and applies it. */
      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] = Math.round(inputSize[0] * state.resolution);
          inputPixel[1] = Math.round(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];
          this.renderer.framebuffer.blit();
          if (filters.length === 1) {
              filters[0].apply(this, state.renderTexture, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state);
              this.returnFilterTexture(state.renderTexture);
          }
          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) {
                  if (i === 1 && state.multisample > 1) {
                      flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution);
                      flop.filterFrame = flip.filterFrame;
                  }
                  filters[i].apply(this, flip, flop, exports.CLEAR_MODES.CLEAR, state);
                  var t = flip;
                  flip = flop;
                  flop = t;
              }
              filters[i].apply(this, flip, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state);
              if (i > 1 && state.multisample > 1) {
                  this.returnFilterTexture(state.renderTexture);
              }
              this.returnFilterTexture(flip);
              this.returnFilterTexture(flop);
          }
          // lastState.renderTexture is blitted when lastState is popped
          state.clear();
          this.statePool.push(state);
      };
      /**
       * Binds a renderTexture with corresponding `filterFrame`, clears it if mode corresponds.
       *
       * @param filterTexture - renderTexture to bind, should belong to filter pool or filter stack
       * @param clearMode - clearMode, by default its CLEAR/YES. See {@link PIXI.CLEAR_MODES}
       */
      FilterSystem.prototype.bindAndClear = function (filterTexture, clearMode) {
          if (clearMode === void 0) { clearMode = exports.CLEAR_MODES.CLEAR; }
          var _a = this.renderer, renderTextureSystem = _a.renderTexture, stateSystem = _a.state;
          if (filterTexture === this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) {
              // Restore projection transform if rendering into the output render-target.
              this.renderer.projection.transform = this.activeState.transform;
          }
          else {
              // Prevent projection within filtering pipeline.
              this.renderer.projection.transform = null;
          }
          if (filterTexture && filterTexture.filterFrame) {
              var destinationFrame = this.tempRect;
              destinationFrame.x = 0;
              destinationFrame.y = 0;
              destinationFrame.width = filterTexture.filterFrame.width;
              destinationFrame.height = filterTexture.filterFrame.height;
              renderTextureSystem.bind(filterTexture, filterTexture.filterFrame, destinationFrame);
          }
          else if (filterTexture !== this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) {
              renderTextureSystem.bind(filterTexture);
          }
          else {
              // Restore binding for output render-target.
              this.renderer.renderTexture.bind(filterTexture, this.activeState.bindingSourceFrame, this.activeState.bindingDestinationFrame);
          }
          // Clear the texture in BLIT mode if blending is disabled or the forceClear flag is set. The blending
          // is stored in the 0th bit of the state.
          var autoClear = (stateSystem.stateId & 1) || this.forceClear;
          if (clearMode === exports.CLEAR_MODES.CLEAR
              || (clearMode === exports.CLEAR_MODES.BLIT && autoClear)) {
              // Use framebuffer.clear because we want to clear the whole filter texture, not just the filtering
              // area over which the shaders are run. This is because filters may sampling outside of it (e.g. blur)
              // instead of clamping their arithmetic.
              this.renderer.framebuffer.clear(0, 0, 0, 0);
          }
      };
      /**
       * Draws a filter using the default rendering process.
       *
       * This should be called only by {@link Filter#apply}.
       *
       * @param filter - The filter to draw.
       * @param input - The input render target.
       * @param output - The target to output to.
       * @param clearMode - Should the output be cleared before rendering to it
       */
      FilterSystem.prototype.applyFilter = function (filter, input, output, clearMode) {
          var renderer = this.renderer;
          // Set state before binding, so bindAndClear gets the blend mode.
          renderer.state.set(filter.state);
          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.shader.bind(filter);
          // check to see if the filter is a legacy one..
          filter.legacy = !!filter.program.attributeData.aTextureCoord;
          if (filter.legacy) {
              this.quadUv.map(input._frame, input.filterFrame);
              renderer.geometry.bind(this.quadUv);
              renderer.geometry.draw(exports.DRAW_MODES.TRIANGLES);
          }
          else {
              renderer.geometry.bind(this.quad);
              renderer.geometry.draw(exports.DRAW_MODES.TRIANGLE_STRIP);
          }
      };
      /**
       * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_.
       *
       * Use `outputMatrix * vTextureCoord` in the shader.
       *
       * @param outputMatrix - The matrix to output to.
       * @param {PIXI.Sprite} sprite - The sprite to map to.
       * @return The mapped matrix.
       */
      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(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;
      };
      /** Destroys this Filter System. */
      FilterSystem.prototype.destroy = function () {
          this.renderer = null;
          // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem
          this.texturePool.clear(false);
      };
      /**
       * Gets a Power-of-Two render texture or fullScreen texture
       *
       * @param minWidth - The minimum width of the render texture in real pixels.
       * @param minHeight - The minimum height of the render texture in real pixels.
       * @param resolution - The resolution of the render texture.
       * @param multisample - Number of samples of the render texture.
       * @return - The new render texture.
       */
      FilterSystem.prototype.getOptimalFilterTexture = function (minWidth, minHeight, resolution, multisample) {
          if (resolution === void 0) { resolution = 1; }
          if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; }
          return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution, multisample);
      };
      /**
       * Gets extra render texture to use inside current filter
       * To be compliant with older filters, you can use params in any order
       *
       * @param input - renderTexture from which size and resolution will be copied
       * @param resolution - override resolution of the renderTexture
       * @param multisample - number of samples of the renderTexture
       */
      FilterSystem.prototype.getFilterTexture = function (input, resolution, multisample) {
          if (typeof input === 'number') {
              var swap = input;
              input = resolution;
              resolution = swap;
          }
          input = input || this.activeState.renderTexture;
          var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE);
          filterTexture.filterFrame = input.filterFrame;
          return filterTexture;
      };
      /**
       * Frees a render texture back into the pool.
       *
       * @param renderTexture - The renderTarget to free
       */
      FilterSystem.prototype.returnFilterTexture = function (renderTexture) {
          this.texturePool.returnTexture(renderTexture);
      };
      /** Empties the texture pool. */
      FilterSystem.prototype.emptyPool = function () {
          this.texturePool.clear(true);
      };
      /** Calls `texturePool.resize()`, affects fullScreen renderTextures. */
      FilterSystem.prototype.resize = function () {
          this.texturePool.setScreenSize(this.renderer.view);
      };
      /**
       * @param matrix - first param
       * @param rect - second param
       */
      FilterSystem.prototype.transformAABB = function (matrix, rect) {
          var lt = tempPoints$1[0];
          var lb = tempPoints$1[1];
          var rt = tempPoints$1[2];
          var rb = tempPoints$1[3];
          lt.set(rect.left, rect.top);
          lb.set(rect.left, rect.bottom);
          rt.set(rect.right, rect.top);
          rb.set(rect.right, rect.bottom);
          matrix.apply(lt, lt);
          matrix.apply(lb, lb);
          matrix.apply(rt, rt);
          matrix.apply(rb, rb);
          var x0 = Math.min(lt.x, lb.x, rt.x, rb.x);
          var y0 = Math.min(lt.y, lb.y, rt.y, rb.y);
          var x1 = Math.max(lt.x, lb.x, rt.x, rb.x);
          var y1 = Math.max(lt.y, lb.y, rt.y, rb.y);
          rect.x = x0;
          rect.y = y0;
          rect.width = x1 - x0;
          rect.height = y1 - y0;
      };
      FilterSystem.prototype.roundFrame = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) {
          if (frame.width <= 0 || frame.height <= 0 || bindingSourceFrame.width <= 0 || bindingSourceFrame.height <= 0) {
              return;
          }
          if (transform) {
              var a = transform.a, b = transform.b, c = transform.c, d = transform.d;
              // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation
              // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0).
              if ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4)
                  && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)) {
                  return;
              }
          }
          transform = transform ? tempMatrix.copyFrom(transform) : tempMatrix.identity();
          // Get forward transform from world space to screen space
          transform
              .translate(-bindingSourceFrame.x, -bindingSourceFrame.y)
              .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height)
              .translate(bindingDestinationFrame.x, bindingDestinationFrame.y);
          // Convert frame to screen space
          this.transformAABB(transform, frame);
          // Round frame in screen space
          frame.ceil(resolution);
          // Project back into world space.
          this.transformAABB(transform.invert(), frame);
      };
      return FilterSystem;
  }());

  /**
   * Base for a common object renderer that can be used as a
   * system renderer plugin.
   *
   * @memberof PIXI
   */
  var ObjectRenderer = /** @class */ (function () {
      /**
       * @param renderer - The renderer this manager works for.
       */
      function ObjectRenderer(renderer) {
          this.renderer = renderer;
      }
      /**
       * Stub method that should be used to empty the current
       * batch by rendering objects now.
       */
      ObjectRenderer.prototype.flush = function () {
          // flush!
      };
      /**
       * 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;
  }());

  /**
   * System plugin to the renderer to manage batching.
   *
   * @memberof PIXI
   */
  var BatchSystem = /** @class */ (function () {
      /**
       * @param renderer - The renderer this System works for.
       */
      function BatchSystem(renderer) {
          this.renderer = renderer;
          this.emptyRenderer = new ObjectRenderer(renderer);
          this.currentRenderer = this.emptyRenderer;
      }
      /**
       * Changes the current renderer to the one given in parameter
       *
       * @param objectRenderer - The object renderer to use.
       */
      BatchSystem.prototype.setObjectRenderer = function (objectRenderer) {
          if (this.currentRenderer === objectRenderer) {
              return;
          }
          this.currentRenderer.stop();
          this.currentRenderer = objectRenderer;
          this.currentRenderer.start();
      };
      /**
       * 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
       *
       * @param arr - arr copy destination
       * @param maxTextures - number of copied elements
       */
      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;
              }
          }
      };
      /**
       * 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 texArray - textures to bound
       * @param boundTextures - current state of bound textures
       * @param batchId - marker for _batchEnabled param of textures in texArray
       * @param maxTextures - number of texture locations to manipulate
       */
      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;
              }
          }
      };
      /**
       * @ignore
       */
      BatchSystem.prototype.destroy = function () {
          this.renderer = null;
      };
      return BatchSystem;
  }());

  var CONTEXT_UID_COUNTER = 0;
  /**
   * System plugin to the renderer to manage the context.
   *
   * @memberof PIXI
   */
  var ContextSystem = /** @class */ (function () {
      /** @param renderer - The renderer this System works for. */
      function ContextSystem(renderer) {
          this.renderer = renderer;
          this.webGLVersion = 1;
          this.extensions = {};
          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);
      }
      Object.defineProperty(ContextSystem.prototype, "isLost", {
          /**
           * `true` if the context is lost
           *
           * @readonly
           */
          get: function () {
              return (!this.gl || this.gl.isContextLost());
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Handles the context change event.
       *
       * @param {WebGLRenderingContext} gl - New WebGL context.
       */
      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();
          }
      };
      /**
       * Initializes the context.
       *
       * @protected
       * @param {WebGLRenderingContext} gl - WebGL context
       */
      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);
      };
      /**
       * Initialize from context options
       *
       * @protected
       * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
       * @param {object} options - context attributes
       */
      ContextSystem.prototype.initFromOptions = function (options) {
          var gl = this.createContext(this.renderer.view, options);
          this.initFromContext(gl);
      };
      /**
       * Helper class to create a WebGL Context
       *
       * @param canvas - the canvas element that we will get the context from
       * @param options - 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
       */
      ContextSystem.prototype.createContext = function (canvas, options) {
          var gl;
          if (settings.PREFER_ENV >= exports.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;
      };
      /** Auto-populate the {@link PIXI.ContextSystem.extensions extensions}. */
      ContextSystem.prototype.getExtensions = function () {
          // time to set up default extensions that Pixi uses.
          var gl = this.gl;
          var common = {
              anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'),
              floatTextureLinear: gl.getExtension('OES_texture_float_linear'),
              s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'),
              s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'),
              etc: gl.getExtension('WEBGL_compressed_texture_etc'),
              etc1: gl.getExtension('WEBGL_compressed_texture_etc1'),
              pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc')
                  || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'),
              atc: gl.getExtension('WEBGL_compressed_texture_atc'),
              astc: gl.getExtension('WEBGL_compressed_texture_astc')
          };
          if (this.webGLVersion === 1) {
              Object.assign(this.extensions, common, {
                  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'),
                  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, common, {
                  // Floats and half-floats
                  colorBufferFloat: gl.getExtension('EXT_color_buffer_float')
              });
          }
      };
      /**
       * Handles a lost webgl context
       *
       * @param {WebGLContextEvent} event - The context lost event.
       */
      ContextSystem.prototype.handleContextLost = function (event) {
          event.preventDefault();
      };
      /** Handles a restored webgl context. */
      ContextSystem.prototype.handleContextRestored = function () {
          this.renderer.runners.contextChange.emit(this.gl);
      };
      ContextSystem.prototype.destroy = function () {
          var view = this.renderer.view;
          this.renderer = null;
          // 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. */
      ContextSystem.prototype.postrender = function () {
          if (this.renderer.renderingToScreen) {
              this.gl.flush();
          }
      };
      /**
       * Validate context.
       *
       * @param {WebGLRenderingContext} gl - Render context.
       */
      ContextSystem.prototype.validateContext = function (gl) {
          var attributes = gl.getContextAttributes();
          var isWebGl2 = 'WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext;
          if (isWebGl2) {
              this.webGLVersion = 2;
          }
          // 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 = isWebGl2 || !!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;
  }());

  /**
   * Internal framebuffer for WebGL context.
   *
   * @memberof PIXI
   */
  var GLFramebuffer = /** @class */ (function () {
      function GLFramebuffer(framebuffer) {
          this.framebuffer = framebuffer;
          this.stencil = null;
          this.dirtyId = -1;
          this.dirtyFormat = -1;
          this.dirtySize = -1;
          this.multisample = exports.MSAA_QUALITY.NONE;
          this.msaaBuffer = null;
          this.blitFramebuffer = null;
          this.mipLevel = 0;
      }
      return GLFramebuffer;
  }());

  var tempRectangle = new Rectangle();
  /**
   * System plugin to the renderer to manage framebuffers.
   *
   * @memberof PIXI
   */
  var FramebufferSystem = /** @class */ (function () {
      /**
       * @param renderer - The renderer this System works for.
       */
      function FramebufferSystem(renderer) {
          this.renderer = renderer;
          this.managedFramebuffers = [];
          this.unknownFramebuffer = new Framebuffer(10, 10);
          this.msaaSamples = null;
      }
      /** Sets up the renderer context and necessary buffers. */
      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 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.PREFER_ENV === exports.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);
          }
      };
      /**
       * Bind a framebuffer.
       *
       * @param framebuffer
       * @param frame - frame, default is framebuffer size
       * @param mipLevel - optional mip level to set on the framebuffer - defaults to 0
       */
      FramebufferSystem.prototype.bind = function (framebuffer, frame, mipLevel) {
          if (mipLevel === void 0) { mipLevel = 0; }
          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..
              if (fbo.mipLevel !== mipLevel) {
                  framebuffer.dirtyId++;
                  framebuffer.dirtyFormat++;
                  fbo.mipLevel = mipLevel;
              }
              // now check for updates...
              if (fbo.dirtyId !== framebuffer.dirtyId) {
                  fbo.dirtyId = framebuffer.dirtyId;
                  if (fbo.dirtyFormat !== framebuffer.dirtyFormat) {
                      fbo.dirtyFormat = framebuffer.dirtyFormat;
                      fbo.dirtySize = framebuffer.dirtySize;
                      this.updateFramebuffer(framebuffer, mipLevel);
                  }
                  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) {
                  var mipWidth = (frame.width >> mipLevel);
                  var mipHeight = (frame.height >> mipLevel);
                  var scale = mipWidth / frame.width;
                  this.setViewport(frame.x * scale, frame.y * scale, mipWidth, mipHeight);
              }
              else {
                  var mipWidth = (framebuffer.width >> mipLevel);
                  var mipHeight = (framebuffer.height >> mipLevel);
                  this.setViewport(0, 0, mipWidth, mipHeight);
              }
          }
          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);
              }
          }
      };
      /**
       * Set the WebGLRenderingContext's viewport.
       *
       * @param x - X position of viewport
       * @param y - Y position of viewport
       * @param width - Width of viewport
       * @param height - Height of viewport
       */
      FramebufferSystem.prototype.setViewport = function (x, y, width, height) {
          var v = this.viewport;
          x = Math.round(x);
          y = Math.round(y);
          width = Math.round(width);
          height = Math.round(height);
          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);
          }
      };
      Object.defineProperty(FramebufferSystem.prototype, "size", {
          /**
           * Get the size of the current width and height. Returns object with `width` and `height` values.
           *
           * @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
      });
      /**
       * Clear the color of the context
       *
       * @param r - Red value from 0 to 1
       * @param g - Green value from 0 to 1
       * @param b - Blue value from 0 to 1
       * @param 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.
       */
      FramebufferSystem.prototype.clear = function (r, g, b, a, mask) {
          if (mask === void 0) { mask = exports.BUFFER_BITS.COLOR | exports.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);
      };
      /**
       * Initialize framebuffer for this context
       *
       * @protected
       * @param framebuffer
       * @returns - created GLFramebuffer
       */
      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;
      };
      /**
       * Resize the framebuffer
       *
       * @protected
       */
      FramebufferSystem.prototype.resizeFramebuffer = function (framebuffer) {
          var gl = this.gl;
          var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
          if (fbo.msaaBuffer) {
              gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer);
              gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height);
          }
          if (fbo.stencil) {
              gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil);
              if (fbo.msaaBuffer) {
                  gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height);
              }
              else {
                  gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height);
              }
          }
          var colorTextures = framebuffer.colorTextures;
          var count = colorTextures.length;
          if (!gl.drawBuffers) {
              count = Math.min(count, 1);
          }
          for (var i = 0; i < count; i++) {
              var texture = colorTextures[i];
              var parentTexture = texture.parentTextureArray || texture;
              this.renderer.texture.bind(parentTexture, 0);
          }
          if (framebuffer.depthTexture && this.writeDepthTexture) {
              this.renderer.texture.bind(framebuffer.depthTexture, 0);
          }
      };
      /**
       * Update the framebuffer
       *
       * @protected
       */
      FramebufferSystem.prototype.updateFramebuffer = function (framebuffer, mipLevel) {
          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);
          }
          if (fbo.multisample > 1 && this.canMultisampleFramebuffer(framebuffer)) {
              fbo.msaaBuffer = 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);
          }
          else if (fbo.msaaBuffer) {
              gl.deleteRenderbuffer(fbo.msaaBuffer);
              fbo.msaaBuffer = null;
              if (fbo.blitFramebuffer) {
                  fbo.blitFramebuffer.dispose();
                  fbo.blitFramebuffer = null;
              }
          }
          var activeTextures = [];
          for (var i = 0; i < count; i++) {
              var texture = colorTextures[i];
              var parentTexture = texture.parentTextureArray || texture;
              this.renderer.texture.bind(parentTexture, 0);
              if (i === 0 && fbo.msaaBuffer) {
                  continue;
              }
              gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, mipLevel);
              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, mipLevel);
              }
          }
          if ((framebuffer.stencil || framebuffer.depth) && !(framebuffer.depthTexture && this.writeDepthTexture)) {
              fbo.stencil = fbo.stencil || gl.createRenderbuffer();
              gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil);
              if (fbo.msaaBuffer) {
                  gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height);
              }
              else {
                  gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height);
              }
              gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil);
          }
          else if (fbo.stencil) {
              gl.deleteRenderbuffer(fbo.stencil);
              fbo.stencil = null;
          }
      };
      /** Returns true if the frame buffer can be multisampled. */
      FramebufferSystem.prototype.canMultisampleFramebuffer = function (framebuffer) {
          return this.renderer.context.webGLVersion !== 1
              && framebuffer.colorTextures.length <= 1 && !framebuffer.depthTexture;
      };
      /**
       * Detects number of samples that is not more than a param but as close to it as possible
       *
       * @param samples - number of samples
       * @returns - recommended number of samples
       */
      FramebufferSystem.prototype.detectSamples = function (samples) {
          var msaaSamples = this.msaaSamples;
          var res = exports.MSAA_QUALITY.NONE;
          if (samples <= 1 || msaaSamples === null) {
              return res;
          }
          for (var i = 0; i < msaaSamples.length; i++) {
              if (msaaSamples[i] <= samples) {
                  res = msaaSamples[i];
                  break;
              }
          }
          if (res === 1) {
              res = exports.MSAA_QUALITY.NONE;
          }
          return res;
      };
      /**
       * Only works with WebGL2
       *
       * 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 framebuffer - by default it blits "into itself", from renderBuffer to texture.
       * @param sourcePixels - source rectangle in pixels
       * @param destPixels - dest rectangle in pixels, assumed to be the same as sourcePixels
       */
      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.msaaBuffer) {
                  return;
              }
              var colorTexture = current.colorTextures[0];
              if (!colorTexture) {
                  return;
              }
              if (!fbo.blitFramebuffer) {
                  fbo.blitFramebuffer = new Framebuffer(current.width, current.height);
                  fbo.blitFramebuffer.addColorTexture(0, colorTexture);
              }
              framebuffer = fbo.blitFramebuffer;
              if (framebuffer.colorTextures[0] !== colorTexture) {
                  framebuffer.colorTextures[0] = colorTexture;
                  framebuffer.dirtyId++;
                  framebuffer.dirtyFormat++;
              }
              if (framebuffer.width !== current.width || framebuffer.height !== current.height) {
                  framebuffer.width = current.width;
                  framebuffer.height = current.height;
                  framebuffer.dirtyId++;
                  framebuffer.dirtySize++;
              }
          }
          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.left, sourcePixels.top, sourcePixels.right, sourcePixels.bottom, destPixels.left, destPixels.top, destPixels.right, destPixels.bottom, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR);
      };
      /**
       * Disposes framebuffer.
       *
       * @param framebuffer - framebuffer that has to be disposed of
       * @param contextLost - If context was lost, we suppress all delete function calls
       */
      FramebufferSystem.prototype.disposeFramebuffer = function (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.msaaBuffer) {
                  gl.deleteRenderbuffer(fbo.msaaBuffer);
              }
              if (fbo.stencil) {
                  gl.deleteRenderbuffer(fbo.stencil);
              }
          }
          if (fbo.blitFramebuffer) {
              fbo.blitFramebuffer.dispose();
          }
      };
      /**
       * Disposes all framebuffers, but not textures bound to them.
       *
       * @param [contextLost=false] - If context was lost, we suppress all delete function calls
       */
      FramebufferSystem.prototype.disposeAll = function (contextLost) {
          var list = this.managedFramebuffers;
          this.managedFramebuffers = [];
          for (var i = 0; i < list.length; i++) {
              this.disposeFramebuffer(list[i], contextLost);
          }
      };
      /**
       * 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.
       *
       * @private
       */
      FramebufferSystem.prototype.forceStencil = function () {
          var framebuffer = this.current;
          if (!framebuffer) {
              return;
          }
          var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
          if (!fbo || fbo.stencil) {
              return;
          }
          framebuffer.stencil = true;
          var w = framebuffer.width;
          var h = framebuffer.height;
          var gl = this.gl;
          var stencil = gl.createRenderbuffer();
          gl.bindRenderbuffer(gl.RENDERBUFFER, stencil);
          if (fbo.msaaBuffer) {
              gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, w, h);
          }
          else {
              gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h);
          }
          fbo.stencil = stencil;
          gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil);
      };
      /**
       * Resets framebuffer stored state, binds screen framebuffer.
       *
       * Should be called before renderTexture reset().
       */
      FramebufferSystem.prototype.reset = function () {
          this.current = this.unknownFramebuffer;
          this.viewport = new Rectangle();
      };
      FramebufferSystem.prototype.destroy = function () {
          this.renderer = null;
      };
      return FramebufferSystem;
  }());

  var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 };
  /**
   * System plugin to the renderer to manage geometry.
   *
   * @memberof PIXI
   */
  var GeometrySystem = /** @class */ (function () {
      /** @param renderer - The renderer this System works for. */
      function GeometrySystem(renderer) {
          this.renderer = renderer;
          this._activeGeometry = null;
          this._activeVao = null;
          this.hasVao = true;
          this.hasInstance = true;
          this.canUseUInt32ElementIndex = false;
          this.managedGeometries = {};
      }
      /** Sets up the renderer context and necessary buffers. */
      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 (context.webGLVersion !== 2) {
              // webgl 1!
              var nativeVaoExtension_1 = this.renderer.context.extensions.vertexArrayObject;
              if (settings.PREFER_ENV === exports.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;
                  };
              }
          }
          if (context.webGLVersion !== 2) {
              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;
      };
      /**
       * Binds geometry so that is can be drawn. Creating a Vao if required
       *
       * @param geometry - Instance of geometry to bind.
       * @param shader - Instance of shader to use vao for.
       */
      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];
          var incRefCount = false;
          if (!vaos) {
              this.managedGeometries[geometry.id] = geometry;
              geometry.disposeRunner.add(this);
              geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {};
              incRefCount = true;
          }
          var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader, incRefCount);
          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();
      };
      /** Reset and unbind any active VAO and geometry. */
      GeometrySystem.prototype.reset = function () {
          this.unbind();
      };
      /** Update buffers of the currently bound geometry. */
      GeometrySystem.prototype.updateBuffers = function () {
          var geometry = this._activeGeometry;
          var bufferSystem = this.renderer.buffer;
          for (var i = 0; i < geometry.buffers.length; i++) {
              var buffer = geometry.buffers[i];
              bufferSystem.update(buffer);
          }
      };
      /**
       * Check compatibility between a geometry and a program
       *
       * @param geometry - Geometry instance.
       * @param 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");
              }
          }
      };
      /**
       * Takes a geometry and program and generates a unique signature for them.
       *
       * @param geometry - To get signature from.
       * @param program - To test geometry against.
       * @return - Unique signature of the geometry and program
       */
      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, shaderAttributes[i].location);
              }
          }
          return strings.join('-');
      };
      /**
       * 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. We use a shader to infer what and how to set up the
       * attribute locations.
       *
       * @param geometry - Instance of geometry to to generate Vao for.
       * @param shader - Instance of the shader.
       * @param incRefCount - Increment refCount of all geometry buffers.
       */
      GeometrySystem.prototype.initGeometryVao = function (geometry, shader, incRefCount) {
          if (incRefCount === void 0) { incRefCount = true; }
          var gl = this.gl;
          var CONTEXT_UID = this.CONTEXT_UID;
          var bufferSystem = this.renderer.buffer;
          var program = shader.program;
          if (!program.glPrograms[CONTEXT_UID]) {
              this.renderer.shader.generateProgram(shader);
          }
          this.checkCompatibility(geometry, program);
          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 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];
          }
          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];
              }
          }
          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];
              bufferSystem.bind(buffer);
              if (incRefCount) {
                  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;
      };
      /**
       * Disposes geometry.
       *
       * @param geometry - Geometry with buffers. Only VAO will be disposed
       * @param [contextLost=false] - If context was lost, we suppress deleteVertexArray
       */
      GeometrySystem.prototype.disposeGeometry = function (geometry, contextLost) {
          var _a;
          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;
          var bufferSystem = (_a = this.renderer) === null || _a === void 0 ? void 0 : _a.buffer;
          geometry.disposeRunner.remove(this);
          if (!vaos) {
              return;
          }
          // bufferSystem may have already been destroyed..
          // if this is the case, there is no need to destroy the geometry buffers...
          // they already have been!
          if (bufferSystem) {
              for (var i = 0; i < buffers.length; i++) {
                  var buf = buffers[i]._glBuffers[this.CONTEXT_UID];
                  // my be null as context may have changed right before the dispose is called
                  if (buf) {
                      buf.refCount--;
                      if (buf.refCount === 0 && !contextLost) {
                          bufferSystem.dispose(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.
       *
       * @param [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);
          }
      };
      /**
       * Activate vertex array object.
       *
       * @param geometry - Geometry instance.
       * @param program - Shader program instance.
       */
      GeometrySystem.prototype.activateVao = function (geometry, program) {
          var gl = this.gl;
          var CONTEXT_UID = this.CONTEXT_UID;
          var bufferSystem = this.renderer.buffer;
          var buffers = geometry.buffers;
          var attributes = geometry.attributes;
          if (geometry.indexBuffer) {
              // first update the index buffer if we have one..
              bufferSystem.bind(geometry.indexBuffer);
          }
          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) {
                      bufferSystem.bind(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');
                      }
                  }
              }
          }
      };
      /**
       * Draws the currently bound geometry.
       *
       * @param type - The type primitive to render.
       * @param size - The number of elements to be rendered. If not specified, all vertices after the
       *  starting vertex will be drawn.
       * @param start - The starting vertex in the geometry to start drawing from. If not specified,
       *  drawing will start from the first vertex.
       * @param instanceCount - The number of instances of the set of elements to execute. If not specified,
       *  all instances will be drawn.
       */
      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. */
      GeometrySystem.prototype.unbind = function () {
          this.gl.bindVertexArray(null);
          this._activeVao = null;
          this._activeGeometry = null;
      };
      GeometrySystem.prototype.destroy = function () {
          this.renderer = null;
      };
      return GeometrySystem;
  }());

  /**
   * Component for masked elements.
   *
   * Holds mask mode and temporary data about current mask.
   *
   * @memberof PIXI
   */
  var MaskData = /** @class */ (function () {
      /**
       * Create MaskData
       *
       * @param {PIXI.DisplayObject} [maskObject=null] - object that describes the mask
       */
      function MaskData(maskObject) {
          if (maskObject === void 0) { maskObject = null; }
          this.type = exports.MASK_TYPES.NONE;
          this.autoDetect = true;
          this.maskObject = maskObject || null;
          this.pooled = false;
          this.isMaskData = true;
          this.resolution = null;
          this.multisample = settings.FILTER_MULTISAMPLE;
          this.enabled = true;
          this._filters = null;
          this._stencilCounter = 0;
          this._scissorCounter = 0;
          this._scissorRect = null;
          this._scissorRectLocal = null;
          this._target = null;
      }
      Object.defineProperty(MaskData.prototype, "filter", {
          /**
           * The sprite mask filter.
           * If set to `null`, the default sprite mask filter is used.
           * @default null
           */
          get: function () {
              return this._filters ? this._filters[0] : null;
          },
          set: function (value) {
              if (value) {
                  if (this._filters) {
                      this._filters[0] = value;
                  }
                  else {
                      this._filters = [value];
                  }
              }
              else {
                  this._filters = null;
              }
          },
          enumerable: false,
          configurable: true
      });
      /** Resets the mask data after popMask(). */
      MaskData.prototype.reset = function () {
          if (this.pooled) {
              this.maskObject = null;
              this.type = exports.MASK_TYPES.NONE;
              this.autoDetect = true;
          }
          this._target = null;
          this._scissorRectLocal = null;
      };
      /** Copies counters from maskData above, called from pushMask(). */
      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;
  }());

  /**
   * @private
   * @param {WebGLRenderingContext} gl - The current WebGL context {WebGLProgram}
   * @param {Number} type - the type, can be either VERTEX_SHADER or FRAGMENT_SHADER
   * @param {string} src - 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;
  }

  /**
   * will log a shader error highlighting the lines with the error
   * also will add numbers along the side.
   *
   * @param gl - the WebGLContext
   * @param shader - the shader to log errors for
   */
  function logPrettyShaderError(gl, shader) {
      var shaderSrc = gl.getShaderSource(shader)
          .split('\n')
          .map(function (line, index) { return index + ": " + line; });
      var shaderLog = gl.getShaderInfoLog(shader);
      var splitShader = shaderLog.split('\n');
      var dedupe = {};
      var lineNumbers = splitShader.map(function (line) { return parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/, '$1')); })
          .filter(function (n) {
          if (n && !dedupe[n]) {
              dedupe[n] = true;
              return true;
          }
          return false;
      });
      var logArgs = [''];
      lineNumbers.forEach(function (number) {
          shaderSrc[number - 1] = "%c" + shaderSrc[number - 1] + "%c";
          logArgs.push('background: #FF0000; color:#FFFFFF; font-size: 10px', 'font-size: 10px');
      });
      var fragmentSourceToLog = shaderSrc
          .join('\n');
      logArgs[0] = fragmentSourceToLog;
      console.error(shaderLog);
      // eslint-disable-next-line no-console
      console.groupCollapsed('click to view full shader code');
      console.warn.apply(console, logArgs);
      // eslint-disable-next-line no-console
      console.groupEnd();
  }
  /**
   *
   * logs out any program errors
   *
   * @param gl - The current WebGL context
   * @param program - the WebGL program to display errors for
   * @param vertexShader  - the fragment WebGL shader program
   * @param fragmentShader - the vertex WebGL shader program
   */
  function logProgramError(gl, program, vertexShader, fragmentShader) {
      // if linking fails, then log and cleanup
      if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
          if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
              logPrettyShaderError(gl, vertexShader);
          }
          if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
              logPrettyShaderError(gl, fragmentShader);
          }
          console.error('PixiJS Error: Could not initialize shader.');
          // if there is a program info log, log it
          if (gl.getProgramInfoLog(program) !== '') {
              console.warn('PixiJS Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program));
          }
      }
  }

  function booleanArray(size) {
      var array = new Array(size);
      for (var i = 0; i < array.length; i++) {
          array[i] = false;
      }
      return array;
  }
  /**
   * @method defaultValue
   * @memberof PIXI.glCore.shader
   * @param {string} type - Type of value
   * @param {number} size
   * @private
   */
  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 'uint':
          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 'uvec2':
              return new Uint32Array(2 * size);
          case 'uvec3':
              return new Uint32Array(3 * size);
          case 'uvec4':
              return new Uint32Array(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 a little WebGL context to use for program inspection.
   *
   * @static
   * @private
   * @returns {WebGLRenderingContext} a gl context to test with
   */
  function getTestContext() {
      if (context === unknownContext || (context && context.isContextLost())) {
          var canvas = document.createElement('canvas');
          var gl = void 0;
          if (settings.PREFER_ENV >= exports.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 = exports.PRECISION.MEDIUM;
          var gl = getTestContext();
          if (gl) {
              if (gl.getShaderPrecisionFormat) {
                  var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
                  maxFragmentPrecision = shaderFragment.precision ? exports.PRECISION.HIGH : exports.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 {PIXI.PRECISION} requestedPrecision - The request float precision of the shader.
   * @param {PIXI.PRECISION} 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 === exports.PRECISION.HIGH && maxSupportedPrecision !== exports.PRECISION.HIGH) {
              precision = exports.PRECISION.MEDIUM;
          }
          return "precision " + precision + " float;\n" + src;
      }
      else if (maxSupportedPrecision !== exports.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,
      uint: 1,
      uvec2: 2,
      uvec3: 3,
      uvec4: 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 {String} type
   * @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',
      UNSIGNED_INT: 'uint',
      UNSIGNED_INT_VEC2: 'uvec2',
      UNSIGNED_INT_VEC3: 'uvec3',
      UNSIGNED_INT_VEC4: 'uvec4',
      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];
  }

  /* 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
  //     codeUbo: (name, uniform) => {} <--- returns the string of the piece of code that uploads the
  //                                         uniform to a uniform buffer
  // }
  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
      {
          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
      {
          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            ";
          },
          codeUbo: function (name) {
              return "\n                var " + name + "_matrix = uv." + name + ".toArray(true);\n\n                data[offset] = " + name + "_matrix[0];\n                data[offset+1] = " + name + "_matrix[1];\n                data[offset+2] = " + name + "_matrix[2];\n        \n                data[offset + 4] = " + name + "_matrix[3];\n                data[offset + 5] = " + name + "_matrix[4];\n                data[offset + 6] = " + name + "_matrix[5];\n        \n                data[offset + 8] = " + name + "_matrix[6];\n                data[offset + 9] = " + name + "_matrix[7];\n                data[offset + 10] = " + name + "_matrix[8];\n            ";
          },
      },
      // uploading a pixi point as a vec2 with caching layer
      {
          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                }";
          },
          codeUbo: function (name) {
              return "\n                v = uv." + name + ";\n\n                data[offset] = v.x;\n                data[offset+1] = v.y;\n            ";
          }
      },
      // caching layer for a vec2
      {
          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
      {
          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                }";
          },
          codeUbo: function (name) {
              return "\n                    v = uv." + name + ";\n\n                    data[offset] = v.x;\n                    data[offset+1] = v.y;\n                    data[offset+2] = v.width;\n                    data[offset+3] = v.height;\n                ";
          }
      },
      // a caching layer for vec4 uploading
      {
          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                }";
          },
      } ];

  // cu = Cached value's uniform data field
  // cv = Cached value
  // v = value to upload
  // ud = uniformData
  // uv = uniformValue
  // l = location
  var GLSL_TO_SINGLE_SETTERS_CACHED = {
      float: "\n    if (cv !== v)\n    {\n        cu.value = 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\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: "\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(location, v[0], v[1], v[2], v[3]);\n    }",
      int: "\n    if (cv !== v)\n    {\n        cu.value = v;\n\n        gl.uniform1i(location, v);\n    }",
      ivec2: "\n    if (cv[0] !== v[0] || cv[1] !== v[1])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n\n        gl.uniform2i(location, v[0], v[1]);\n    }",
      ivec3: "\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.uniform3i(location, v[0], v[1], v[2]);\n    }",
      ivec4: "\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.uniform4i(location, v[0], v[1], v[2], v[3]);\n    }",
      uint: "\n    if (cv !== v)\n    {\n        cu.value = v;\n\n        gl.uniform1ui(location, v);\n    }",
      uvec2: "\n    if (cv[0] !== v[0] || cv[1] !== v[1])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n\n        gl.uniform2ui(location, v[0], v[1]);\n    }",
      uvec3: "\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.uniform3ui(location, v[0], v[1], v[2]);\n    }",
      uvec4: "\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.uniform4ui(location, v[0], v[1], v[2], v[3]);\n    }",
      bool: "\n    if (cv !== v)\n    {\n        cu.value = v;\n        gl.uniform1i(location, v);\n    }",
      bvec2: "\n    if (cv[0] != v[0] || cv[1] != v[1])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n\n        gl.uniform2i(location, v[0], v[1]);\n    }",
      bvec3: "\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.uniform3i(location, v[0], v[1], v[2]);\n    }",
      bvec4: "\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.uniform4i(location, v[0], v[1], v[2], v[3]);\n    }",
      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)',
      uint: 'gl.uniform1uiv(location, v)',
      uvec2: 'gl.uniform2uiv(location, v)',
      uvec3: 'gl.uniform3uiv(location, v)',
      uvec4: 'gl.uniform4uiv(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 _a;
      var funcFragments = ["\n        var v = null;\n        var cv = null;\n        var cu = null;\n        var t = 0;\n        var gl = renderer.gl;\n    "];
      for (var i in group.uniforms) {
          var data = uniformData[i];
          if (!data) {
              if ((_a = group.uniforms[i]) === null || _a === void 0 ? void 0 : _a.group) {
                  if (group.uniforms[i].ubo) {
                      funcFragments.push("\n                        renderer.shader.syncUniformBufferGroup(uv." + i + ", '" + i + "');\n                    ");
                  }
                  else {
                      funcFragments.push("\n                        renderer.shader.syncUniformGroup(uv." + i + ", syncData);\n                    ");
                  }
              }
              continue;
          }
          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;
              }
          }
          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            cu = ud[\"" + i + "\"];\n            cv = cu.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'));
  }

  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;
  /**
   * 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";

  var UID$3 = 0;
  var nameCache = {};
  /**
   * Helper class to create a shader program.
   *
   * @memberof PIXI
   */
  var Program = /** @class */ (function () {
      /**
       * @param vertexSrc - The source of the vertex shader.
       * @param fragmentSrc - The source of the fragment shader.
       * @param name - Name for shader
       */
      function Program(vertexSrc, fragmentSrc, name) {
          if (name === void 0) { name = 'pixi-shader'; }
          this.id = UID$3++;
          this.vertexSrc = vertexSrc || Program.defaultVertexSrc;
          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.PRECISION_VERTEX, exports.PRECISION.HIGH);
              this.fragmentSrc = setPrecision(this.fragmentSrc, settings.PRECISION_FRAGMENT, getMaxFragmentPrecision());
          }
          // currently this does not extract structs only default types
          // this is where we store shader references..
          this.glPrograms = {};
          this.syncUniforms = null;
      }
      Object.defineProperty(Program, "defaultVertexSrc", {
          /**
           * The default vertex shader source.
           *
           * @constant
           */
          get: function () {
              return defaultVertex;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Program, "defaultFragmentSrc", {
          /**
           * The default fragment shader source.
           *
           * @constant
           */
          get: function () {
              return defaultFragment;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * 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 vertexSrc - The source of the vertex shader.
       * @param fragmentSrc - The source of the fragment shader.
       * @param name - Name for shader
       * @returns A shiny new PixiJS shader program!
       */
      Program.from = function (vertexSrc, fragmentSrc, name) {
          var key = vertexSrc + fragmentSrc;
          var program = ProgramCache[key];
          if (!program) {
              ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name);
          }
          return program;
      };
      return Program;
  }());

  /**
   * A helper class for shaders.
   *
   * @memberof PIXI
   */
  var Shader = /** @class */ (function () {
      /**
       * @param program - The program the shader will use.
       * @param uniforms - Custom uniforms to use to augment the built-in ones.
       */
      function Shader(program, uniforms) {
          /**
           * Used internally to bind uniform buffer objects.
           * @ignore
           */
          this.uniformBindCount = 0;
          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({});
          }
      }
      // 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
           */
          get: function () {
              return this.uniformGroup.uniforms;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * A short hand function to create a shader based of a vertex and fragment shader.
       *
       * @param vertexSrc - The source of the vertex shader.
       * @param fragmentSrc - The source of the fragment shader.
       * @param uniforms - Custom uniforms to use to augment the built-in ones.
       * @returns A shiny new PixiJS shader!
       */
      Shader.from = function (vertexSrc, fragmentSrc, uniforms) {
          var program = Program.from(vertexSrc, fragmentSrc);
          return new Shader(program, uniforms);
      };
      return Shader;
  }());

  /* eslint-disable max-len */
  var BLEND = 0;
  var OFFSET = 1;
  var CULLING = 2;
  var DEPTH_TEST = 3;
  var WINDING = 4;
  var DEPTH_MASK = 5;
  /**
   * This is a WebGL state, and is is passed to {@link PIXI.StateSystem}.
   *
   * 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
   *
   * @memberof PIXI
   */
  var State = /** @class */ (function () {
      function State() {
          this.data = 0;
          this.blendMode = exports.BLEND_MODES.NORMAL;
          this.polygonOffset = 0;
          this.blend = true;
          this.depthMask = true;
          //  this.depthTest = true;
      }
      Object.defineProperty(State.prototype, "blend", {
          /**
           * Activates blending of the computed fragment color values.
           *
           * @default true
           */
          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
           *
           * @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.
           *
           * @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.
           *
           * @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, "depthMask", {
          /**
           * Enables or disables writing to the depth buffer.
           *
           * @default true
           */
          get: function () {
              return !!(this.data & (1 << DEPTH_MASK));
          },
          set: function (value) {
              if (!!(this.data & (1 << DEPTH_MASK)) !== value) {
                  this.data ^= (1 << DEPTH_MASK);
              }
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(State.prototype, "clockwiseFrontFace", {
          /**
           * Specifies whether or not front or back-facing polygons can be culled.
           *
           * @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.
           *
           * @default PIXI.BLEND_MODES.NORMAL
           */
          get: function () {
              return this._blendMode;
          },
          set: function (value) {
              this.blend = (value !== exports.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.
           *
           * @default 0
           */
          get: function () {
              return this._polygonOffset;
          },
          set: function (value) {
              this.offsets = !!value;
              this._polygonOffset = value;
          },
          enumerable: false,
          configurable: true
      });
      State.prototype.toString = function () {
          return "[@pixi/core:State "
              + ("blendMode=" + this.blendMode + " ")
              + ("clockwiseFrontFace=" + this.clockwiseFrontFace + " ")
              + ("culling=" + this.culling + " ")
              + ("depthMask=" + this.depthMask + " ")
              + ("polygonOffset=" + this.polygonOffset)
              + "]";
      };
      State.for2d = function () {
          var state = new State();
          state.depthTest = false;
          state.blend = true;
          return state;
      };
      return State;
  }());

  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";

  /**
   * A filter is a special shader that applies post-processing effects to an input texture and writes into an output
   * render-target.
   *
   * {@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}.
   *
   * ### Frames
   *
   * The following table summarizes the coordinate spaces used in the filtering pipeline:
   *
   * <table>
   * <thead>
   *   <tr>
   *     <th>Coordinate Space</th>
   *     <th>Description</th>
   *   </tr>
   * </thead>
   * <tbody>
   *   <tr>
   *     <td>Texture Coordinates</td>
   *     <td>
   *         The texture (or UV) coordinates in the input base-texture's space. These are normalized into the (0,1) range along
   *         both axes.
   *     </td>
   *   </tr>
   *   <tr>
   *     <td>World Space</td>
   *     <td>
   *         A point in the same space as the world bounds of any display-object (i.e. in the scene graph's space).
   *     </td>
   *   </tr>
   *   <tr>
   *     <td>Physical Pixels</td>
   *     <td>
   *         This is base-texture's space with the origin on the top-left. You can calculate these by multiplying the texture
   *         coordinates by the dimensions of the texture.
   *     </td>
   *   </tr>
   * </tbody>
   * </table>
   *
   * ### 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(modifiedTextureCoord, 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.
   *
   * @memberof PIXI
   */
  var Filter = /** @class */ (function (_super) {
      __extends$2(Filter, _super);
      /**
       * @param vertexSrc - The source of the vertex shader.
       * @param fragmentSrc - The source of the fragment shader.
       * @param uniforms - Custom uniforms to use to augment the built-in ones.
       */
      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;
          _this.padding = 0;
          _this.resolution = settings.FILTER_RESOLUTION;
          _this.multisample = settings.FILTER_MULTISAMPLE;
          _this.enabled = true;
          _this.autoFit = true;
          _this.state = new State();
          return _this;
      }
      /**
       * Applies the filter
       *
       * @param {PIXI.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
       */
      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 blend mode of the filter.
           *
           * @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.prototype, "resolution", {
          /**
           * The resolution of the filter. Setting this to be lower will lower the quality but
           * increase the performance of the filter.
           */
          get: function () {
              return this._resolution;
          },
          set: function (value) {
              this._resolution = value;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Filter, "defaultVertexSrc", {
          /**
           * The default vertex shader source
           *
           * @constant
           */
          get: function () {
              return defaultVertex$1;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Filter, "defaultFragmentSrc", {
          /**
           * The default fragment shader source
           *
           * @constant
           */
          get: function () {
              return defaultFragment$1;
          },
          enumerable: false,
          configurable: true
      });
      return Filter;
  }(Shader));

  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 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
   * @memberof PIXI
   */
  var TextureMatrix = /** @class */ (function () {
      /**
       * @param texture - observed texture
       * @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border.
       */
      function TextureMatrix(texture, clampMargin) {
          this._texture = texture;
          this.mapCoord = new Matrix();
          this.uClampFrame = new Float32Array(4);
          this.uClampOffset = new Float32Array(2);
          this._textureID = -1;
          this._updateID = 0;
          this.clampOffset = 0;
          this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin;
          this.isSimple = false;
      }
      Object.defineProperty(TextureMatrix.prototype, "texture", {
          /** Texture property. */
          get: function () {
              return this._texture;
          },
          set: function (value) {
              this._texture = value;
              this._textureID = -1;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Multiplies uvs array to transform
       *
       * @param uvs - mesh uvs
       * @param [out=uvs] - output
       * @returns - output
       */
      TextureMatrix.prototype.multiplyUvs = function (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;
          }
          return out;
      };
      /**
       * Updates matrices if texture was changed.
       *
       * @param [forceUpdate=false] - if true, matrices will be updated any case
       * @returns - Whether or not it was updated
       */
      TextureMatrix.prototype.update = function (forceUpdate) {
          var tex = this._texture;
          if (!tex || !tex.valid) {
              return false;
          }
          if (!forceUpdate
              && this._textureID === tex._updateID) {
              return false;
          }
          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.
   *
   * @memberof PIXI
   */
  var SpriteMaskFilter = /** @class */ (function (_super) {
      __extends$2(SpriteMaskFilter, _super);
      /** @ignore */
      function SpriteMaskFilter(vertexSrc, fragmentSrc, uniforms) {
          var _this = this;
          var sprite = null;
          if (typeof vertexSrc !== 'string' && fragmentSrc === undefined && uniforms === undefined) {
              sprite = vertexSrc;
              vertexSrc = undefined;
              fragmentSrc = undefined;
              uniforms = undefined;
          }
          _this = _super.call(this, vertexSrc || vertex, fragmentSrc || fragment, uniforms) || this;
          _this.maskSprite = sprite;
          _this.maskMatrix = new Matrix();
          return _this;
      }
      Object.defineProperty(SpriteMaskFilter.prototype, "maskSprite", {
          /**
           * Sprite mask
           *
           * @type {PIXI.DisplayObject}
           */
          get: function () {
              return this._maskSprite;
          },
          set: function (value) {
              this._maskSprite = value;
              if (this._maskSprite) {
                  this._maskSprite.renderable = false;
              }
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Applies the filter
       *
       * @param filterManager - The renderer to retrieve the filter from
       * @param input - The input render target.
       * @param output - The target to output to.
       * @param clearMode - Should the output be cleared before rendering to it.
       */
      SpriteMaskFilter.prototype.apply = function (filterManager, input, output, clearMode) {
          var maskSprite = this._maskSprite;
          var tex = maskSprite._texture;
          if (!tex.valid) {
              return;
          }
          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.
   *
   * There are three built-in types of masking:
   * * **Scissor Masking**: Scissor masking discards pixels that are outside of a rectangle called the scissor box. It is
   *  the most performant as the scissor test is inexpensive. However, it can only be used when the mask is rectangular.
   * * **Stencil Masking**: Stencil masking discards pixels that don't overlap with the pixels rendered into the stencil
   *  buffer. It is the next fastest option as it does not require rendering into a separate framebuffer. However, it does
   *  cause the mask to be rendered **twice** for each masking operation; hence, minimize the rendering cost of your masks.
   * * **Sprite Mask Filtering**: Sprite mask filtering discards pixels based on the red channel of the sprite-mask's
   *  texture. (Generally, the masking texture is grayscale). Using advanced techniques, you might be able to embed this
   *  type of masking in a custom shader - and hence, bypassing the masking system fully for performance wins.
   *
   * The best type of masking is auto-detected when you `push` one. To use scissor masking, you must pass in a `Graphics`
   * object with just a rectangle drawn.
   *
   * ## Mask Stacks
   *
   * In the scene graph, masks can be applied recursively, i.e. a mask can be applied during a masking operation. The mask
   * stack stores the currently applied masks in order. Each {@link PIXI.BaseRenderTexture} holds its own mask stack, i.e.
   * when you switch render-textures, the old masks only applied when you switch back to rendering to the old render-target.
   *
   * @memberof PIXI
   */
  var MaskSystem = /** @class */ (function () {
      /**
       * @param renderer - The renderer this System works for.
       */
      function MaskSystem(renderer) {
          this.renderer = renderer;
          this.enableScissor = true;
          this.alphaMaskPool = [];
          this.maskDataPool = [];
          this.maskStack = [];
          this.alphaMaskIndex = 0;
      }
      /**
       * Changes the mask stack that is used by this System.
       *
       * @param maskStack - The mask stack
       */
      MaskSystem.prototype.setMaskStack = function (maskStack) {
          this.maskStack = maskStack;
          this.renderer.scissor.setMaskStack(maskStack);
          this.renderer.stencil.setMaskStack(maskStack);
      };
      /**
       * Enables the mask and appends it to the current mask stack.
       *
       * NOTE: The batch renderer should be flushed beforehand to prevent pending renders from being masked.
       *
       * @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 (target, maskDataOrTarget) {
          var maskData = maskDataOrTarget;
          if (!maskData.isMaskData) {
              var d = this.maskDataPool.pop() || new MaskData();
              d.pooled = true;
              d.maskObject = maskDataOrTarget;
              maskData = d;
          }
          var maskAbove = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null;
          maskData.copyCountersOrReset(maskAbove);
          if (maskData.autoDetect) {
              this.detect(maskData);
          }
          maskData._target = target;
          if (maskData.type !== exports.MASK_TYPES.SPRITE) {
              this.maskStack.push(maskData);
          }
          if (maskData.enabled) {
              switch (maskData.type) {
                  case exports.MASK_TYPES.SCISSOR:
                      this.renderer.scissor.push(maskData);
                      break;
                  case exports.MASK_TYPES.STENCIL:
                      this.renderer.stencil.push(maskData);
                      break;
                  case exports.MASK_TYPES.SPRITE:
                      maskData.copyCountersOrReset(null);
                      this.pushSpriteMask(maskData);
                      break;
              }
          }
          if (maskData.type === exports.MASK_TYPES.SPRITE) {
              this.maskStack.push(maskData);
          }
      };
      /**
       * Removes the last mask from the mask stack and doesn't return it.
       *
       * NOTE: The batch renderer should be flushed beforehand to render the masked contents before the mask is removed.
       *
       * @param {PIXI.DisplayObject} target - Display Object to pop the mask from
       */
      MaskSystem.prototype.pop = function (target) {
          var maskData = this.maskStack.pop();
          if (!maskData || maskData._target !== target) {
              // TODO: add an assert when we have it
              return;
          }
          if (maskData.enabled) {
              switch (maskData.type) {
                  case exports.MASK_TYPES.SCISSOR:
                      this.renderer.scissor.pop();
                      break;
                  case exports.MASK_TYPES.STENCIL:
                      this.renderer.stencil.pop(maskData.maskObject);
                      break;
                  case exports.MASK_TYPES.SPRITE:
                      this.popSpriteMask(maskData);
                      break;
              }
          }
          maskData.reset();
          if (maskData.pooled) {
              this.maskDataPool.push(maskData);
          }
          if (this.maskStack.length !== 0) {
              var maskCurrent = this.maskStack[this.maskStack.length - 1];
              if (maskCurrent.type === exports.MASK_TYPES.SPRITE && maskCurrent._filters) {
                  maskCurrent._filters[0].maskSprite = maskCurrent.maskObject;
              }
          }
      };
      /** Sets type of MaskData based on its maskObject. */
      MaskSystem.prototype.detect = function (maskData) {
          var maskObject = maskData.maskObject;
          if (maskObject.isSprite) {
              maskData.type = exports.MASK_TYPES.SPRITE;
          }
          else if (this.enableScissor && this.renderer.scissor.testScissor(maskData)) {
              maskData.type = exports.MASK_TYPES.SCISSOR;
          }
          else {
              maskData.type = exports.MASK_TYPES.STENCIL;
          }
      };
      /**
       * Applies the Mask and adds it to the current filter stack.
       *
       * @param maskData - Sprite to be used as the mask.
       */
      MaskSystem.prototype.pushSpriteMask = function (maskData) {
          var _a, _b;
          var maskObject = maskData.maskObject;
          var target = maskData._target;
          var alphaMaskFilter = maskData._filters;
          if (!alphaMaskFilter) {
              alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex];
              if (!alphaMaskFilter) {
                  alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter()];
              }
          }
          var renderer = this.renderer;
          var renderTextureSystem = renderer.renderTexture;
          var resolution;
          var multisample;
          if (renderTextureSystem.current) {
              var renderTexture = renderTextureSystem.current;
              resolution = maskData.resolution || renderTexture.resolution;
              multisample = (_a = maskData.multisample) !== null && _a !== void 0 ? _a : renderTexture.multisample;
          }
          else {
              resolution = maskData.resolution || renderer.resolution;
              multisample = (_b = maskData.multisample) !== null && _b !== void 0 ? _b : renderer.multisample;
          }
          alphaMaskFilter[0].resolution = resolution;
          alphaMaskFilter[0].multisample = multisample;
          alphaMaskFilter[0].maskSprite = maskObject;
          var stashFilterArea = target.filterArea;
          target.filterArea = maskObject.getBounds(true);
          renderer.filter.push(target, alphaMaskFilter);
          target.filterArea = stashFilterArea;
          if (!maskData._filters) {
              this.alphaMaskIndex++;
          }
      };
      /**
       * Removes the last filter from the filter stack and doesn't return it.
       *
       * @param maskData - Sprite to be used as the mask.
       */
      MaskSystem.prototype.popSpriteMask = function (maskData) {
          this.renderer.filter.pop();
          if (maskData._filters) {
              maskData._filters[0].maskSprite = null;
          }
          else {
              this.alphaMaskIndex--;
              this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite = null;
          }
      };
      MaskSystem.prototype.destroy = function () {
          this.renderer = null;
      };
      return MaskSystem;
  }());

  /**
   * System plugin to the renderer to manage specific types of masking operations.
   *
   * @memberof PIXI
   */
  var AbstractMaskSystem = /** @class */ (function () {
      /**
       * @param renderer - The renderer this System works for.
       */
      function AbstractMaskSystem(renderer) {
          this.renderer = renderer;
          this.maskStack = [];
          this.glConst = 0;
      }
      /** Gets count of masks of certain type. */
      AbstractMaskSystem.prototype.getStackLength = function () {
          return this.maskStack.length;
      };
      /**
       * Changes the mask stack that is used by this System.
       *
       * @param {PIXI.MaskData[]} maskStack - The mask stack
       */
      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();
              }
          }
      };
      /**
       * Setup renderer to use the current mask data.
       * @private
       */
      AbstractMaskSystem.prototype._useCurrent = function () {
          // OVERWRITE;
      };
      /** Destroys the mask stack. */
      AbstractMaskSystem.prototype.destroy = function () {
          this.renderer = null;
          this.maskStack = null;
      };
      return AbstractMaskSystem;
  }());

  var tempMatrix$1 = new Matrix();
  /**
   * System plugin to the renderer to manage scissor masking.
   *
   * Scissor masking discards pixels outside of a rectangle called the scissor box. The scissor box is in the framebuffer
   * viewport's space; however, the mask's rectangle is projected from world-space to viewport space automatically
   * by this system.
   *
   * @memberof PIXI
   */
  var ScissorSystem = /** @class */ (function (_super) {
      __extends$2(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;
      }
      ScissorSystem.prototype.getStackLength = function () {
          var maskData = this.maskStack[this.maskStack.length - 1];
          if (maskData) {
              return maskData._scissorCounter;
          }
          return 0;
      };
      /**
       * evaluates _boundsTransformed, _scissorRect for MaskData
       * @param maskData
       */
      ScissorSystem.prototype.calcScissorRect = function (maskData) {
          if (maskData._scissorRectLocal) {
              return;
          }
          var prevData = maskData._scissorRect;
          var maskObject = maskData.maskObject;
          var renderer = this.renderer;
          var renderTextureSystem = renderer.renderTexture;
          maskObject.renderable = true;
          var rect = maskObject.getBounds();
          this.roundFrameToPixels(rect, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform);
          maskObject.renderable = false;
          if (prevData) {
              rect.fit(prevData);
          }
          maskData._scissorRectLocal = rect;
      };
      ScissorSystem.isMatrixRotated = function (matrix) {
          if (!matrix) {
              return false;
          }
          var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d;
          // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation
          // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0).
          return ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4)
              && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4));
      };
      /**
       * Test, whether the object can be scissor mask with current renderer projection.
       * Calls "calcScissorRect()" if its true.
       * @param maskData mask data
       * @returns whether Whether the object can be scissor mask
       */
      ScissorSystem.prototype.testScissor = function (maskData) {
          var maskObject = maskData.maskObject;
          if (!maskObject.isFastRect || !maskObject.isFastRect()) {
              return false;
          }
          if (ScissorSystem.isMatrixRotated(maskObject.worldTransform)) {
              return false;
          }
          if (ScissorSystem.isMatrixRotated(this.renderer.projection.transform)) {
              return false;
          }
          this.calcScissorRect(maskData);
          var rect = maskData._scissorRectLocal;
          return rect.width > 0 && rect.height > 0;
      };
      ScissorSystem.prototype.roundFrameToPixels = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) {
          if (ScissorSystem.isMatrixRotated(transform)) {
              return;
          }
          transform = transform ? tempMatrix$1.copyFrom(transform) : tempMatrix$1.identity();
          // Get forward transform from world space to screen space
          transform
              .translate(-bindingSourceFrame.x, -bindingSourceFrame.y)
              .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height)
              .translate(bindingDestinationFrame.x, bindingDestinationFrame.y);
          // Convert frame to screen space
          this.renderer.filter.transformAABB(transform, frame);
          frame.fit(bindingDestinationFrame);
          frame.x = Math.round(frame.x * resolution);
          frame.y = Math.round(frame.y * resolution);
          frame.width = Math.round(frame.width * resolution);
          frame.height = Math.round(frame.height * resolution);
      };
      /**
       * Applies the Mask and adds it to the current stencil stack.
       *
       * @author alvin
       * @param maskData - The mask data.
       */
      ScissorSystem.prototype.push = function (maskData) {
          if (!maskData._scissorRectLocal) {
              this.calcScissorRect(maskData);
          }
          var gl = this.renderer.gl;
          if (!maskData._scissorRect) {
              gl.enable(gl.SCISSOR_TEST);
          }
          maskData._scissorCounter++;
          maskData._scissorRect = maskData._scissorRectLocal;
          this._useCurrent();
      };
      /**
       * This should be called after a mask is popped off the mask stack. It will rebind the scissor box to be latest with the
       * last mask in the stack.
       *
       * This can also be called when you directly modify the scissor box and want to restore PixiJS state.
       */
      ScissorSystem.prototype.pop = function () {
          var gl = this.renderer.gl;
          if (this.getStackLength() > 0) {
              this._useCurrent();
          }
          else {
              gl.disable(gl.SCISSOR_TEST);
          }
      };
      /**
       * Setup renderer to use the current scissor data.
       * @private
       */
      ScissorSystem.prototype._useCurrent = function () {
          var rect = this.maskStack[this.maskStack.length - 1]._scissorRect;
          var y;
          if (this.renderer.renderTexture.current) {
              y = rect.y;
          }
          else {
              // flipY. In future we'll have it over renderTextures as an option
              y = this.renderer.height - rect.height - rect.y;
          }
          this.renderer.gl.scissor(rect.x, y, rect.width, rect.height);
      };
      return ScissorSystem;
  }(AbstractMaskSystem));

  /**
   * System plugin to the renderer to manage stencils (used for masks).
   *
   * @memberof PIXI
   */
  var StencilSystem = /** @class */ (function (_super) {
      __extends$2(StencilSystem, _super);
      /**
       * @param renderer - The renderer this System works for.
       */
      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;
      };
      /**
       * Applies the Mask and adds it to the current stencil stack.
       *
       * @param maskData - The mask data
       */
      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.clearStencil(0);
              gl.clear(gl.STENCIL_BUFFER_BIT);
              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, 0xFFFFFFFF);
          gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
          maskObject.renderable = true;
          maskObject.render(this.renderer);
          this.renderer.batch.flush();
          maskObject.renderable = false;
          this._useCurrent();
      };
      /**
       * Pops stencil mask. MaskData is already removed from stack
       *
       * @param {PIXI.DisplayObject} maskObject - object of popped mask data
       */
      StencilSystem.prototype.pop = function (maskObject) {
          var gl = this.renderer.gl;
          if (this.getStackLength() === 0) {
              // the stack is empty!
              gl.disable(gl.STENCIL_TEST);
          }
          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();
          }
      };
      /**
       * Setup renderer to use the current stencil data.
       * @private
       */
      StencilSystem.prototype._useCurrent = function () {
          var gl = this.renderer.gl;
          gl.colorMask(true, true, true, true);
          gl.stencilFunc(gl.EQUAL, this.getStackLength(), 0xFFFFFFFF);
          gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
      };
      return StencilSystem;
  }(AbstractMaskSystem));

  /**
   * System plugin to the renderer to manage the projection matrix.
   *
   * The `projectionMatrix` is a global uniform provided to all shaders. It is used to transform points in world space to
   * normalized device coordinates.
   *
   * @memberof PIXI
   */
  var ProjectionSystem = /** @class */ (function () {
      /** @param renderer - The renderer this System works for. */
      function ProjectionSystem(renderer) {
          this.renderer = renderer;
          this.destinationFrame = null;
          this.sourceFrame = null;
          this.defaultFrame = null;
          this.projectionMatrix = new Matrix();
          this.transform = null;
      }
      /**
       * Updates the projection-matrix based on the sourceFrame → destinationFrame mapping provided.
       *
       * NOTE: It is expected you call `renderer.framebuffer.setViewport(destinationFrame)` after this. This is because
       * the framebuffer viewport converts shader vertex output in normalized device coordinates to window coordinates.
       *
       * NOTE-2: {@link RenderTextureSystem#bind} updates the projection-matrix when you bind a render-texture. It is expected
       * that you dirty the current bindings when calling this manually.
       *
       * @param destinationFrame - The rectangle in the render-target to render the contents into. If rendering to the canvas,
       *  the origin is on the top-left; if rendering to a render-texture, the origin is on the bottom-left.
       * @param sourceFrame - The rectangle in world space that contains the contents being rendered.
       * @param resolution - The resolution of the render-target, which is the ratio of
       *  world-space (or CSS) pixels to physical pixels.
       * @param root - Whether the render-target is the screen. This is required because rendering to textures
       *  is y-flipped (i.e. upside down relative to the screen).
       */
      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);
          }
      };
      /**
       * Calculates the `projectionMatrix` to map points inside `sourceFrame` to inside `destinationFrame`.
       *
       * @param destinationFrame - The destination frame in the render-target.
       * @param sourceFrame - The source frame in world space.
       * @param resolution - The render-target's resolution, i.e. ratio of CSS to physical pixels.
       * @param root - Whether rendering into the screen. Otherwise, if rendering to a framebuffer, the projection
       *  is y-flipped.
       */
      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);
      };
      /**
       * Sets the transform of the active render target to the given matrix.
       *
       * @param matrix - The transformation matrix
       */
      ProjectionSystem.prototype.setTransform = function (_matrix) {
          // this._activeRenderTarget.transform = matrix;
      };
      ProjectionSystem.prototype.destroy = function () {
          this.renderer = null;
      };
      return ProjectionSystem;
  }());

  // Temporary rectangle for assigned sourceFrame or destinationFrame
  var tempRect = new Rectangle();
  // Temporary rectangle for renderTexture destinationFrame
  var tempRect2 = new Rectangle();
  /* eslint-disable max-len */
  /**
   * System plugin to the renderer to manage render textures.
   *
   * Should be added after FramebufferSystem
   *
   * ### Frames
   *
   * The `RenderTextureSystem` holds a sourceFrame → destinationFrame projection. The following table explains the different
   * coordinate spaces used:
   *
   * | Frame                  | Description                                                      | Coordinate System                                       |
   * | ---------------------- | ---------------------------------------------------------------- | ------------------------------------------------------- |
   * | sourceFrame            | The rectangle inside of which display-objects are being rendered | **World Space**: The origin on the top-left             |
   * | destinationFrame       | The rectangle in the render-target (canvas or texture) into which contents should be rendered | If rendering to the canvas, this is in screen space and the origin is on the top-left. If rendering to a render-texture, this is in its base-texture's space with the origin on the bottom-left.  |
   * | viewportFrame          | The framebuffer viewport corresponding to the destination-frame  | **Window Coordinates**: The origin is always on the bottom-left. |
   *
   * @memberof PIXI
   */
  var RenderTextureSystem = /** @class */ (function () {
      /**
       * @param renderer - The renderer this System works for.
       */
      function RenderTextureSystem(renderer) {
          this.renderer = renderer;
          this.clearColor = renderer._backgroundColorRgba;
          this.defaultMaskStack = [];
          this.current = null;
          this.sourceFrame = new Rectangle();
          this.destinationFrame = new Rectangle();
          this.viewportFrame = new Rectangle();
      }
      /**
       * Bind the current render texture.
       *
       * @param renderTexture - RenderTexture to bind, by default its `null` - the screen.
       * @param sourceFrame - Part of world that is mapped to the renderTexture.
       * @param destinationFrame - Part of renderTexture, by default it has the same size as sourceFrame.
       */
      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 (!destinationFrame) {
                  tempRect2.x = renderTexture.frame.x;
                  tempRect2.y = renderTexture.frame.y;
                  tempRect2.width = sourceFrame.width;
                  tempRect2.height = sourceFrame.height;
                  destinationFrame = tempRect2;
              }
              framebuffer = baseTexture.framebuffer;
          }
          else {
              resolution = renderer.resolution;
              if (!sourceFrame) {
                  tempRect.width = renderer.screen.width;
                  tempRect.height = renderer.screen.height;
                  sourceFrame = tempRect;
              }
              if (!destinationFrame) {
                  destinationFrame = tempRect;
                  destinationFrame.width = sourceFrame.width;
                  destinationFrame.height = sourceFrame.height;
              }
          }
          var viewportFrame = this.viewportFrame;
          viewportFrame.x = destinationFrame.x * resolution;
          viewportFrame.y = destinationFrame.y * resolution;
          viewportFrame.width = destinationFrame.width * resolution;
          viewportFrame.height = destinationFrame.height * resolution;
          if (!renderTexture) {
              viewportFrame.y = renderer.view.height - (viewportFrame.y + viewportFrame.height);
          }
          viewportFrame.ceil();
          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);
      };
      /**
       * Erases the render texture and fills the drawing area with a colour.
       *
       * @param clearColor - The color as rgba, default to use the renderer backgroundColor
       * @param [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks
       *  that indicate the buffers to be cleared, by default COLOR and DEPTH buffers.
       */
      RenderTextureSystem.prototype.clear = function (clearColor, mask) {
          if (this.current) {
              clearColor = clearColor || this.current.baseTexture.clearColor;
          }
          else {
              clearColor = clearColor || this.clearColor;
          }
          var destinationFrame = this.destinationFrame;
          var baseFrame = this.current ? this.current.baseTexture : this.renderer.screen;
          var clearMask = destinationFrame.width !== baseFrame.width || destinationFrame.height !== baseFrame.height;
          if (clearMask) {
              var _a = this.viewportFrame, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
              x = Math.round(x);
              y = Math.round(y);
              width = Math.round(width);
              height = Math.round(height);
              // TODO: ScissorSystem should cache whether the scissor test is enabled or not.
              this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST);
              this.renderer.gl.scissor(x, y, width, height);
          }
          this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3], mask);
          if (clearMask) {
              // Restore the scissor box
              this.renderer.scissor.pop();
          }
      };
      RenderTextureSystem.prototype.resize = function () {
          // resize the root only!
          this.bind(null);
      };
      /** Resets render-texture state. */
      RenderTextureSystem.prototype.reset = function () {
          this.bind(null);
      };
      RenderTextureSystem.prototype.destroy = function () {
          this.renderer = null;
      };
      return RenderTextureSystem;
  }());

  function uboUpdate(_ud, _uv, _renderer, _syncData, buffer) {
      _renderer.buffer.update(buffer);
  }
  // cv = CachedValue
  // v = value
  // ud = uniformData
  // uv = uniformValue
  // l = location
  var UBO_TO_SINGLE_SETTERS = {
      float: "\n        data[offset] = v;\n    ",
      vec2: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n    ",
      vec3: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n        data[offset+2] = v[2];\n\n    ",
      vec4: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n        data[offset+2] = v[2];\n        data[offset+3] = v[3];\n    ",
      mat2: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n\n        data[offset+4] = v[2];\n        data[offset+5] = v[3];\n    ",
      mat3: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n        data[offset+2] = v[2];\n\n        data[offset + 4] = v[3];\n        data[offset + 5] = v[4];\n        data[offset + 6] = v[5];\n\n        data[offset + 8] = v[6];\n        data[offset + 9] = v[7];\n        data[offset + 10] = v[8];\n    ",
      mat4: "\n        for(var i = 0; i < 16; i++)\n        {\n            data[offset + i] = v[i];\n        }\n    "
  };
  var GLSL_TO_STD40_SIZE = {
      float: 4,
      vec2: 8,
      vec3: 12,
      vec4: 16,
      int: 4,
      ivec2: 8,
      ivec3: 12,
      ivec4: 16,
      uint: 4,
      uvec2: 8,
      uvec3: 12,
      uvec4: 16,
      bool: 4,
      bvec2: 8,
      bvec3: 12,
      bvec4: 16,
      mat2: 16 * 2,
      mat3: 16 * 3,
      mat4: 16 * 4,
  };
  /**
   * @ignore
   *
   * logic originally from here: https://github.com/sketchpunk/FunWithWebGL2/blob/master/lesson_022/Shaders.js
   * rewrote it, but this was a great starting point to get a solid understanding of whats going on :)
   *
   * @param uniformData
   */
  function createUBOElements(uniformData) {
      var uboElements = uniformData.map(function (data) {
          return ({
              data: data,
              offset: 0,
              dataLen: 0,
              dirty: 0
          });
      });
      var size = 0;
      var chunkSize = 0;
      var offset = 0;
      for (var i = 0; i < uboElements.length; i++) {
          var uboElement = uboElements[i];
          size = GLSL_TO_STD40_SIZE[uboElement.data.type];
          if (uboElement.data.size > 1) {
              size = Math.max(size, 16) * uboElement.data.size;
          }
          uboElement.dataLen = size;
          // add some size offset..
          // must align to the nearest 16 bytes or internally nearest round size
          if (chunkSize % size !== 0 && chunkSize < 16) {
              // diff required to line up..
              var lineUpValue = (chunkSize % size) % 16;
              chunkSize += lineUpValue;
              offset += lineUpValue;
          }
          if ((chunkSize + size) > 16) {
              offset = Math.ceil(offset / 16) * 16;
              uboElement.offset = offset;
              offset += size;
              chunkSize = size;
          }
          else {
              uboElement.offset = offset;
              chunkSize += size;
              offset += size;
          }
      }
      offset = Math.ceil(offset / 16) * 16;
      return { uboElements: uboElements, size: offset };
  }
  function getUBOData(uniforms, uniformData) {
      var usedUniformDatas = [];
      // build..
      for (var i in uniforms) {
          if (uniformData[i]) {
              usedUniformDatas.push(uniformData[i]);
          }
      }
      // sort them out by index!
      usedUniformDatas.sort(function (a, b) { return a.index - b.index; });
      return usedUniformDatas;
  }
  function generateUniformBufferSync(group, uniformData) {
      if (!group.autoManage) {
          // if the group is nott automatically managed, we don't need to generate a special function for it...
          return { size: 0, syncFunc: uboUpdate };
      }
      var usedUniformDatas = getUBOData(group.uniforms, uniformData);
      var _a = createUBOElements(usedUniformDatas), uboElements = _a.uboElements, size = _a.size;
      var funcFragments = ["\n    var v = null;\n    var v2 = null;\n    var cv = null;\n    var t = 0;\n    var gl = renderer.gl\n    var index = 0;\n    var data = buffer.data;\n    "];
      for (var i = 0; i < uboElements.length; i++) {
          var uboElement = uboElements[i];
          var uniform = group.uniforms[uboElement.data.name];
          var name = uboElement.data.name;
          var parsed = false;
          for (var j = 0; j < uniformParsers.length; j++) {
              var uniformParser = uniformParsers[j];
              if (uniformParser.codeUbo && uniformParser.test(uboElement.data, uniform)) {
                  funcFragments.push("offset = " + uboElement.offset / 4 + ";", uniformParsers[j].codeUbo(uboElement.data.name, uniform));
                  parsed = true;
                  break;
              }
          }
          if (!parsed) {
              if (uboElement.data.size > 1) {
                  var size_1 = mapSize(uboElement.data.type);
                  var rowSize = Math.max(GLSL_TO_STD40_SIZE[uboElement.data.type] / 16, 1);
                  var elementSize = size_1 / rowSize;
                  var remainder = (4 - (elementSize % 4)) % 4;
                  funcFragments.push("\n                cv = ud." + name + ".value;\n                v = uv." + name + ";\n                offset = " + uboElement.offset / 4 + ";\n\n                t = 0;\n\n                for(var i=0; i < " + uboElement.data.size * rowSize + "; i++)\n                {\n                    for(var j = 0; j < " + elementSize + "; j++)\n                    {\n                        data[offset++] = v[t++];\n                    }\n                    offset += " + remainder + ";\n                }\n\n                ");
              }
              else {
                  var template = UBO_TO_SINGLE_SETTERS[uboElement.data.type];
                  funcFragments.push("\n                cv = ud." + name + ".value;\n                v = uv." + name + ";\n                offset = " + uboElement.offset / 4 + ";\n                " + template + ";\n                ");
              }
          }
      }
      funcFragments.push("\n       renderer.buffer.update(buffer);\n    ");
      return {
          size: size,
          // eslint-disable-next-line no-new-func
          syncFunc: new Function('ud', 'uv', 'renderer', 'syncData', 'buffer', funcFragments.join('\n'))
      };
  }

  /**
   * @private
   */
  var IGLUniformData = /** @class */ (function () {
      function IGLUniformData() {
      }
      return IGLUniformData;
  }());
  /**
   * Helper class to create a WebGL Program
   *
   * @memberof PIXI
   */
  var GLProgram = /** @class */ (function () {
      /**
       * Makes a new Pixi program.
       *
       * @param program - webgl program
       * @param uniformData - uniforms
       */
      function GLProgram(program, uniformData) {
          this.program = program;
          this.uniformData = uniformData;
          this.uniformGroups = {};
          this.uniformDirtyGroups = {};
          this.uniformBufferBindings = {};
      }
      /** Destroys this program. */
      GLProgram.prototype.destroy = function () {
          this.uniformData = null;
          this.uniformGroups = null;
          this.uniformDirtyGroups = null;
          this.uniformBufferBindings = null;
          this.program = null;
      };
      return GLProgram;
  }());

  /**
   * 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
   */
  function getAttributeData(program, gl) {
      var attributes = {};
      var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
      for (var i = 0; i < totalAttributes; i++) {
          var attribData = gl.getActiveAttrib(program, i);
          if (attribData.name.indexOf('gl_') === 0) {
              continue;
          }
          var type = mapType(gl, attribData.type);
          var data = {
              type: type,
              name: attribData.name,
              size: mapSize(type),
              location: gl.getAttribLocation(program, attribData.name),
          };
          attributes[attribData.name] = data;
      }
      return attributes;
  }

  /**
   * returns the uniform data from the program
   * @private
   *
   * @param program - the webgl program
   * @param gl - the WebGL context
   *
   * @returns {object} the uniform data for this program
   */
  function getUniformData(program, gl) {
      var uniforms = {};
      var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
      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);
          uniforms[name] = {
              name: name,
              index: i,
              type: type,
              size: uniformData.size,
              isArray: isArray,
              value: defaultValue(type, uniformData.size),
          };
      }
      return uniforms;
  }

  /**
   * generates a WebGL Program object from a high level Pixi Program.
   *
   * @param gl - a rendering context on which to generate the program
   * @param program - the high level Pixi Program.
   */
  function generateProgram(gl, program) {
      var glVertShader = compileShader(gl, gl.VERTEX_SHADER, program.vertexSrc);
      var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, program.fragmentSrc);
      var webGLProgram = gl.createProgram();
      gl.attachShader(webGLProgram, glVertShader);
      gl.attachShader(webGLProgram, glFragShader);
      gl.linkProgram(webGLProgram);
      if (!gl.getProgramParameter(webGLProgram, gl.LINK_STATUS)) {
          logProgramError(gl, webGLProgram, glVertShader, glFragShader);
      }
      program.attributeData = getAttributeData(webGLProgram, gl);
      program.uniformData = getUniformData(webGLProgram, gl);
      // GLSL 1.00: bind attributes sorted by name in ascending order
      // GLSL 3.00: don't change the attribute locations that where chosen by the compiler
      //            or assigned by the layout specifier in the shader source code
      if (!(/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m).test(program.vertexSrc)) {
          var keys = Object.keys(program.attributeData);
          keys.sort(function (a, b) { return (a > b) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow
          for (var i = 0; i < keys.length; i++) {
              program.attributeData[keys[i]].location = i;
              gl.bindAttribLocation(webGLProgram, i, keys[i]);
          }
          gl.linkProgram(webGLProgram);
      }
      gl.deleteShader(glVertShader);
      gl.deleteShader(glFragShader);
      var uniformData = {};
      for (var i in program.uniformData) {
          var data = program.uniformData[i];
          uniformData[i] = {
              location: gl.getUniformLocation(webGLProgram, i),
              value: defaultValue(data.type, data.size),
          };
      }
      var glProgram = new GLProgram(webGLProgram, uniformData);
      return glProgram;
  }

  var UID$4 = 0;
  // default sync data so we don't create a new one each time!
  var defaultSyncData = { textureCount: 0, uboCount: 0 };
  /**
   * System plugin to the renderer to manage shaders.
   *
   * @memberof PIXI
   */
  var ShaderSystem = /** @class */ (function () {
      /** @param renderer - The renderer this System works for. */
      function ShaderSystem(renderer) {
          this.destroyed = false;
          this.renderer = renderer;
          // Validation check that this environment support `new Function`
          this.systemCheck();
          this.gl = null;
          this.shader = null;
          this.program = null;
          this.cache = {};
          this._uboCache = {};
          this.id = UID$4++;
      }
      /**
       * Overrideable function by `@pixi/unsafe-eval` to silence
       * throwing an error if platform doesn't support unsafe-evals.
       *
       * @private
       */
      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.');
          }
      };
      ShaderSystem.prototype.contextChange = function (gl) {
          this.gl = gl;
          this.reset();
      };
      /**
       * Changes the current shader to the one given in parameter.
       *
       * @param shader - the new shader
       * @param dontSync - false if the shader should automatically sync its uniforms.
       * @returns the glProgram that belongs to the shader.
       */
      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.generateProgram(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;
              defaultSyncData.uboCount = 0;
              this.syncUniformGroup(shader.uniformGroup, defaultSyncData);
          }
          return glProgram;
      };
      /**
       * Uploads the uniforms values to the currently bound shader.
       *
       * @param uniforms - the uniforms values that be applied to the current shader
       */
      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 */
      /**
       * 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
       */
      ShaderSystem.prototype.syncUniformGroup = function (group, syncData) {
          var glProgram = this.getGlProgram();
          if (!group.static || group.dirtyId !== glProgram.uniformDirtyGroups[group.id]) {
              glProgram.uniformDirtyGroups[group.id] = group.dirtyId;
              this.syncUniforms(group, glProgram, syncData);
          }
      };
      /**
       * Overrideable by the @pixi/unsafe-eval package to use static syncUniforms instead.
       */
      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);
      };
      ShaderSystem.prototype.createSyncGroups = function (group) {
          var id = this.getSignature(group, this.shader.program.uniformData, 'u');
          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];
      };
      /**
       * Syncs uniform buffers
       *
       * @param group - the uniform buffer group to sync
       * @param name - the name of the uniform buffer
       */
      ShaderSystem.prototype.syncUniformBufferGroup = function (group, name) {
          var glProgram = this.getGlProgram();
          if (!group.static || group.dirtyId !== 0 || !glProgram.uniformGroups[group.id]) {
              group.dirtyId = 0;
              var syncFunc = glProgram.uniformGroups[group.id]
                  || this.createSyncBufferGroup(group, glProgram, name);
              // TODO wrap update in a cache??
              group.buffer.update();
              syncFunc(glProgram.uniformData, group.uniforms, this.renderer, defaultSyncData, group.buffer);
          }
          this.renderer.buffer.bindBufferBase(group.buffer, glProgram.uniformBufferBindings[name]);
      };
      /**
       * Will create a function that uploads a uniform buffer using the STD140 standard.
       * The upload function will then be cached for future calls
       * If a group is manually managed, then a simple upload function is generated
       *
       * @param group - the uniform buffer group to sync
       * @param glProgram - the gl program to attach the uniform bindings to
       * @param name - the name of the uniform buffer (must exist on the shader)
       */
      ShaderSystem.prototype.createSyncBufferGroup = function (group, glProgram, name) {
          var gl = this.renderer.gl;
          this.renderer.buffer.bind(group.buffer);
          // bind them...
          var uniformBlockIndex = this.gl.getUniformBlockIndex(glProgram.program, name);
          glProgram.uniformBufferBindings[name] = this.shader.uniformBindCount;
          gl.uniformBlockBinding(glProgram.program, uniformBlockIndex, this.shader.uniformBindCount);
          this.shader.uniformBindCount++;
          var id = this.getSignature(group, this.shader.program.uniformData, 'ubo');
          var uboData = this._uboCache[id];
          if (!uboData) {
              uboData = this._uboCache[id] = generateUniformBufferSync(group, this.shader.program.uniformData);
          }
          if (group.autoManage) {
              var data = new Float32Array(uboData.size / 4);
              group.buffer.update(data);
          }
          glProgram.uniformGroups[group.id] = uboData.syncFunc;
          return glProgram.uniformGroups[group.id];
      };
      /**
       * Takes a uniform group and data and generates a unique signature for them.
       *
       * @param group - The uniform group to get signature of
       * @param uniformData - Uniform information generated by the shader
       * @returns Unique signature of the uniform group
       */
      ShaderSystem.prototype.getSignature = function (group, uniformData, preFix) {
          var uniforms = group.uniforms;
          var strings = [preFix + "-"];
          for (var i in uniforms) {
              strings.push(i);
              if (uniformData[i]) {
                  strings.push(uniformData[i].type);
              }
          }
          return strings.join('-');
      };
      /**
       * 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 The glProgram for the currently bound Shader for this context
       */
      ShaderSystem.prototype.getGlProgram = function () {
          if (this.shader) {
              return this.shader.program.glPrograms[this.renderer.CONTEXT_UID];
          }
          return null;
      };
      /**
       * Generates a glProgram version of the Shader provided.
       *
       * @param shader - The shader that the glProgram will be based on.
       * @return A shiny new glProgram!
       */
      ShaderSystem.prototype.generateProgram = function (shader) {
          var gl = this.gl;
          var program = shader.program;
          var glProgram = generateProgram(gl, program);
          program.glPrograms[this.renderer.CONTEXT_UID] = glProgram;
          return glProgram;
      };
      /** Resets ShaderSystem state, does not affect WebGL state. */
      ShaderSystem.prototype.reset = function () {
          this.program = null;
          this.shader = null;
      };
      /** Destroys this System and removes all its textures. */
      ShaderSystem.prototype.destroy = function () {
          this.renderer = null;
          // TODO implement destroy method for ShaderSystem
          this.destroyed = true;
      };
      return ShaderSystem;
  }());

  /**
   * 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[exports.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.ADD] = [gl.ONE, gl.ONE];
      array[exports.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.NONE] = [0, 0];
      // not-premultiplied blend modes
      array[exports.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE];
      array[exports.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
      // composite operations
      array[exports.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO];
      array[exports.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO];
      array[exports.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE];
      array[exports.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA];
      array[exports.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA];
      array[exports.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA];
      array[exports.BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA];
      // SUBTRACT from flash
      array[exports.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;
  var DEPTH_MASK$1 = 5;
  /**
   * System plugin to the renderer to manage WebGL state machines.
   *
   * @memberof PIXI
   */
  var StateSystem = /** @class */ (function () {
      function StateSystem() {
          this.gl = null;
          this.stateId = 0;
          this.polygonOffset = 0;
          this.blendMode = exports.BLEND_MODES.NONE;
          this._blendEq = false;
          // map functions for when we set state..
          this.map = [];
          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;
          this.map[DEPTH_MASK$1] = this.setDepthMask;
          this.checks = [];
          this.defaultState = new State();
          this.defaultState.blend = true;
      }
      StateSystem.prototype.contextChange = function (gl) {
          this.gl = gl;
          this.blendModes = mapWebGLBlendModesToPixi(gl);
          this.set(this.defaultState);
          this.reset();
      };
      /**
       * Sets the current state
       *
       * @param {*} state - The state to set.
       */
      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;
          }
          // 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);
          }
      };
      /**
       * Sets the state, when previous state is unknown.
       *
       * @param {*} state - The state to set
       */
      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)));
          }
          for (var i = 0; i < this.checks.length; i++) {
              this.checks[i](this, state);
          }
          this.stateId = state.data;
      };
      /**
       * Sets whether to enable or disable blending.
       *
       * @param value - Turn on or off WebGl blending.
       */
      StateSystem.prototype.setBlend = function (value) {
          this.updateCheck(StateSystem.checkBlendMode, value);
          this.gl[value ? 'enable' : 'disable'](this.gl.BLEND);
      };
      /**
       * Sets whether to enable or disable polygon offset fill.
       *
       * @param value - Turn on or off webgl polygon offset testing.
       */
      StateSystem.prototype.setOffset = function (value) {
          this.updateCheck(StateSystem.checkPolygonOffset, value);
          this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL);
      };
      /**
       * Sets whether to enable or disable depth test.
       *
       * @param value - Turn on or off webgl depth testing.
       */
      StateSystem.prototype.setDepthTest = function (value) {
          this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST);
      };
      /**
       * Sets whether to enable or disable depth mask.
       *
       * @param value - Turn on or off webgl depth mask.
       */
      StateSystem.prototype.setDepthMask = function (value) {
          this.gl.depthMask(value);
      };
      /**
       * Sets whether to enable or disable cull face.
       *
       * @param {boolean} value - Turn on or off webgl cull face.
       */
      StateSystem.prototype.setCullFace = function (value) {
          this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE);
      };
      /**
       * Sets the gl front face.
       *
       * @param {boolean} value - true is clockwise and false is counter-clockwise
       */
      StateSystem.prototype.setFrontFace = function (value) {
          this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']);
      };
      /**
       * Sets the blend mode.
       *
       * @param {number} value - The blend mode to set to.
       */
      StateSystem.prototype.setBlendMode = function (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]);
          }
          else if (this._blendEq) {
              this._blendEq = false;
              gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
          }
      };
      /**
       * Sets the polygon offset.
       *
       * @param {number} value - the polygon offset
       * @param {number} scale - the polygon offset scale
       */
      StateSystem.prototype.setPolygonOffset = function (value, scale) {
          this.gl.polygonOffset(value, scale);
      };
      // used
      /** Resets all the logic and disables the VAOs. */
      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);
      };
      /**
       * 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.
       *
       * @param func - the checking function to add or remove
       * @param value - should the check function be added or removed.
       */
      StateSystem.prototype.updateCheck = function (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);
          }
      };
      /**
       * A private little wrapper function that we call to check the blend mode.
       *
       * @param System - the System to perform the state check on
       * @param state - the state that the blendMode will pulled from
       */
      StateSystem.checkBlendMode = function (system, state) {
          system.setBlendMode(state.blendMode);
      };
      /**
       * A private little wrapper function that we call to check the polygon offset.
       *
       * @param System - the System to perform the state check on
       * @param state - the state that the blendMode will pulled from
       */
      StateSystem.checkPolygonOffset = function (system, state) {
          system.setPolygonOffset(1, state.polygonOffset);
      };
      /**
       * @ignore
       */
      StateSystem.prototype.destroy = function () {
          this.gl = null;
      };
      return StateSystem;
  }());

  /**
   * 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.
   *
   * @memberof PIXI
   */
  var TextureGCSystem = /** @class */ (function () {
      /** @param renderer - The renderer this System works for. */
      function TextureGCSystem(renderer) {
          this.renderer = renderer;
          this.count = 0;
          this.checkCount = 0;
          this.maxIdle = settings.GC_MAX_IDLE;
          this.checkCountMax = settings.GC_MAX_CHECK_COUNT;
          this.mode = settings.GC_MODE;
      }
      /**
       * 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
       */
      TextureGCSystem.prototype.postrender = function () {
          if (!this.renderer.renderingToScreen) {
              return;
          }
          this.count++;
          if (this.mode === exports.GC_MODES.MANUAL) {
              return;
          }
          this.checkCount++;
          if (this.checkCount > this.checkCountMax) {
              this.checkCount = 0;
              this.run();
          }
      };
      /**
       * 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
       */
      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;
          }
      };
      /**
       * 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.
       */
      TextureGCSystem.prototype.unload = function (displayObject) {
          var tm = this.renderer.texture;
          var texture = displayObject._texture;
          // only destroy non generated textures
          if (texture && !texture.framebuffer) {
              tm.destroyTexture(texture);
          }
          for (var i = displayObject.children.length - 1; i >= 0; i--) {
              this.unload(displayObject.children[i]);
          }
      };
      TextureGCSystem.prototype.destroy = function () {
          this.renderer = null;
      };
      return TextureGCSystem;
  }());

  /**
   * Returns a lookup table that maps each type-format pair to a compatible internal format.
   *
   * @memberof PIXI
   * @function mapTypeAndFormatToInternalFormat
   * @private
   * @param {WebGLRenderingContext} gl - The rendering context.
   * @return {{ [type: number]: { [format: number]: number } }} Lookup table.
   */
  function mapTypeAndFormatToInternalFormat(gl) {
      var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
      var table;
      if ('WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext) {
          table = (_a = {},
              _a[exports.TYPES.UNSIGNED_BYTE] = (_b = {},
                  _b[exports.FORMATS.RGBA] = gl.RGBA8,
                  _b[exports.FORMATS.RGB] = gl.RGB8,
                  _b[exports.FORMATS.RG] = gl.RG8,
                  _b[exports.FORMATS.RED] = gl.R8,
                  _b[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8UI,
                  _b[exports.FORMATS.RGB_INTEGER] = gl.RGB8UI,
                  _b[exports.FORMATS.RG_INTEGER] = gl.RG8UI,
                  _b[exports.FORMATS.RED_INTEGER] = gl.R8UI,
                  _b[exports.FORMATS.ALPHA] = gl.ALPHA,
                  _b[exports.FORMATS.LUMINANCE] = gl.LUMINANCE,
                  _b[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA,
                  _b),
              _a[exports.TYPES.BYTE] = (_c = {},
                  _c[exports.FORMATS.RGBA] = gl.RGBA8_SNORM,
                  _c[exports.FORMATS.RGB] = gl.RGB8_SNORM,
                  _c[exports.FORMATS.RG] = gl.RG8_SNORM,
                  _c[exports.FORMATS.RED] = gl.R8_SNORM,
                  _c[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8I,
                  _c[exports.FORMATS.RGB_INTEGER] = gl.RGB8I,
                  _c[exports.FORMATS.RG_INTEGER] = gl.RG8I,
                  _c[exports.FORMATS.RED_INTEGER] = gl.R8I,
                  _c),
              _a[exports.TYPES.UNSIGNED_SHORT] = (_d = {},
                  _d[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16UI,
                  _d[exports.FORMATS.RGB_INTEGER] = gl.RGB16UI,
                  _d[exports.FORMATS.RG_INTEGER] = gl.RG16UI,
                  _d[exports.FORMATS.RED_INTEGER] = gl.R16UI,
                  _d[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT16,
                  _d),
              _a[exports.TYPES.SHORT] = (_e = {},
                  _e[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16I,
                  _e[exports.FORMATS.RGB_INTEGER] = gl.RGB16I,
                  _e[exports.FORMATS.RG_INTEGER] = gl.RG16I,
                  _e[exports.FORMATS.RED_INTEGER] = gl.R16I,
                  _e),
              _a[exports.TYPES.UNSIGNED_INT] = (_f = {},
                  _f[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32UI,
                  _f[exports.FORMATS.RGB_INTEGER] = gl.RGB32UI,
                  _f[exports.FORMATS.RG_INTEGER] = gl.RG32UI,
                  _f[exports.FORMATS.RED_INTEGER] = gl.R32UI,
                  _f[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT24,
                  _f),
              _a[exports.TYPES.INT] = (_g = {},
                  _g[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32I,
                  _g[exports.FORMATS.RGB_INTEGER] = gl.RGB32I,
                  _g[exports.FORMATS.RG_INTEGER] = gl.RG32I,
                  _g[exports.FORMATS.RED_INTEGER] = gl.R32I,
                  _g),
              _a[exports.TYPES.FLOAT] = (_h = {},
                  _h[exports.FORMATS.RGBA] = gl.RGBA32F,
                  _h[exports.FORMATS.RGB] = gl.RGB32F,
                  _h[exports.FORMATS.RG] = gl.RG32F,
                  _h[exports.FORMATS.RED] = gl.R32F,
                  _h[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT32F,
                  _h),
              _a[exports.TYPES.HALF_FLOAT] = (_j = {},
                  _j[exports.FORMATS.RGBA] = gl.RGBA16F,
                  _j[exports.FORMATS.RGB] = gl.RGB16F,
                  _j[exports.FORMATS.RG] = gl.RG16F,
                  _j[exports.FORMATS.RED] = gl.R16F,
                  _j),
              _a[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_k = {},
                  _k[exports.FORMATS.RGB] = gl.RGB565,
                  _k),
              _a[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_l = {},
                  _l[exports.FORMATS.RGBA] = gl.RGBA4,
                  _l),
              _a[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_m = {},
                  _m[exports.FORMATS.RGBA] = gl.RGB5_A1,
                  _m),
              _a[exports.TYPES.UNSIGNED_INT_2_10_10_10_REV] = (_o = {},
                  _o[exports.FORMATS.RGBA] = gl.RGB10_A2,
                  _o[exports.FORMATS.RGBA_INTEGER] = gl.RGB10_A2UI,
                  _o),
              _a[exports.TYPES.UNSIGNED_INT_10F_11F_11F_REV] = (_p = {},
                  _p[exports.FORMATS.RGB] = gl.R11F_G11F_B10F,
                  _p),
              _a[exports.TYPES.UNSIGNED_INT_5_9_9_9_REV] = (_q = {},
                  _q[exports.FORMATS.RGB] = gl.RGB9_E5,
                  _q),
              _a[exports.TYPES.UNSIGNED_INT_24_8] = (_r = {},
                  _r[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH24_STENCIL8,
                  _r),
              _a[exports.TYPES.FLOAT_32_UNSIGNED_INT_24_8_REV] = (_s = {},
                  _s[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH32F_STENCIL8,
                  _s),
              _a);
      }
      else {
          table = (_t = {},
              _t[exports.TYPES.UNSIGNED_BYTE] = (_u = {},
                  _u[exports.FORMATS.RGBA] = gl.RGBA,
                  _u[exports.FORMATS.RGB] = gl.RGB,
                  _u[exports.FORMATS.ALPHA] = gl.ALPHA,
                  _u[exports.FORMATS.LUMINANCE] = gl.LUMINANCE,
                  _u[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA,
                  _u),
              _t[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_v = {},
                  _v[exports.FORMATS.RGB] = gl.RGB,
                  _v),
              _t[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_w = {},
                  _w[exports.FORMATS.RGBA] = gl.RGBA,
                  _w),
              _t[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_x = {},
                  _x[exports.FORMATS.RGBA] = gl.RGBA,
                  _x),
              _t);
      }
      return table;
  }

  /**
   * Internal texture for WebGL context.
   *
   * @memberof PIXI
   */
  var GLTexture = /** @class */ (function () {
      function GLTexture(texture) {
          this.texture = texture;
          this.width = -1;
          this.height = -1;
          this.dirtyId = -1;
          this.dirtyStyleId = -1;
          this.mipmap = false;
          this.wrapMode = 33071;
          this.type = exports.TYPES.UNSIGNED_BYTE;
          this.internalFormat = exports.FORMATS.RGBA;
          this.samplerType = 0;
      }
      return GLTexture;
  }());

  /**
   * System plugin to the renderer to manage textures.
   *
   * @memberof PIXI
   */
  var TextureSystem = /** @class */ (function () {
      /**
       * @param renderer - The renderer this system works for.
       */
      function TextureSystem(renderer) {
          this.renderer = renderer;
          // TODO set to max textures...
          this.boundTextures = [];
          this.currentLocation = -1;
          this.managedTextures = [];
          this._unknownBoundTextures = false;
          this.unknownTexture = new BaseTexture();
          this.hasIntegerTextures = false;
      }
      /** 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;
          this.internalFormats = mapTypeAndFormatToInternalFormat(gl);
          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 texture_ - Texture to bind
       * @param [location=0] - Location to bind at
       */
      TextureSystem.prototype.bind = function (texture, location) {
          if (location === void 0) { location = 0; }
          var gl = this.gl;
          texture = texture === null || texture === void 0 ? void 0 : texture.castToBaseTexture();
          // cannot bind partial texture
          // TODO: report a warning
          if (texture && texture.valid && !texture.parentTextureArray) {
              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.hasIntegerTextures = false;
          this.currentLocation = -1;
          for (var i = 0; i < this.boundTextures.length; i++) {
              this.boundTextures[i] = this.unknownTexture;
          }
      };
      /**
       * Unbind a texture.
       *
       * @param 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(texture.target, this.emptyTextures[texture.target].texture);
                  boundTextures[i] = null;
              }
          }
      };
      /**
       * Ensures that current boundTextures all have FLOAT sampler type,
       * see {@link PIXI.SAMPLER_TYPES} for explanation.
       *
       * @param maxTextures - number of locations to check
       */
      TextureSystem.prototype.ensureSamplerType = function (maxTextures) {
          var _a = this, boundTextures = _a.boundTextures, hasIntegerTextures = _a.hasIntegerTextures, CONTEXT_UID = _a.CONTEXT_UID;
          if (!hasIntegerTextures) {
              return;
          }
          for (var i = maxTextures - 1; i >= 0; --i) {
              var tex = boundTextures[i];
              if (tex) {
                  var glTexture = tex._glTextures[CONTEXT_UID];
                  if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) {
                      this.renderer.texture.unbind(tex);
                  }
              }
          }
      };
      /**
       * Initialize a texture
       *
       * @private
       * @param texture - Texture to initialize
       */
      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) {
          var _a, _b;
          glTexture.internalFormat = (_b = (_a = this.internalFormats[texture.type]) === null || _a === void 0 ? void 0 : _a[texture.format]) !== null && _b !== void 0 ? _b : texture.format;
          if (this.webGLVersion === 2 && texture.type === exports.TYPES.HALF_FLOAT) {
              // TYPES.HALF_FLOAT is WebGL1 HALF_FLOAT_OES
              // we have to convert it to WebGL HALF_FLOAT
              glTexture.type = this.gl.HALF_FLOAT;
          }
          else {
              glTexture.type = texture.type;
          }
      };
      /**
       * Update a texture
       *
       * @private
       * @param {PIXI.BaseTexture} texture - Texture to initialize
       */
      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)) {
              // texture is uploaded, dont do anything!
              if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) {
                  this.hasIntegerTextures = true;
              }
          }
          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 texture_ - the texture to destroy
       * @param [skipRemove=false] - Whether to skip removing the texture from the TextureManager.
       */
      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) {
                      removeItems(this.managedTextures, i, 1);
                  }
              }
          }
      };
      /**
       * Update texture style such as mipmap flag
       *
       * @private
       * @param {PIXI.BaseTexture} texture - Texture to update
       */
      TextureSystem.prototype.updateTextureStyle = function (texture) {
          var glTexture = texture._glTextures[this.CONTEXT_UID];
          if (!glTexture) {
              return;
          }
          if ((texture.mipmap === exports.MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) {
              glTexture.mipmap = false;
          }
          else {
              glTexture.mipmap = texture.mipmap >= 1;
          }
          if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) {
              glTexture.wrapMode = exports.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 texture - Texture to update
       * @param glTexture
       */
      TextureSystem.prototype.setStyle = function (texture, glTexture) {
          var gl = this.gl;
          if (glTexture.mipmap && texture.mipmap !== exports.MIPMAP_MODES.ON_MANUAL) {
              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 === exports.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 === exports.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 === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST);
          }
          gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST);
      };
      TextureSystem.prototype.destroy = function () {
          this.renderer = null;
      };
      return TextureSystem;
  }());



  var _systems = {
      __proto__: null,
      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$2 = new 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 = /** @class */ (function (_super) {
      __extends$2(AbstractRenderer, _super);
      /**
       * @param system - The name of the system this renderer is for.
       * @param [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.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property.
       *   If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the
       *   canvas needs to be opaque, possibly for performance reasons on some older devices.
       * @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=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
       * @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).
       * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
       */
      function AbstractRenderer(type, options) {
          if (type === void 0) { type = exports.RENDERER_TYPE.UNKNOWN; }
          var _this = _super.call(this) || this;
          // Add the default render options
          options = Object.assign({}, settings.RENDER_OPTIONS, options);
          /**
           * 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 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 PIXI.settings.RESOLUTION
           */
          _this.resolution = options.resolution || settings.RESOLUTION;
          /**
           * Pass-thru setting for the canvas' context `alpha` property. This is typically
           * not something you need to fiddle with. If you want transparency, use `backgroundAlpha`.
           *
           * @member {boolean}
           */
          _this.useContextAlpha = options.useContextAlpha;
          /**
           * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically.
           *
           * @member {boolean}
           */
          _this.autoDensity = !!options.autoDensity;
          /**
           * 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, A] array.
           *
           * @member {number[]}
           * @protected
           */
          _this._backgroundColorRgba = [0, 0, 0, 1];
          /**
           * The background color as a string.
           *
           * @member {string}
           * @protected
           */
          _this._backgroundColorString = '#000000';
          _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter
          _this.backgroundAlpha = options.backgroundAlpha;
          // @deprecated
          if (options.transparent !== undefined) {
              deprecation('6.0.0', 'Option transparent is deprecated, please use backgroundAlpha instead.');
              _this.useContextAlpha = options.transparent;
              _this.backgroundAlpha = options.transparent ? 0 : 1;
          }
          /**
           * 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;
      }
      /**
       * 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);
          }
      };
      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 as close as possible to the specified width and height.
       * Canvas dimensions are multiplied by resolution and rounded to the nearest integers.
       * The new canvas dimensions divided by the resolution become the new screen dimensions.
       *
       * @param desiredScreenWidth - The desired width of the screen.
       * @param desiredScreenHeight - The desired height of the screen.
       */
      AbstractRenderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) {
          this.view.width = Math.round(desiredScreenWidth * this.resolution);
          this.view.height = Math.round(desiredScreenHeight * this.resolution);
          var screenWidth = this.view.width / this.resolution;
          var screenHeight = this.view.height / this.resolution;
          this.screen.width = screenWidth;
          this.screen.height = screenHeight;
          if (this.autoDensity) {
              this.view.style.width = screenWidth + "px";
              this.view.style.height = screenHeight + "px";
          }
          /**
           * 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);
      };
      /**
       * @ignore
       */
      AbstractRenderer.prototype.generateTexture = function (displayObject, options, resolution, region) {
          if (options === void 0) { options = {}; }
          // @deprecated parameters spread, use options instead
          if (typeof options === 'number') {
              deprecation('6.1.0', 'generateTexture options (scaleMode, resolution, region) are now object options.');
              options = { scaleMode: options, resolution: resolution, region: region };
          }
          var manualRegion = options.region, textureOptions = __rest(options, ["region"]);
          region = manualRegion || 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(__assign({ width: region.width, height: region.height }, textureOptions));
          tempMatrix$2.tx = -region.x;
          tempMatrix$2.ty = -region.y;
          this.render(displayObject, {
              renderTexture: renderTexture,
              clear: false,
              transform: tempMatrix$2,
              skipUpdateTransform: !!displayObject.parent
          });
          return renderTexture;
      };
      /**
       * Removes everything from the renderer and optionally removes the Canvas DOM element.
       *
       * @param [removeView=false] - Removes the Canvas element from the DOM.
       */
      AbstractRenderer.prototype.destroy = function (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);
          }
          var thisAny = this;
          // null-ing all objects, that's a tradition!
          thisAny.plugins = null;
          thisAny.type = exports.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 = hex2string(value);
              hex2rgb(value, this._backgroundColorRgba);
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(AbstractRenderer.prototype, "backgroundAlpha", {
          /**
           * The background color alpha. Setting this to 0 will make the canvas transparent.
           *
           * @member {number}
           */
          get: function () {
              return this._backgroundColorRgba[3];
          },
          set: function (value) {
              this._backgroundColorRgba[3] = value;
          },
          enumerable: false,
          configurable: true
      });
      return AbstractRenderer;
  }(eventemitter3));

  var GLBuffer = /** @class */ (function () {
      function GLBuffer(buffer) {
          this.buffer = buffer || null;
          this.updateID = -1;
          this.byteLength = -1;
          this.refCount = 0;
      }
      return GLBuffer;
  }());

  /**
   * System plugin to the renderer to manage buffers.
   *
   * WebGL uses Buffers as a way to store objects to the GPU.
   * This system makes working with them a lot easier.
   *
   * Buffers are used in three main places in WebGL
   * - geometry information
   * - Uniform information (via uniform buffer objects - a WebGL 2 only feature)
   * - Transform feedback information. (WebGL 2 only feature)
   *
   * This system will handle the binding of buffers to the GPU as well as uploading
   * them. With this system, you never need to work directly with GPU buffers, but instead work with
   * the PIXI.Buffer class.
   *
   *
   * @class
   * @memberof PIXI
   */
  var BufferSystem = /** @class */ (function () {
      /**
       * @param {PIXI.Renderer} renderer - The renderer this System works for.
       */
      function BufferSystem(renderer) {
          this.renderer = renderer;
          this.managedBuffers = {};
          this.boundBufferBases = {};
      }
      /**
       * @ignore
       */
      BufferSystem.prototype.destroy = function () {
          this.renderer = null;
      };
      /**
       * Sets up the renderer context and necessary buffers.
       */
      BufferSystem.prototype.contextChange = function () {
          this.disposeAll(true);
          this.gl = this.renderer.gl;
          // TODO fill out...
          this.CONTEXT_UID = this.renderer.CONTEXT_UID;
      };
      /**
       * This binds specified buffer. On first run, it will create the webGL buffers for the context too
       *
       * @param buffer - the buffer to bind to the renderer
       */
      BufferSystem.prototype.bind = function (buffer) {
          var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
          var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer);
          gl.bindBuffer(buffer.type, glBuffer.buffer);
      };
      /**
       * Binds an uniform buffer to at the given index.
       *
       * A cache is used so a buffer will not be bound again if already bound.
       *
       * @param buffer - the buffer to bind
       * @param index - the base index to bind it to.
       */
      BufferSystem.prototype.bindBufferBase = function (buffer, index) {
          var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
          if (this.boundBufferBases[index] !== buffer) {
              var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer);
              this.boundBufferBases[index] = buffer;
              gl.bindBufferBase(gl.UNIFORM_BUFFER, index, glBuffer.buffer);
          }
      };
      /**
       * Binds a buffer whilst also binding its range.
       * This will make the buffer start from the offset supplied rather than 0 when it is read.
       *
       * @param buffer - the buffer to bind
       * @param index - the base index to bind at, defaults to 0
       * @param offset - the offset to bind at (this is blocks of 256). 0 = 0, 1 = 256, 2 = 512 etc
       */
      BufferSystem.prototype.bindBufferRange = function (buffer, index, offset) {
          var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
          offset = offset || 0;
          var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer);
          gl.bindBufferRange(gl.UNIFORM_BUFFER, index || 0, glBuffer.buffer, offset * 256, 256);
      };
      /**
       * Will ensure the data in the buffer is uploaded to the GPU.
       *
       * @param {PIXI.Buffer} buffer - the buffer to update
       */
      BufferSystem.prototype.update = function (buffer) {
          var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
          var glBuffer = buffer._glBuffers[CONTEXT_UID];
          if (buffer._updateID === glBuffer.updateID) {
              return;
          }
          glBuffer.updateID = buffer._updateID;
          gl.bindBuffer(buffer.type, glBuffer.buffer);
          if (glBuffer.byteLength >= buffer.data.byteLength) {
              // offset is always zero for now!
              gl.bufferSubData(buffer.type, 0, buffer.data);
          }
          else {
              var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW;
              glBuffer.byteLength = buffer.data.byteLength;
              gl.bufferData(buffer.type, buffer.data, drawType);
          }
      };
      /**
       * Disposes buffer
       * @param {PIXI.Buffer} buffer - buffer with data
       * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray
       */
      BufferSystem.prototype.dispose = function (buffer, contextLost) {
          if (!this.managedBuffers[buffer.id]) {
              return;
          }
          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];
      };
      /**
       * dispose all WebGL resources of all managed buffers
       * @param {boolean} [contextLost=false] - If context was lost, we suppress `gl.delete` calls
       */
      BufferSystem.prototype.disposeAll = function (contextLost) {
          var all = Object.keys(this.managedBuffers);
          for (var i = 0; i < all.length; i++) {
              this.dispose(this.managedBuffers[all[i]], contextLost);
          }
      };
      /**
       * creates and attaches a GLBuffer object tied to the current context.
       * @protected
       */
      BufferSystem.prototype.createGLBuffer = function (buffer) {
          var _a = this, CONTEXT_UID = _a.CONTEXT_UID, gl = _a.gl;
          buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer());
          this.managedBuffers[buffer.id] = buffer;
          buffer.disposeRunner.add(this);
          return buffer._glBuffers[CONTEXT_UID];
      };
      return BufferSystem;
  }());

  /**
   * 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!
   *
   * Renderer is composed of systems that manage specific tasks. The following systems are added by default
   * whenever you create a renderer:
   *
   * | System                               | Description                                                                   |
   * | ------------------------------------ | ----------------------------------------------------------------------------- |
   * | {@link PIXI.BatchSystem}             | This manages object renderers that defer rendering until a flush.             |
   * | {@link PIXI.ContextSystem}           | This manages the WebGL context and extensions.                                |
   * | {@link PIXI.EventSystem}             | This manages UI events.                                                       |
   * | {@link PIXI.FilterSystem}            | This manages the filtering pipeline for post-processing effects.              |
   * | {@link PIXI.FramebufferSystem}       | This manages framebuffers, which are used for offscreen rendering.            |
   * | {@link PIXI.GeometrySystem}          | This manages geometries & buffers, which are used to draw object meshes.      |
   * | {@link PIXI.MaskSystem}              | This manages masking operations.                                              |
   * | {@link PIXI.ProjectionSystem}        | This manages the `projectionMatrix`, used by shaders to get NDC coordinates.  |
   * | {@link PIXI.RenderTextureSystem}     | This manages render-textures, which are an abstraction over framebuffers.     |
   * | {@link PIXI.ScissorSystem}           | This handles scissor masking, and is used internally by {@link MaskSystem}    |
   * | {@link PIXI.ShaderSystem}            | This manages shaders, programs that run on the GPU to calculate 'em pixels.   |
   * | {@link PIXI.StateSystem}             | This manages the WebGL state variables like blend mode, depth testing, etc.   |
   * | {@link PIXI.StencilSystem}           | This handles stencil masking, and is used internally by {@link MaskSystem}    |
   * | {@link PIXI.TextureSystem}           | This manages textures and their resources on the GPU.                         |
   * | {@link PIXI.TextureGCSystem}         | This will automatically remove textures from the GPU if they are not used.    |
   *
   * The breadth of the API surface provided by the renderer is contained within these systems.
   *
   * @memberof PIXI
   */
  var Renderer = /** @class */ (function (_super) {
      __extends$2(Renderer, _super);
      /**
       * @param [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.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property.
       *   If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the
       *   canvas needs to be opaque, possibly for performance reasons on some older devices.
       * @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=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
       * @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 {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
       * @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.
       */
      function Renderer(options) {
          var _this = _super.call(this, exports.RENDERER_TYPE.WEBGL, options) || this;
          // the options will have been modified here in the super constructor with pixi's default settings..
          options = _this.options;
          _this.gl = null;
          _this.CONTEXT_UID = 0;
          _this.runners = {
              destroy: new Runner('destroy'),
              contextChange: new Runner('contextChange'),
              reset: new Runner('reset'),
              update: new Runner('update'),
              postrender: new Runner('postrender'),
              prerender: new Runner('prerender'),
              resize: new Runner('resize'),
          };
          _this.runners.contextChange.add(_this);
          _this.globalUniforms = new UniformGroup({
              projectionMatrix: new Matrix(),
          }, true);
          _this.addSystem(MaskSystem, 'mask')
              .addSystem(ContextSystem, 'context')
              .addSystem(StateSystem, 'state')
              .addSystem(ShaderSystem, 'shader')
              .addSystem(TextureSystem, 'texture')
              .addSystem(BufferSystem, 'buffer')
              .addSystem(GeometrySystem, 'geometry')
              .addSystem(FramebufferSystem, 'framebuffer')
              .addSystem(ScissorSystem, 'scissor')
              .addSystem(StencilSystem, 'stencil')
              .addSystem(ProjectionSystem, 'projection')
              .addSystem(TextureGCSystem, 'textureGC')
              .addSystem(FilterSystem, 'filter')
              .addSystem(RenderTextureSystem, 'renderTexture')
              .addSystem(BatchSystem, 'batch');
          _this.initPlugins(Renderer.__plugins);
          _this.multisample = undefined;
          /*
           * The options passed in to create a new WebGL context.
           */
          if (options.context) {
              _this.context.initFromContext(options.context);
          }
          else {
              _this.context.initFromOptions({
                  alpha: !!_this.useContextAlpha,
                  antialias: options.antialias,
                  premultipliedAlpha: _this.useContextAlpha && _this.useContextAlpha !== 'notMultiplied',
                  stencil: true,
                  preserveDrawingBuffer: options.preserveDrawingBuffer,
                  powerPreference: _this.options.powerPreference,
              });
          }
          _this.renderingToScreen = true;
          sayHello(_this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1');
          _this.resize(_this.options.width, _this.options.height);
          return _this;
      }
      /**
       * Create renderer if WebGL is available. Overrideable
       * by the **@pixi/canvas-renderer** package to allow fallback.
       * throws error if WebGL is not available.
       *
       * @private
       */
      Renderer.create = function (options) {
          if (isWebGLSupported()) {
              return new Renderer(options);
          }
          throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.');
      };
      Renderer.prototype.contextChange = function () {
          var gl = this.gl;
          var samples;
          if (this.context.webGLVersion === 1) {
              var framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
              gl.bindFramebuffer(gl.FRAMEBUFFER, null);
              samples = gl.getParameter(gl.SAMPLES);
              gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
          }
          else {
              var framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);
              gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
              samples = gl.getParameter(gl.SAMPLES);
              gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, framebuffer);
          }
          if (samples >= exports.MSAA_QUALITY.HIGH) {
              this.multisample = exports.MSAA_QUALITY.HIGH;
          }
          else if (samples >= exports.MSAA_QUALITY.MEDIUM) {
              this.multisample = exports.MSAA_QUALITY.MEDIUM;
          }
          else if (samples >= exports.MSAA_QUALITY.LOW) {
              this.multisample = exports.MSAA_QUALITY.LOW;
          }
          else {
              this.multisample = exports.MSAA_QUALITY.NONE;
          }
      };
      /**
       * Add a new system to the renderer.
       *
       * @param ClassRef - Class reference
       * @param 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 Return instance of renderer
       */
      Renderer.prototype.addSystem = function (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;
      };
      /**
       * @ignore
       */
      Renderer.prototype.render = function (displayObject, options) {
          var renderTexture;
          var clear;
          var transform;
          var skipUpdateTransform;
          if (options) {
              if (options instanceof RenderTexture) {
                  deprecation('6.0.0', 'Renderer#render arguments changed, use options instead.');
                  /* eslint-disable prefer-rest-params */
                  renderTexture = options;
                  clear = arguments[2];
                  transform = arguments[3];
                  skipUpdateTransform = arguments[4];
                  /* eslint-enable prefer-rest-params */
              }
              else {
                  renderTexture = options.renderTexture;
                  clear = options.clear;
                  transform = options.transform;
                  skipUpdateTransform = options.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;
          }
          if (!renderTexture) {
              this._lastObjectRendered = displayObject;
          }
          if (!skipUpdateTransform) {
              // update the scene graph
              var cacheParent = displayObject.enableTempParent();
              displayObject.updateTransform();
              displayObject.disableTempParent(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.emit();
          // reset transform after render
          this.projection.transform = null;
          this.emit('postrender');
      };
      /**
       * @override
       * @ignore
       */
      Renderer.prototype.generateTexture = function (displayObject, options, resolution, region) {
          if (options === void 0) { options = {}; }
          var renderTexture = _super.prototype.generateTexture.call(this, displayObject, options, resolution, region);
          this.framebuffer.blit();
          return renderTexture;
      };
      /**
       * Resizes the WebGL view to the specified width and height.
       *
       * @param desiredScreenWidth - The desired width of the screen.
       * @param desiredScreenHeight - The desired height of the screen.
       */
      Renderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) {
          _super.prototype.resize.call(this, desiredScreenWidth, desiredScreenHeight);
          this.runners.resize.emit(this.screen.height, this.screen.width);
      };
      /**
       * Resets the WebGL state so you can render things however you fancy!
       *
       * @return 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 [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;
      };
      Object.defineProperty(Renderer.prototype, "extract", {
          /**
           * Please use `plugins.extract` instead.
           * @member {PIXI.Extract} extract
           * @deprecated since 6.0.0
           * @readonly
           */
          get: function () {
              deprecation('6.0.0', 'Renderer#extract has been deprecated, please use Renderer#plugins.extract instead.');
              return this.plugins.extract;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Adds a plugin to the renderer.
       *
       * @param pluginName - The name of the plugin.
       * @param 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));

  /**
   * 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.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property.
   *   If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the
   *   canvas needs to be opaque, possibly for performance reasons on some older devices.
   * @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 {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
   * @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=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
   * @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
   */
  function autoDetectRenderer(options) {
      return Renderer.create(options);
  }

  var $defaultVertex = "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 $defaultFilterVertex = "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";

  /**
   * Default vertex shader
   * @memberof PIXI
   * @member {string} defaultVertex
   */
  /**
   * Default filter vertex shader
   * @memberof PIXI
   * @member {string} defaultFilterVertex
   */
  // NOTE: This black magic is so that @microsoft/api-extractor does not complain! This explicitly specifies the types
  // of defaultVertex, defaultFilterVertex.
  var defaultVertex$2 = $defaultVertex;
  var defaultFilterVertex = $defaultFilterVertex;

  /**
   * Use the ISystem interface instead.
   * @deprecated since 6.1.0
   * @memberof PIXI
   */
  var System = /** @class */ (function () {
      /**
       * @param renderer - Reference to Renderer
       */
      function System(renderer) {
          deprecation('6.1.0', 'System class is deprecated, implemement ISystem interface instead.');
          this.renderer = renderer;
      }
      /** Destroy and don't use after this. */
      System.prototype.destroy = function () {
          this.renderer = null;
      };
      return System;
  }());

  /**
   * Used by the batcher to draw batches.
   * Each one of these contains all information required to draw a bound geometry.
   *
   * @memberof PIXI
   */
  var BatchDrawCall = /** @class */ (function () {
      function BatchDrawCall() {
          this.texArray = null;
          this.blend = 0;
          this.type = exports.DRAW_MODES.TRIANGLES;
          this.start = 0;
          this.size = 0;
          this.data = null;
      }
      return BatchDrawCall;
  }());

  /**
   * Used by the batcher to build texture batches.
   * Holds list of textures and their respective locations.
   *
   * @memberof PIXI
   */
  var BatchTextureArray = /** @class */ (function () {
      function BatchTextureArray() {
          this.elements = [];
          this.ids = [];
          this.count = 0;
      }
      BatchTextureArray.prototype.clear = function () {
          for (var i = 0; i < this.count; i++) {
              this.elements[i] = null;
          }
          this.count = 0;
      };
      return BatchTextureArray;
  }());

  /**
   * Flexible wrapper around `ArrayBuffer` that also provides typed array views on demand.
   *
   * @memberof PIXI
   */
  var ViewableBuffer = /** @class */ (function () {
      function ViewableBuffer(sizeOrBuffer) {
          if (typeof sizeOrBuffer === 'number') {
              this.rawBinaryData = new ArrayBuffer(sizeOrBuffer);
          }
          else if (sizeOrBuffer instanceof Uint8Array) {
              this.rawBinaryData = sizeOrBuffer.buffer;
          }
          else {
              this.rawBinaryData = sizeOrBuffer;
          }
          this.uint32View = new Uint32Array(this.rawBinaryData);
          this.float32View = new Float32Array(this.rawBinaryData);
      }
      Object.defineProperty(ViewableBuffer.prototype, "int8View", {
          /** View on the raw binary data as a `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`. */
          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`. */
          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`. */
          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`. */
          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 type - One of `int8`, `uint8`, `int16`,
       *    `uint16`, `int32`, `uint32`, and `float32`.
       * @return - 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;
  }());

  /**
   * 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.
   *
   * @memberof PIXI
   */
  var AbstractBatchRenderer = /** @class */ (function (_super) {
      __extends$2(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;
          _this.shaderGenerator = null;
          _this.geometryClass = null;
          _this.vertexSize = null;
          _this.state = State.for2d();
          _this.size = settings.SPRITE_BATCH_SIZE * 4;
          _this._vertexCount = 0;
          _this._indexCount = 0;
          _this._bufferedElements = [];
          _this._bufferedTextures = [];
          _this._bufferSize = 0;
          _this._shader = null;
          _this._packedGeometries = [];
          _this._packedGeometryPoolSize = 2;
          _this._flushId = 0;
          _this._aBuffers = {};
          _this._iBuffers = {};
          _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;
      }
      /**
       * Handles the `contextChange` signal.
       *
       * It calculates `this.MAX_TEXTURES` and allocating the packed-geometry object pool.
       */
      AbstractBatchRenderer.prototype.contextChange = function () {
          var gl = this.renderer.gl;
          if (settings.PREFER_ENV === exports.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.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. */
      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;
          }
      };
      /**
       * Handles the `prerender` signal.
       *
       * It ensures that flushes start from the first geometry object again.
       */
      AbstractBatchRenderer.prototype.onPrerender = function () {
          this._flushId = 0;
      };
      /**
       * Buffers the "batchable" object. It need not be rendered immediately.
       *
       * @param {PIXI.DisplayObject} element - the element to render when
       *    using this renderer
       */
      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;
      };
      /** Populating drawcalls for rendering */
      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 = 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 */
      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.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.texture.ensureSamplerType(this.MAX_TEXTURES);
          this.renderer.shader.bind(this._shader);
          if (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);
      };
      /**
       * Fetches an attribute buffer from `this._aBuffers` that can hold atleast `size` floats.
       *
       * @param size - minimum capacity required
       * @return - buffer than can hold atleast `size` floats
       */
      AbstractBatchRenderer.prototype.getAttributeBuffer = function (size) {
          // 8 vertices is enough for 2 quads
          var roundedP2 = nextPow2(Math.ceil(size / 8));
          var roundedSizeIndex = 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;
      };
      /**
       * Fetches an index buffer from `this._iBuffers` that can
       * have at least `size` capacity.
       *
       * @param size - minimum required capacity
       * @return - buffer that can fit `size` indices.
       */
      AbstractBatchRenderer.prototype.getIndexBuffer = function (size) {
          // 12 indices is enough for 2 quads
          var roundedP2 = nextPow2(Math.ceil(size / 12));
          var roundedSizeIndex = 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;
      };
      /**
       * 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.DisplayObject} element - element being rendered
       * @param attributeBuffer - attribute buffer.
       * @param indexBuffer - index buffer
       * @param aIndex - number of floats already in the attribute buffer
       * @param iIndex - number of indices already in `indexBuffer`
       */
      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)
              ? 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.
       *
       * @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.
       *
       * @member {PIXI.BatchTextureArray[]}
       */
      AbstractBatchRenderer._textureArrayPool = [];
      return AbstractBatchRenderer;
  }(ObjectRenderer));

  /**
   * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer
   *
   * @memberof PIXI
   */
  var BatchShaderGenerator = /** @class */ (function () {
      /**
       * @param vertexSrc - Vertex shader
       * @param fragTemplate - Fragment shader template
       */
      function BatchShaderGenerator(vertexSrc, fragTemplate) {
          this.vertexSrc = vertexSrc;
          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 (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 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;
  }());

  /**
   * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects).
   *
   * @memberof PIXI
   */
  var BatchGeometry = /** @class */ (function (_super) {
      __extends$2(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;
          _this._buffer = new Buffer(null, _static, false);
          _this._indexBuffer = new Buffer(null, _static, true);
          _this.addAttribute('aVertexPosition', _this._buffer, 2, false, exports.TYPES.FLOAT)
              .addAttribute('aTextureCoord', _this._buffer, 2, false, exports.TYPES.FLOAT)
              .addAttribute('aColor', _this._buffer, 4, true, exports.TYPES.UNSIGNED_BYTE)
              .addAttribute('aTextureId', _this._buffer, 1, true, exports.TYPES.FLOAT)
              .addIndex(_this._indexBuffer);
          return _this;
      }
      return BatchGeometry;
  }(Geometry));

  var defaultVertex$3 = "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";

  /** @memberof PIXI */
  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';
       *
       * @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$3,
              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$2(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", {
          /**
           * The default vertex shader source
           *
           * @readonly
           */
          get: function () {
              return defaultVertex$3;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BatchPluginFactory, "defaultFragmentTemplate", {
          /**
           * The default fragment shader source
           *
           * @readonly
           */
          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();

  /**
   * @memberof PIXI
   * @namespace resources
   * @see PIXI
   * @deprecated since 6.0.0
   */
  var resources = {};
  var _loop_1 = function (name) {
      Object.defineProperty(resources, name, {
          get: function () {
              deprecation('6.0.0', "PIXI.systems." + name + " has moved to PIXI." + name);
              return _resources[name];
          },
      });
  };
  for (var name in _resources) {
      _loop_1(name);
  }
  /**
   * @memberof PIXI
   * @namespace systems
   * @see PIXI
   * @deprecated since 6.0.0
   */
  var systems = {};
  var _loop_2 = function (name) {
      Object.defineProperty(systems, name, {
          get: function () {
              deprecation('6.0.0', "PIXI.resources." + name + " has moved to PIXI." + name);
              return _systems[name];
          },
      });
  };
  for (var name in _systems) {
      _loop_2(name);
  }

  /*!
   * @pixi/app - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/app is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * 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.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property.
       *   If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the
       *   canvas needs to be opaque, possibly for performance reasons on some older devices.
       * @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=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
       * @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 {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
       * @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 root display container that's rendered.
           * @member {PIXI.Container}
           */
          this.stage = new Container();
          // The default options
          options = Object.assign({
              forceCanvas: false,
          }, options);
          this.renderer = autoDetectRenderer(options);
          // install plugins here
          Application._plugins.forEach(function (plugin) {
              plugin.init.call(_this, options);
          });
      }
      /**
       * Register a middleware plugin for the application
       * @static
       * @param {PIXI.IApplicationPlugin} plugin - Plugin being installed
       */
      Application.registerPlugin = function (plugin) {
          Application._plugins.push(plugin);
      };
      /**
       * Render the current stage.
       */
      Application.prototype.render = function () {
          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;
      };
      /** Collection of installed plugins. */
      Application._plugins = [];
      return Application;
  }());

  /**
   * 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;
          Object.defineProperty(this, 'resizeTo', 
          /**
           * The HTML element or window to automatically resize the
           * renderer's view element to match width and height.
           * @member {Window|HTMLElement}
           * @name resizeTo
           * @memberof PIXI.Application#
           */
          {
              set: function (dom) {
                  globalThis.removeEventListener('resize', this.queueResize);
                  this._resizeTo = dom;
                  if (dom) {
                      globalThis.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.
           *
           * @memberof PIXI.Application#
           * @method queueResize
           * @private
           */
          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.
           *
           * @memberof PIXI.Application#
           * @method 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.
           *
           * @memberof PIXI.Application#
           * @method resize
           */
          this.resize = function () {
              if (!_this._resizeTo) {
                  return;
              }
              // clear queue resize
              _this.cancelResize();
              var width;
              var height;
              // Resize to the window
              if (_this._resizeTo === globalThis.window) {
                  width = globalThis.innerWidth;
                  height = globalThis.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 () {
          globalThis.removeEventListener('resize', this.queueResize);
          this.cancelResize();
          this.cancelResize = null;
          this.queueResize = null;
          this.resizeTo = null;
          this.resize = null;
      };
      return ResizePlugin;
  }());

  Application.registerPlugin(ResizePlugin);

  /*!
   * @pixi/extract - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/extract is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  var TEMP_RECT = new Rectangle();
  var BYTES_PER_PIXEL = 4;
  /**
   * 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);
   *
   * @memberof PIXI
   */
  var Extract = /** @class */ (function () {
      /**
       * @param renderer - A reference to the current renderer
       */
      function Extract(renderer) {
          this.renderer = renderer;
      }
      /**
       * Will return a HTML Image of the target
       *
       * @param target - A displayObject or renderTexture
       *  to convert. If left empty will use the main renderer
       * @param format - Image format, e.g. "image/jpeg" or "image/webp".
       * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92.
       * @return - HTML Image of the target
       */
      Extract.prototype.image = function (target, format, quality) {
          var image = new Image();
          image.src = this.base64(target, format, quality);
          return image;
      };
      /**
       * Will return a base64 encoded string of this target. It works by calling
       *  `Extract.getCanvas` and then running toDataURL on that.
       *
       * @param target - A displayObject or renderTexture
       *  to convert. If left empty will use the main renderer
       * @param format - Image format, e.g. "image/jpeg" or "image/webp".
       * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92.
       * @return - A base64 encoded string of the texture.
       */
      Extract.prototype.base64 = function (target, format, quality) {
          return this.canvas(target).toDataURL(format, quality);
      };
      /**
       * Creates a Canvas element, renders this target to it and then returns it.
       *
       * @param target - A displayObject or renderTexture
       *  to convert. If left empty will use the main renderer
       * @return - A Canvas element with the texture rendered on.
       */
      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 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 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 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 target - A displayObject or renderTexture
       *  to convert. If left empty will use the main renderer
       * @return - 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 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;
      };
      /** Destroys the extract. */
      Extract.prototype.destroy = function () {
          this.renderer = null;
      };
      /**
       * Takes premultiplied pixel data and produces regular pixel data
       *
       * @private
       * @param pixels - array of pixel data
       * @param out - output array
       */
      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;
  }());

  /*!
   * @pixi/loaders - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/loaders is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /* jshint -W097 */
  /**
   * @memberof PIXI
   */
  var SignalBinding = /** @class */ (function () {
      /**
       * SignalBinding constructor.
       * @constructs SignalBinding
       * @param {Function} fn - Event handler to be called.
       * @param {Boolean} [once=false] - Should this listener be removed after dispatch
       * @param {object} [thisArg] - The context of the callback function.
       * @api private
       */
      // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
      function SignalBinding(fn, once, thisArg) {
          if (once === void 0) { once = false; }
          this._fn = fn;
          this._once = once;
          this._thisArg = thisArg;
          this._next = this._prev = this._owner = null;
      }
      SignalBinding.prototype.detach = function () {
          if (this._owner === null)
              { return false; }
          this._owner.detach(this);
          return true;
      };
      return SignalBinding;
  }());
  /**
   * @private
   */
  function _addSignalBinding(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;
  }
  /**
   * @memberof PIXI
   */
  var Signal = /** @class */ (function () {
      /**
       * MiniSignal constructor.
       * @example
       * let mySignal = new Signal();
       * let binding = mySignal.add(onSignal);
       * mySignal.dispatch('foo', 'bar');
       * mySignal.detach(binding);
       */
      function Signal() {
          this._head = this._tail = undefined;
      }
      /**
       * Return an array of attached SignalBinding.
       *
       * @param {Boolean} [exists=false] - We only need to know if there are handlers.
       * @returns {PIXI.SignalBinding[]|Boolean} Array of attached SignalBinding or Boolean if called with exists = true
       * @api public
       */
      Signal.prototype.handlers = function (exists) {
          if (exists === void 0) { exists = false; }
          var node = this._head;
          if (exists)
              { return !!node; }
          var ee = [];
          while (node) {
              ee.push(node);
              node = node._next;
          }
          return ee;
      };
      /**
       * Return true if node is a SignalBinding attached to this MiniSignal
       *
       * @param {PIXI.SignalBinding} node - Node to check.
       * @returns {Boolean} True if node is attache to mini-signal
       */
      Signal.prototype.has = function (node) {
          if (!(node instanceof SignalBinding)) {
              throw new Error('MiniSignal#has(): First arg must be a SignalBinding object.');
          }
          return node._owner === this;
      };
      /**
       * Dispaches a signal to all registered listeners.
       *
       * @returns {Boolean} Indication if we've emitted an event.
       */
      Signal.prototype.dispatch = function () {
          var arguments$1 = arguments;

          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments$1[_i];
          }
          var node = this._head;
          if (!node)
              { return false; }
          while (node) {
              if (node._once)
                  { this.detach(node); }
              node._fn.apply(node._thisArg, args);
              node = node._next;
          }
          return true;
      };
      /**
       * Register a new listener.
       *
       * @param {Function} fn - Callback function.
       * @param {object} [thisArg] - The context of the callback function.
       * @returns {PIXI.SignalBinding} The SignalBinding node that was added.
       */
      Signal.prototype.add = function (fn, thisArg) {
          if (thisArg === void 0) { thisArg = null; }
          if (typeof fn !== 'function') {
              throw new Error('MiniSignal#add(): First arg must be a Function.');
          }
          return _addSignalBinding(this, new SignalBinding(fn, false, thisArg));
      };
      /**
       * Register a new listener that will be executed only once.
       *
       * @param {Function} fn - Callback function.
       * @param {object} [thisArg] - The context of the callback function.
       * @returns {PIXI.SignalBinding} The SignalBinding node that was added.
       */
      Signal.prototype.once = function (fn, thisArg) {
          if (thisArg === void 0) { thisArg = null; }
          if (typeof fn !== 'function') {
              throw new Error('MiniSignal#once(): First arg must be a Function.');
          }
          return _addSignalBinding(this, new SignalBinding(fn, true, thisArg));
      };
      /**
       * Remove binding object.
       *
       * @param {PIXI.SignalBinding} node - The binding node that will be removed.
       * @returns {Signal} The instance on which this method was called.
       * @api public */
      Signal.prototype.detach = function (node) {
          if (!(node instanceof SignalBinding)) {
              throw new Error('MiniSignal#detach(): First arg must be a SignalBinding object.');
          }
          if (node._owner !== this)
              { return this; } // todo: or error?
          if (node._prev)
              { node._prev._next = node._next; }
          if (node._next)
              { node._next._prev = node._prev; }
          if (node === this._head) { // first node
              this._head = node._next;
              if (node._next === null) {
                  this._tail = null;
              }
          }
          else if (node === this._tail) { // last node
              this._tail = node._prev;
              this._tail._next = null;
          }
          node._owner = null;
          return this;
      };
      /**
       * Detach all listeners.
       *
       * @returns {Signal} The instance on which this method was called.
       */
      Signal.prototype.detachAll = function () {
          var node = this._head;
          if (!node)
              { return this; }
          this._head = this._tail = null;
          while (node) {
              node._owner = null;
              node = node._next;
          }
          return this;
      };
      return Signal;
  }());

  /**
   * function from npm package `parseUri`, converted to TS to avoid leftpad incident
   * @param {string} str
   * @param [opts] - options
   * @param {boolean} [opts.strictMode] - type of parser
   */
  function parseUri(str, opts) {
      opts = opts || {};
      var o = {
          // eslint-disable-next-line max-len
          key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'],
          q: {
              name: 'queryKey',
              parser: /(?:^|&)([^&=]*)=?([^&]*)/g
          },
          parser: {
              // eslint-disable-next-line max-len
              strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
              // eslint-disable-next-line max-len
              loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
          }
      };
      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 (_t0, t1, t2) {
          if (t1)
              { uri[o.q.name][t1] = t2; }
      });
      return uri;
  }

  // tests if CORS is supported in XHR, if not we need to use XDR
  var useXdr = !!(globalThis.XDomainRequest && !('withCredentials' in (new XMLHttpRequest())));
  var tempAnchor$1 = null;
  // some status constants
  var STATUS_NONE = 0;
  var STATUS_OK = 200;
  var STATUS_EMPTY = 204;
  var STATUS_IE_BUG_EMPTY = 1223;
  var STATUS_TYPE_OK = 2;
  // noop
  function _noop() { }
  /**
   * 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 map - The map to set on.
   * @param extname - The extension (or key) to set.
   * @param val - The value to set.
   */
  function setExtMap(map, extname, val) {
      if (extname && extname.indexOf('.') === 0) {
          extname = extname.substring(1);
      }
      if (!extname) {
          return;
      }
      map[extname] = val;
  }
  /**
   * Quick helper to get string xhr type.
   *
   * @ignore
   * @param xhr - The request to check.
   * @return The type.
   */
  function reqType(xhr) {
      return xhr.toString().replace('object ', '');
  }
  /**
   * Manages the state and loading of a resource and all child resources.
   *
   * Can be extended in `GlobalMixins.LoaderResource`.
   *
   * @memberof PIXI
   */
  exports.LoaderResource = /** @class */ (function () {
      /**
       * @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 {PIXI.LoaderResource.LOAD_TYPE} [options.loadType=LOAD_TYPE.XHR] - How should this resource
       *      be loaded?
       * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} [options.xhrType=XHR_RESPONSE_TYPE.DEFAULT] - How
       *      should the data being loaded be interpreted when using XHR?
       * @param {PIXI.LoaderResource.IMetadata} [options.metadata] - Extra configuration for middleware
       *      and the Resource object.
       */
      function LoaderResource(name, url, options) {
          /**
           * The `dequeue` method that will be used a storage place for the async queue dequeue method
           * used privately by the loader.
           *
           * @private
           * @member {function}
           */
          this._dequeue = _noop;
          /**
           * Used a storage place for the on load binding used privately by the loader.
           *
           * @private
           * @member {function}
           */
          this._onLoadBinding = null;
          /**
           * The timer for element loads to check if they timeout.
           *
           * @private
           */
          this._elementTimer = 0;
          /**
           * The `complete` function bound to this resource's context.
           *
           * @private
           * @type {function}
           */
          this._boundComplete = null;
          /**
           * The `_onError` function bound to this resource's context.
           *
           * @private
           * @type {function}
           */
          this._boundOnError = null;
          /**
           * The `_onProgress` function bound to this resource's context.
           *
           * @private
           * @type {function}
           */
          this._boundOnProgress = null;
          /**
           * The `_onTimeout` function bound to this resource's context.
           *
           * @private
           * @type {function}
           */
          this._boundOnTimeout = null;
          this._boundXhrOnError = null;
          this._boundXhrOnTimeout = null;
          this._boundXhrOnAbort = null;
          this._boundXhrOnLoad = null;
          if (typeof name !== 'string' || typeof url !== 'string') {
              throw new Error('Both name and url are required for constructing a resource.');
          }
          options = options || {};
          this._flags = 0;
          // set data url flag, needs to be set early for some _determineX checks to work.
          this._setFlag(LoaderResource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0);
          this.name = name;
          this.url = url;
          this.extension = this._getExtension();
          this.data = null;
          this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin;
          this.timeout = options.timeout || 0;
          this.loadType = options.loadType || this._determineLoadType();
          // The type used to load the resource via XHR. If unset, determined automatically.
          this.xhrType = options.xhrType;
          // 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.
          this.metadata = options.metadata || {};
          // The error that occurred while loading (if any).
          this.error = null;
          // The XHR object that was used to load this resource. This is only set
          // when `loadType` is `LoaderResource.LOAD_TYPE.XHR`.
          this.xhr = null;
          // The child resources this resource owns.
          this.children = [];
          // The resource type.
          this.type = LoaderResource.TYPE.UNKNOWN;
          // The progress chunk owned by this resource.
          this.progressChunk = 0;
          // The `dequeue` method that will be used a storage place for the async queue dequeue method
          // used privately by the loader.
          this._dequeue = _noop;
          // Used a storage place for the on load binding used privately by the loader.
          this._onLoadBinding = null;
          // The timer for element loads to check if they timeout.
          this._elementTimer = 0;
          this._boundComplete = this.complete.bind(this);
          this._boundOnError = this._onError.bind(this);
          this._boundOnProgress = this._onProgress.bind(this);
          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);
          // Dispatched when the resource beings to load.
          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.
          this.onProgress = new Signal();
          // Dispatched once this resource has loaded, if there was an error it will
          // be in the `error` property.
          this.onComplete = new Signal();
          // Dispatched after this resource has had all the *after* middleware run on it.
          this.onAfterMiddleware = new Signal();
      }
      /**
       * 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 {PIXI.LoaderResource.LOAD_TYPE} loadType - The load type to set it to.
       */
      LoaderResource.setExtensionLoadType = function (extname, loadType) {
          setExtMap(LoaderResource._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 {PIXI.LoaderResource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to.
       */
      LoaderResource.setExtensionXhrType = function (extname, xhrType) {
          setExtMap(LoaderResource._xhrTypeMap, extname, xhrType);
      };
      Object.defineProperty(LoaderResource.prototype, "isDataUrl", {
          /**
           * When the resource starts to load.
           *
           * @memberof PIXI.LoaderResource
           * @callback OnStartSignal
           * @param {Resource} resource - The resource that the event happened on.
           */
          /**
           * When the resource reports loading progress.
           *
           * @memberof PIXI.LoaderResource
           * @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].
           */
          /**
           * When the resource finishes loading.
           *
           * @memberof PIXI.LoaderResource
           * @callback OnCompleteSignal
           * @param {Resource} resource - The resource that the event happened on.
           */
          /**
           * @memberof PIXI.LoaderResource
           * @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.
           */
          /**
           * Stores whether or not this url is a data url.
           *
           * @readonly
           * @member {boolean}
           */
          get: function () {
              return this._hasFlag(LoaderResource.STATUS_FLAGS.DATA_URL);
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(LoaderResource.prototype, "isComplete", {
          /**
           * Describes if this resource has finished loading. Is true when the resource has completely
           * loaded.
           *
           * @readonly
           * @member {boolean}
           */
          get: function () {
              return this._hasFlag(LoaderResource.STATUS_FLAGS.COMPLETE);
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(LoaderResource.prototype, "isLoading", {
          /**
           * Describes if this resource is currently loading. Is true when the resource starts loading,
           * and is false again when complete.
           *
           * @readonly
           * @member {boolean}
           */
          get: function () {
              return this._hasFlag(LoaderResource.STATUS_FLAGS.LOADING);
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Marks the resource as complete.
       *
       */
      LoaderResource.prototype.complete = function () {
          this._clearEvents();
          this._finish();
      };
      /**
       * Aborts the loading of this resource, with an optional message.
       *
       * @param {string} message - The message to use for the error
       */
      LoaderResource.prototype.abort = function (message) {
          // abort can be called multiple times, ignore subsequent calls.
          if (this.error) {
              return;
          }
          // store error
          this.error = new Error(message);
          // clear events before calling aborts
          this._clearEvents();
          // abort the actual loading
          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 = LoaderResource.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 {PIXI.LoaderResource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded.
       */
      LoaderResource.prototype.load = function (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(LoaderResource.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 LoaderResource.LOAD_TYPE.IMAGE:
                  this.type = LoaderResource.TYPE.IMAGE;
                  this._loadElement('image');
                  break;
              case LoaderResource.LOAD_TYPE.AUDIO:
                  this.type = LoaderResource.TYPE.AUDIO;
                  this._loadSourceElement('audio');
                  break;
              case LoaderResource.LOAD_TYPE.VIDEO:
                  this.type = LoaderResource.TYPE.VIDEO;
                  this._loadSourceElement('video');
                  break;
              case LoaderResource.LOAD_TYPE.XHR:
              /* falls through */
              default:
                  if (useXdr && this.crossOrigin) {
                      this._loadXdr();
                  }
                  else {
                      this._loadXhr();
                  }
                  break;
          }
      };
      /**
       * Checks if the flag is set.
       *
       * @param flag - The flag to check.
       * @return True if the flag is set.
       */
      LoaderResource.prototype._hasFlag = function (flag) {
          return (this._flags & flag) !== 0;
      };
      /**
       * (Un)Sets the flag.
       *
       * @param flag - The flag to (un)set.
       * @param value - Whether to set or (un)set the flag.
       */
      LoaderResource.prototype._setFlag = function (flag, value) {
          this._flags = value ? (this._flags | flag) : (this._flags & ~flag);
      };
      /**
       * Clears all the events from the underlying loading source.
       */
      LoaderResource.prototype._clearEvents = function () {
          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);
          }
          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.
       */
      LoaderResource.prototype._finish = function () {
          if (this.isComplete) {
              throw new Error('Complete called again for an already completed resource.');
          }
          this._setFlag(LoaderResource.STATUS_FLAGS.COMPLETE, true);
          this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, false);
          this.onComplete.dispatch(this);
      };
      /**
       * Loads this resources using an element that has a single source,
       * like an HTMLImageElement.
       * @private
       * @param type - The type of element to use.
       */
      LoaderResource.prototype._loadElement = function (type) {
          if (this.metadata.loadElement) {
              this.data = this.metadata.loadElement;
          }
          else if (type === 'image' && typeof globalThis.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);
          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.
       * @param type - The type of element to use.
       */
      LoaderResource.prototype._loadSourceElement = function (type) {
          if (this.metadata.loadElement) {
              this.data = this.metadata.loadElement;
          }
          else if (type === 'audio' && typeof globalThis.Audio !== 'undefined') {
              this.data = new Audio();
          }
          else {
              this.data = document.createElement(type);
          }
          if (this.data === null) {
              this.abort("Unsupported element: " + type);
              return;
          }
          if (this.crossOrigin) {
              this.data.crossOrigin = this.crossOrigin;
          }
          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;
                  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));
              }
          }
          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);
          }
      };
      /**
       * Loads this resources using an XMLHttpRequest.
       */
      LoaderResource.prototype._loadXhr = function () {
          // if unset, determine the value
          if (typeof this.xhrType !== 'string') {
              this.xhrType = this._determineXhrType();
          }
          var xhr = this.xhr = new XMLHttpRequest();
          // send credentials when crossOrigin with credentials requested
          if (this.crossOrigin === 'use-credentials') {
              xhr.withCredentials = true;
          }
          // 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 === LoaderResource.XHR_RESPONSE_TYPE.JSON
              || this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) {
              xhr.responseType = LoaderResource.XHR_RESPONSE_TYPE.TEXT;
          }
          else {
              xhr.responseType = this.xhrType;
          }
          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).
       */
      LoaderResource.prototype._loadXdr = function () {
          // if unset, determine the value
          if (typeof this.xhrType !== 'string') {
              this.xhrType = this._determineXhrType();
          }
          var xdr = this.xhr = new globalThis.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
          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
          setTimeout(function () { return xdr.send(); }, 1);
      };
      /**
       * Creates a source used in loading via an element.
       * @param type - The element type (video or audio).
       * @param url - The source URL to load from.
       * @param [mime] - The mime type of the video
       * @return The source element.
       */
      LoaderResource.prototype._createSource = function (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 - The error event from the element that emits it.
       */
      LoaderResource.prototype._onError = function (event) {
          this.abort("Failed to load element using: " + event.target.nodeName);
      };
      /**
       * Called if a load progress event fires for an element or xhr/xdr.
       * @param event - Progress event.
       */
      LoaderResource.prototype._onProgress = function (event) {
          if (event && event.lengthComputable) {
              this.onProgress.dispatch(this, event.loaded / event.total);
          }
      };
      /**
       * Called if a timeout event fires for an element.
       */
      LoaderResource.prototype._onTimeout = function () {
          this.abort("Load timed out.");
      };
      /**
       * Called if an error event fires for xhr/xdr.
       */
      LoaderResource.prototype._xhrOnError = function () {
          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.
       */
      LoaderResource.prototype._xhrOnTimeout = function () {
          var xhr = this.xhr;
          this.abort(reqType(xhr) + " Request timed out.");
      };
      /**
       * Called if an abort event fires for xhr/xdr.
       */
      LoaderResource.prototype._xhrOnAbort = function () {
          var xhr = this.xhr;
          this.abort(reqType(xhr) + " Request was aborted by the user.");
      };
      /**
       * Called when data successfully loads from an xhr/xdr request.
       */
      LoaderResource.prototype._xhrOnLoad = function () {
          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 (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 (status === STATUS_NONE && (text.length > 0 || xhr.responseType === LoaderResource.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;
          }
          var statusType = (status / 100) | 0;
          if (statusType === STATUS_TYPE_OK) {
              // if text, just return it
              if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.TEXT) {
                  this.data = text;
                  this.type = LoaderResource.TYPE.TEXT;
              }
              // if json, parse into json object
              else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON) {
                  try {
                      this.data = JSON.parse(text);
                      this.type = LoaderResource.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 === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) {
                  try {
                      if (globalThis.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 = LoaderResource.TYPE.XML;
                  }
                  catch (e$1) {
                      this.abort("Error trying to parse loaded xml: " + e$1);
                      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 url - The url to test.
       * @param [loc=globalThis.location] - The location object to test against.
       * @return The crossOrigin value to use (or empty string for none).
       */
      // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
      LoaderResource.prototype._determineCrossOrigin = function (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 globalThis.location.origin, and will always require
          // crossOrigin requests regardless of whether the location matches.
          if (globalThis.origin !== globalThis.location.origin) {
              return 'anonymous';
          }
          // default is globalThis.location
          loc = loc || globalThis.location;
          if (!tempAnchor$1) {
              tempAnchor$1 = 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$1.href = url;
          var parsedUrl = parseUri(tempAnchor$1.href, { strictMode: true });
          var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port);
          var protocol = parsedUrl.protocol ? parsedUrl.protocol + ":" : '';
          // if cross origin
          if (parsedUrl.host !== loc.hostname || !samePort || protocol !== loc.protocol) {
              return 'anonymous';
          }
          return '';
      };
      /**
       * Determines the responseType of an XHR request based on the extension of the
       * resource being loaded.
       *
       * @private
       * @return {PIXI.LoaderResource.XHR_RESPONSE_TYPE} The responseType to use.
       */
      LoaderResource.prototype._determineXhrType = function () {
          return LoaderResource._xhrTypeMap[this.extension] || LoaderResource.XHR_RESPONSE_TYPE.TEXT;
      };
      /**
       * Determines the loadType of a resource based on the extension of the
       * resource being loaded.
       *
       * @private
       * @return {PIXI.LoaderResource.LOAD_TYPE} The loadType to use.
       */
      LoaderResource.prototype._determineLoadType = function () {
          return LoaderResource._loadTypeMap[this.extension] || LoaderResource.LOAD_TYPE.XHR;
      };
      /**
       * Extracts the extension (sans '.') of the file being loaded by the resource.
       *
       * @param [url] - url to parse, `this.url` by default.
       * @return The extension.
       */
      LoaderResource.prototype._getExtension = function (url) {
          if (url === void 0) { url = this.url; }
          var ext = '';
          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);
          }
          return ext.toLowerCase();
      };
      /**
       * Determines the mime type of an XHR request based on the responseType of
       * resource being loaded.
       *
       * @param type - The type to get a mime type for.
       * @private
       * @return The mime type to use.
       */
      LoaderResource.prototype._getMimeFromXhrType = function (type) {
          switch (type) {
              case LoaderResource.XHR_RESPONSE_TYPE.BUFFER:
                  return 'application/octet-binary';
              case LoaderResource.XHR_RESPONSE_TYPE.BLOB:
                  return 'application/blob';
              case LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT:
                  return 'application/xml';
              case LoaderResource.XHR_RESPONSE_TYPE.JSON:
                  return 'application/json';
              case LoaderResource.XHR_RESPONSE_TYPE.DEFAULT:
              case LoaderResource.XHR_RESPONSE_TYPE.TEXT:
              /* falls through */
              default:
                  return 'text/plain';
          }
      };
      return LoaderResource;
  }());
  // eslint-disable-next-line @typescript-eslint/no-namespace
  (function (LoaderResource) {
      /**
       * The types of resources a resource could represent.
       *
       * @static
       * @readonly
       * @enum {number}
       * @memberof PIXI.LoaderResource
       */
      var STATUS_FLAGS;
      (function (STATUS_FLAGS) {
          /** None */
          STATUS_FLAGS[STATUS_FLAGS["NONE"] = 0] = "NONE";
          /** Data URL */
          STATUS_FLAGS[STATUS_FLAGS["DATA_URL"] = 1] = "DATA_URL";
          /** Complete */
          STATUS_FLAGS[STATUS_FLAGS["COMPLETE"] = 2] = "COMPLETE";
          /** Loading */
          STATUS_FLAGS[STATUS_FLAGS["LOADING"] = 4] = "LOADING";
      })(STATUS_FLAGS = LoaderResource.STATUS_FLAGS || (LoaderResource.STATUS_FLAGS = {}));
      /**
       * The types of resources a resource could represent.
       *
       * @static
       * @readonly
       * @enum {number}
       * @memberof PIXI.LoaderResource
       */
      var TYPE;
      (function (TYPE) {
          /** Unknown */
          TYPE[TYPE["UNKNOWN"] = 0] = "UNKNOWN";
          /** JSON */
          TYPE[TYPE["JSON"] = 1] = "JSON";
          /** XML */
          TYPE[TYPE["XML"] = 2] = "XML";
          /** Image */
          TYPE[TYPE["IMAGE"] = 3] = "IMAGE";
          /** Audio */
          TYPE[TYPE["AUDIO"] = 4] = "AUDIO";
          /** Video */
          TYPE[TYPE["VIDEO"] = 5] = "VIDEO";
          /** Plain text */
          TYPE[TYPE["TEXT"] = 6] = "TEXT";
      })(TYPE = LoaderResource.TYPE || (LoaderResource.TYPE = {}));
      /**
       * The types of loading a resource can use.
       *
       * @static
       * @readonly
       * @enum {number}
       * @memberof PIXI.LoaderResource
       */
      var LOAD_TYPE;
      (function (LOAD_TYPE) {
          /** Uses XMLHttpRequest to load the resource. */
          LOAD_TYPE[LOAD_TYPE["XHR"] = 1] = "XHR";
          /** Uses an `Image` object to load the resource. */
          LOAD_TYPE[LOAD_TYPE["IMAGE"] = 2] = "IMAGE";
          /** Uses an `Audio` object to load the resource. */
          LOAD_TYPE[LOAD_TYPE["AUDIO"] = 3] = "AUDIO";
          /** Uses a `Video` object to load the resource. */
          LOAD_TYPE[LOAD_TYPE["VIDEO"] = 4] = "VIDEO";
      })(LOAD_TYPE = LoaderResource.LOAD_TYPE || (LoaderResource.LOAD_TYPE = {}));
      /**
       * The XHR ready states, used internally.
       *
       * @static
       * @readonly
       * @enum {string}
       * @memberof PIXI.LoaderResource
       */
      var XHR_RESPONSE_TYPE;
      (function (XHR_RESPONSE_TYPE) {
          /** string */
          XHR_RESPONSE_TYPE["DEFAULT"] = "text";
          /** ArrayBuffer */
          XHR_RESPONSE_TYPE["BUFFER"] = "arraybuffer";
          /** Blob */
          XHR_RESPONSE_TYPE["BLOB"] = "blob";
          /** Document */
          XHR_RESPONSE_TYPE["DOCUMENT"] = "document";
          /** Object */
          XHR_RESPONSE_TYPE["JSON"] = "json";
          /** String */
          XHR_RESPONSE_TYPE["TEXT"] = "text";
      })(XHR_RESPONSE_TYPE = LoaderResource.XHR_RESPONSE_TYPE || (LoaderResource.XHR_RESPONSE_TYPE = {}));
      LoaderResource._loadTypeMap = {
          // images
          gif: LoaderResource.LOAD_TYPE.IMAGE,
          png: LoaderResource.LOAD_TYPE.IMAGE,
          bmp: LoaderResource.LOAD_TYPE.IMAGE,
          jpg: LoaderResource.LOAD_TYPE.IMAGE,
          jpeg: LoaderResource.LOAD_TYPE.IMAGE,
          tif: LoaderResource.LOAD_TYPE.IMAGE,
          tiff: LoaderResource.LOAD_TYPE.IMAGE,
          webp: LoaderResource.LOAD_TYPE.IMAGE,
          tga: LoaderResource.LOAD_TYPE.IMAGE,
          svg: LoaderResource.LOAD_TYPE.IMAGE,
          'svg+xml': LoaderResource.LOAD_TYPE.IMAGE,
          // audio
          mp3: LoaderResource.LOAD_TYPE.AUDIO,
          ogg: LoaderResource.LOAD_TYPE.AUDIO,
          wav: LoaderResource.LOAD_TYPE.AUDIO,
          // videos
          mp4: LoaderResource.LOAD_TYPE.VIDEO,
          webm: LoaderResource.LOAD_TYPE.VIDEO,
      };
      LoaderResource._xhrTypeMap = {
          // xml
          xhtml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
          html: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
          htm: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
          xml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
          tmx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
          svg: LoaderResource.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: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
          // images
          gif: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
          png: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
          bmp: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
          jpg: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
          jpeg: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
          tif: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
          tiff: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
          webp: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
          tga: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
          // json
          json: LoaderResource.XHR_RESPONSE_TYPE.JSON,
          // text
          text: LoaderResource.XHR_RESPONSE_TYPE.TEXT,
          txt: LoaderResource.XHR_RESPONSE_TYPE.TEXT,
          // fonts
          ttf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER,
          otf: LoaderResource.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
      LoaderResource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
  })(exports.LoaderResource || (exports.LoaderResource = {}));

  /**
   * Smaller version of the async library constructs.
   * @ignore
   */
  function _noop$1() {
  }
  /**
   * Ensures a function is only called once.
   * @ignore
   * @param {function} fn - The function to wrap.
   * @return {function} The wrapping function.
   */
  function onlyOnce(fn) {
      return function onceWrapper() {
          var arguments$1 = arguments;

          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments$1[_i];
          }
          if (fn === null) {
              throw new Error('Callback was already called.');
          }
          var callFn = fn;
          fn = null;
          callFn.apply(this, args);
      };
  }
  /**
   * @private
   * @memberof PIXI
   */
  var AsyncQueueItem = /** @class */ (function () {
      /**
       * @private
       */
      function AsyncQueueItem(data, callback) {
          this.data = data;
          this.callback = callback;
      }
      return AsyncQueueItem;
  }());
  /**
   * @private
   * @memberof PIXI
   */
  var AsyncQueue = /** @class */ (function () {
      /**
       * @private
       */
      function AsyncQueue(worker, concurrency) {
          var _this = this;
          if (concurrency === void 0) { concurrency = 1; }
          this.workers = 0;
          this.saturated = _noop$1;
          this.unsaturated = _noop$1;
          this.empty = _noop$1;
          this.drain = _noop$1;
          this.error = _noop$1;
          this.started = false;
          this.paused = false;
          this._tasks = [];
          this._insert = function (data, insertAtFront, callback) {
              if (callback && typeof callback !== 'function') {
                  throw new Error('task callback must be a function');
              }
              _this.started = true;
              // eslint-disable-next-line no-eq-null,eqeqeq
              if (data == null && _this.idle()) {
                  // call drain immediately if there are no tasks
                  setTimeout(function () { return _this.drain(); }, 1);
                  return;
              }
              var item = new AsyncQueueItem(data, typeof callback === 'function' ? callback : _noop$1);
              if (insertAtFront) {
                  _this._tasks.unshift(item);
              }
              else {
                  _this._tasks.push(item);
              }
              setTimeout(_this.process, 1);
          };
          this.process = function () {
              while (!_this.paused && _this.workers < _this.concurrency && _this._tasks.length) {
                  var task = _this._tasks.shift();
                  if (_this._tasks.length === 0) {
                      _this.empty();
                  }
                  _this.workers += 1;
                  if (_this.workers === _this.concurrency) {
                      _this.saturated();
                  }
                  _this._worker(task.data, onlyOnce(_this._next(task)));
              }
          };
          this._worker = worker;
          if (concurrency === 0) {
              throw new Error('Concurrency must not be zero');
          }
          this.concurrency = concurrency;
          this.buffer = concurrency / 4.0;
      }
      /**
       * @private
       */
      AsyncQueue.prototype._next = function (task) {
          var _this = this;
          return function () {
              var arguments$1 = arguments;

              var args = [];
              for (var _i = 0; _i < arguments.length; _i++) {
                  args[_i] = arguments$1[_i];
              }
              _this.workers -= 1;
              task.callback.apply(task, args);
              // eslint-disable-next-line no-eq-null,eqeqeq
              if (args[0] != null) {
                  _this.error(args[0], task.data);
              }
              if (_this.workers <= (_this.concurrency - _this.buffer)) {
                  _this.unsaturated();
              }
              if (_this.idle()) {
                  _this.drain();
              }
              _this.process();
          };
      };
      // That was in object
      // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
      AsyncQueue.prototype.push = function (data, callback) {
          this._insert(data, false, callback);
      };
      AsyncQueue.prototype.kill = function () {
          this.workers = 0;
          this.drain = _noop$1;
          this.started = false;
          this._tasks = [];
      };
      // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
      AsyncQueue.prototype.unshift = function (data, callback) {
          this._insert(data, true, callback);
      };
      AsyncQueue.prototype.length = function () {
          return this._tasks.length;
      };
      AsyncQueue.prototype.running = function () {
          return this.workers;
      };
      AsyncQueue.prototype.idle = function () {
          return this._tasks.length + this.workers === 0;
      };
      AsyncQueue.prototype.pause = function () {
          if (this.paused === true) {
              return;
          }
          this.paused = true;
      };
      AsyncQueue.prototype.resume = function () {
          if (this.paused === false) {
              return;
          }
          this.paused = false;
          // Need to call this.process once per concurrent
          // worker to preserve full concurrency after pause
          for (var w = 1; w <= this.concurrency; w++) {
              this.process();
          }
      };
      /**
       * Iterates an array in series.
       *
       * @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.
       */
      AsyncQueue.eachSeries = function (array, iterator, callback, deferNext) {
          var i = 0;
          var len = array.length;
          function next(err) {
              if (err || i === len) {
                  if (callback) {
                      callback(err);
                  }
                  return;
              }
              if (deferNext) {
                  setTimeout(function () {
                      iterator(array[i++], next);
                  }, 1);
              }
              else {
                  iterator(array[i++], next);
              }
          }
          next();
      };
      /**
       * Async queue implementation,
       *
       * @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.
       */
      AsyncQueue.queue = function (worker, concurrency) {
          return new AsyncQueue(worker, concurrency);
      };
      return AsyncQueue;
  }());

  // some constants
  var MAX_PROGRESS = 100;
  var rgxExtractUrlHash = /(#[\w-]+)?$/;
  /**
   * The new loader, forked from Resource Loader by Chad Engler: https://github.com/englercj/resource-loader
   *
   * ```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 = {};
   *
   * // 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.
   * ```
   *
   * @memberof PIXI
   */
  var Loader = /** @class */ (function () {
      /**
       * @param baseUrl - The base url for all resources loaded by this loader.
       * @param concurrency - The number of resources to load concurrently.
       */
      function Loader(baseUrl, concurrency) {
          var _this = this;
          if (baseUrl === void 0) { baseUrl = ''; }
          if (concurrency === void 0) { concurrency = 10; }
          /**
           * The progress percent of the loader going through the queue.
           */
          this.progress = 0;
          /**
           * Loading state of the loader, true if it is currently loading resources.
           */
          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();
           */
          this.defaultQueryString = '';
          /**
           * The middleware to run before loading each resource.
           */
          this._beforeMiddleware = [];
          /**
           * The middleware to run after loading each resource.
           */
          this._afterMiddleware = [];
          /**
           * The tracks the resources we are currently completing parsing for.
           */
          this._resourcesParsing = [];
          /**
           * The `_loadResource` function bound with this object context.
           *
           * @param r - The resource to load
           * @param d - The dequeue function
           */
          this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); };
          /**
           * All the resources for this loader keyed by name.
           */
          this.resources = {};
          this.baseUrl = baseUrl;
          this._beforeMiddleware = [];
          this._afterMiddleware = [];
          this._resourcesParsing = [];
          this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); };
          this._queue = AsyncQueue.queue(this._boundLoadResource, concurrency);
          this._queue.pause();
          this.resources = {};
          this.onProgress = new Signal();
          this.onError = new Signal();
          this.onLoad = new Signal();
          this.onStart = new Signal();
          this.onComplete = new Signal();
          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);
              }
          }
          this._protected = false;
      }
      /**
       * Same as add, params have strict order
       *
       * @private
       * @param name - The name of the resource to load.
       * @param url - The url for this resource, relative to the baseUrl of this loader.
       * @param options - The options for the load.
       * @param callback - Function to call when this specific resource completes loading.
       * @return The loader itself.
       */
      Loader.prototype._add = function (name, url, options, callback) {
          // 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 exports.LoaderResource(name, url, options);
          if (typeof callback === 'function') {
              this.resources[name].onAfterMiddleware.once(callback);
          }
          // if actively loading, make sure to adjust progress chunks for that parent and its children
          if (this.loading) {
              var parent = options.parentResource;
              var incompleteChildren = [];
              for (var i = 0; i < parent.children.length; ++i) {
                  if (!parent.children[i].isComplete) {
                      incompleteChildren.push(parent.children[i]);
                  }
              }
              var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent
              var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child
              parent.children.push(this.resources[name]);
              parent.progressChunk = eachChunk;
              for (var i = 0; i < incompleteChildren.length; ++i) {
                  incompleteChildren[i].progressChunk = eachChunk;
              }
              this.resources[name].progressChunk = eachChunk;
          }
          // add the resource to the queue
          this._queue.push(this.resources[name]);
          return this;
      };
      /* eslint-enable require-jsdoc,valid-jsdoc */
      /**
       * Sets up a middleware function that will run *before* the
       * resource is loaded.
       *
       * @param fn - The middleware function to register.
       * @return The loader itself.
       */
      Loader.prototype.pre = function (fn) {
          this._beforeMiddleware.push(fn);
          return this;
      };
      /**
       * Sets up a middleware function that will run *after* the
       * resource is loaded.
       *
       * @param fn - The middleware function to register.
       * @return The loader itself.
       */
      Loader.prototype.use = function (fn) {
          this._afterMiddleware.push(fn);
          return this;
      };
      /**
       * Resets the queue of the loader to prepare for a new load.
       *
       * @return The loader itself.
       */
      Loader.prototype.reset = function () {
          this.progress = 0;
          this.loading = false;
          this._queue.kill();
          this._queue.pause();
          // abort all resource loads
          for (var k in this.resources) {
              var res = this.resources[k];
              if (res._onLoadBinding) {
                  res._onLoadBinding.detach();
              }
              if (res.isLoading) {
                  res.abort('loader reset');
              }
          }
          this.resources = {};
          return this;
      };
      /**
       * Starts loading the queued resources.
       * @param cb - Optional callback that will be bound to the `complete` event.
       * @return The loader itself.
       */
      Loader.prototype.load = function (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
          if (this.loading) {
              return this;
          }
          if (this._queue.idle()) {
              this._onStart();
              this._onComplete();
          }
          else {
              // distribute progress chunks
              var numTasks = this._queue._tasks.length;
              var chunk = MAX_PROGRESS / numTasks;
              for (var i = 0; i < this._queue._tasks.length; ++i) {
                  this._queue._tasks[i].data.progressChunk = chunk;
              }
              // notify we are starting
              this._onStart();
              // start loading
              this._queue.resume();
          }
          return this;
      };
      Object.defineProperty(Loader.prototype, "concurrency", {
          /**
           * The number of resources to load concurrently.
           *
           * @default 10
           */
          get: function () {
              return this._queue.concurrency;
          },
          set: function (concurrency) {
              this._queue.concurrency = concurrency;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Prepares a url for usage based on the configuration of this object
       * @param url - The url to prepare.
       * @return The prepared url.
       */
      Loader.prototype._prepareUrl = function (url) {
          var parsedUrl = parseUri(url, { strictMode: true });
          var result;
          // absolute url, just use it as is.
          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 (this.defaultQueryString) {
              var hash = rgxExtractUrlHash.exec(result)[0];
              result = result.slice(0, result.length - hash.length);
              if (result.indexOf('?') !== -1) {
                  result += "&" + this.defaultQueryString;
              }
              else {
                  result += "?" + this.defaultQueryString;
              }
              result += hash;
          }
          return result;
      };
      /**
       * Loads a single resource.
       *
       * @param resource - The resource to load.
       * @param dequeue - The function to call when we need to dequeue this item.
       */
      Loader.prototype._loadResource = function (resource, dequeue) {
          var _this = this;
          resource._dequeue = dequeue;
          // run before middleware
          AsyncQueue.eachSeries(this._beforeMiddleware, function (fn, next) {
              fn.call(_this, 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) {
                  _this._onLoad(resource);
              }
              else {
                  resource._onLoadBinding = resource.onComplete.once(_this._onLoad, _this);
                  resource.load();
              }
          }, true);
      };
      /**
       * Called once loading has started.
       */
      Loader.prototype._onStart = function () {
          this.progress = 0;
          this.loading = true;
          this.onStart.dispatch(this);
      };
      /**
       * Called once each resource has loaded.
       */
      Loader.prototype._onComplete = function () {
          this.progress = MAX_PROGRESS;
          this.loading = false;
          this.onComplete.dispatch(this, this.resources);
      };
      /**
       * Called each time a resources is loaded.
       * @param resource - The resource that was loaded
       */
      Loader.prototype._onLoad = function (resource) {
          var _this = this;
          resource._onLoadBinding = null;
          // remove this resource from the async queue, and add it to our list of resources that are being parsed
          this._resourcesParsing.push(resource);
          resource._dequeue();
          // run all the after middleware for this resource
          AsyncQueue.eachSeries(this._afterMiddleware, function (fn, next) {
              fn.call(_this, resource, next);
          }, function () {
              resource.onAfterMiddleware.dispatch(resource);
              _this.progress = Math.min(MAX_PROGRESS, _this.progress + resource.progressChunk);
              _this.onProgress.dispatch(_this, resource);
              if (resource.error) {
                  _this.onError.dispatch(resource.error, _this, resource);
              }
              else {
                  _this.onLoad.dispatch(_this, resource);
              }
              _this._resourcesParsing.splice(_this._resourcesParsing.indexOf(resource), 1);
              // do completion check
              if (_this._queue.idle() && _this._resourcesParsing.length === 0) {
                  _this._onComplete();
              }
          }, true);
      };
      /**
       * Destroy the loader, removes references.
       */
      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.
           */
          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.
       *
       * @param plugin - The plugin to add
       * @return Reference to PIXI.Loader for chaining
       */
      Loader.registerPlugin = function (plugin) {
          Loader._plugins.push(plugin);
          if (plugin.add) {
              plugin.add();
          }
          return Loader;
      };
      Loader._plugins = [];
      return Loader;
  }());
  Loader.prototype.add = function add(name, url, options, callback) {
      // 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]);
          }
          return this;
      }
      // if an object is passed instead of params
      if (typeof name === 'object') {
          options = name;
          callback = url || options.callback || options.onComplete;
          url = options.url;
          name = options.name || options.key || options.url;
      }
      // case where no name is passed shift all args over by one.
      if (typeof url !== 'string') {
          callback = options;
          options = url;
          url = name;
      }
      // now that we shifted make sure we have a proper 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
      if (typeof options === 'function') {
          callback = options;
          options = null;
      }
      return this._add(name, url, options, callback);
  };

  /**
   * 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);
   * @memberof PIXI
   */
  var AppLoaderPlugin = /** @class */ (function () {
      function AppLoaderPlugin() {
      }
      /**
       * Called on application constructor
       *
       * @private
       */
      AppLoaderPlugin.init = function (options) {
          options = Object.assign({
              sharedLoader: false,
          }, options);
          this.loader = options.sharedLoader ? Loader.shared : new Loader();
      };
      /**
       * Called when application destroyed
       *
       * @private
       */
      AppLoaderPlugin.destroy = function () {
          if (this.loader) {
              this.loader.destroy();
              this.loader = null;
          }
      };
      return AppLoaderPlugin;
  }());

  /**
   * Loader plugin for handling Texture resources.
   *
   * @memberof PIXI
   */
  var TextureLoader = /** @class */ (function () {
      function TextureLoader() {
      }
      /**
       * Handle SVG elements a text, render with SVGResource.
       */
      TextureLoader.add = function () {
          exports.LoaderResource.setExtensionLoadType('svg', exports.LoaderResource.LOAD_TYPE.XHR);
          exports.LoaderResource.setExtensionXhrType('svg', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT);
      };
      /**
       * Called after a resource is loaded.
       * @see PIXI.Loader.loaderMiddleware
       * @param resource
       * @param {function} next
       */
      TextureLoader.use = function (resource, next) {
          // create a new texture if the data is an Image object
          if (resource.data && (resource.type === exports.LoaderResource.TYPE.IMAGE || resource.extension === 'svg')) {
              var data = resource.data, url = resource.url, name = resource.name, metadata = resource.metadata;
              Texture.fromLoader(data, url, name, metadata).then(function (texture) {
                  resource.texture = texture;
                  next();
              })
                  // TODO: handle errors in Texture.fromLoader
                  // so we can pass them to the Loader
                  .catch(next);
          }
          else {
              next();
          }
      };
      return TextureLoader;
  }());

  var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  /**
   * Encodes binary into base64.
   *
   * @function encodeBinary
   * @param {string} input - The input data to encode.
   * @returns {string} The encoded base64 string
   */
  function encodeBinary(input) {
      var output = '';
      var inx = 0;
      while (inx < input.length) {
          // Fill byte buffer array
          var bytebuffer = [0, 0, 0];
          var encodedCharIndexes = [0, 0, 0, 0];
          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
          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)
          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)
          encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6);
          // index 3: forth 6 bits (6 least significant bits from input byte 3)
          encodedCharIndexes[3] = bytebuffer[2] & 0x3f;
          // Determine whether padding happened, and adjust accordingly
          var paddingBytes = inx - (input.length - 1);
          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;
          }
          // Now we will grab each appropriate character out of our keystring
          // based on our index array and append it to the output string
          for (var jnx = 0; jnx < encodedCharIndexes.length; ++jnx) {
              output += _keyStr.charAt(encodedCharIndexes[jnx]);
          }
      }
      return output;
  }

  var Url$1 = self.URL || self.webkitURL;
  /**
   * A middleware for transforming XHR loaded Blobs into more useful objects
   *
   * @ignore
   * @function parsing
   * @example
   * import { Loader, middleware } from 'resource-loader';
   * const loader = new Loader();
   * loader.use(middleware.parsing);
   * @param resource - Current Resource
   * @param 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 === exports.LoaderResource.XHR_RESPONSE_TYPE.BLOB) {
          // if there is no blob support we probably got a binary string back
          if (!self.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 = exports.LoaderResource.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
                  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_1 = Url$1.createObjectURL(resource.data);
              resource.blob = resource.data;
              resource.data = new Image();
              resource.data.src = src_1;
              resource.type = exports.LoaderResource.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$1.revokeObjectURL(src_1);
                  resource.data.onload = null;
                  next();
              };
              // next will be called on load.
              return;
          }
      }
      next();
  }

  // parse any blob into more usable objects (e.g. Image)
  Loader.registerPlugin({ use: parsing });
  // parse any Image objects into textures
  Loader.registerPlugin(TextureLoader);

  /*!
   * @pixi/compressed-textures - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/compressed-textures is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  var _a;
  /**
   * WebGL internal formats, including compressed texture formats provided by extensions
   *
   * @memberof PIXI
   * @static
   * @name INTERNAL_FORMATS
   * @enum {number}
   * @property {number} COMPRESSED_RGB_S3TC_DXT1_EXT=0x83F0
   * @property {number} COMPRESSED_RGBA_S3TC_DXT1_EXT=0x83F1
   * @property {number} COMPRESSED_RGBA_S3TC_DXT3_EXT=0x83F2
   * @property {number} COMPRESSED_RGBA_S3TC_DXT5_EXT=0x83F3
   * @property {number} COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917
   * @property {number} COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918
   * @property {number} COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919
   * @property {number} COMPRESSED_SRGB_S3TC_DXT1_EXT=35916
   * @property {number} COMPRESSED_R11_EAC=0x9270
   * @property {number} COMPRESSED_SIGNED_R11_EAC=0x9271
   * @property {number} COMPRESSED_RG11_EAC=0x9272
   * @property {number} COMPRESSED_SIGNED_RG11_EAC=0x9273
   * @property {number} COMPRESSED_RGB8_ETC2=0x9274
   * @property {number} COMPRESSED_RGBA8_ETC2_EAC=0x9278
   * @property {number} COMPRESSED_SRGB8_ETC2=0x9275
   * @property {number} COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=0x9279
   * @property {number} COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9276
   * @property {number} COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9277
   * @property {number} COMPRESSED_RGB_PVRTC_4BPPV1_IMG=0x8C00
   * @property {number} COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=0x8C02
   * @property {number} COMPRESSED_RGB_PVRTC_2BPPV1_IMG=0x8C01
   * @property {number} COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=0x8C03
   * @property {number} COMPRESSED_RGB_ETC1_WEBGL=0x8D64
   * @property {number} COMPRESSED_RGB_ATC_WEBGL=0x8C92
   * @property {number} COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=0x8C92
   * @property {number} COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=0x87EE
   */

  (function (INTERNAL_FORMATS) {
      // WEBGL_compressed_texture_s3tc
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT";
      // WEBGL_compressed_texture_s3tc_srgb
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT";
      // WEBGL_compressed_texture_etc
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2";
      // WEBGL_compressed_texture_pvrtc
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG";
      // WEBGL_compressed_texture_etc1
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL";
      // WEBGL_compressed_texture_atc
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ATC_WEBGL"] = 35986] = "COMPRESSED_RGB_ATC_WEBGL";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"] = 35986] = "COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL";
      INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"] = 34798] = "COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL";
  })(exports.INTERNAL_FORMATS || (exports.INTERNAL_FORMATS = {}));
  /**
   * Maps the compressed texture formats in {@link PIXI.INTERNAL_FORMATS} to the number of bytes taken by
   * each texel.
   *
   * @memberof PIXI
   * @static
   * @ignore
   */
  var INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = (_a = {},
      // WEBGL_compressed_texture_s3tc
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1,
      // WEBGL_compressed_texture_s3tc
      _a[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_S3TC_DXT1_EXT] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT] = 1,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT] = 1,
      // WEBGL_compressed_texture_etc
      _a[exports.INTERNAL_FORMATS.COMPRESSED_R11_EAC] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_R11_EAC] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RG11_EAC] = 1,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_RG11_EAC] = 1,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_ETC2] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGBA8_ETC2_EAC] = 1,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ETC2] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC] = 1,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5,
      // WEBGL_compressed_texture_pvrtc
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25,
      // WEBGL_compressed_texture_etc1
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ETC1_WEBGL] = 0.5,
      // @see https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_compressed_ATC_texture.txt
      // WEBGL_compressed_texture_atc
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ATC_WEBGL] = 0.5,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1,
      _a[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1,
      _a);

  /*! *****************************************************************************
  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$3 = function(d, b) {
      extendStatics$3 = 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$3(d, b);
  };

  function __extends$3(d, b) {
      extendStatics$3(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  function __awaiter(thisArg, _arguments, P, generator) {
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  }

  function __generator(thisArg, body) {
      var _ = { label: 0, sent: function() { if (t[0] & 1) { throw t[1]; } return t[1]; }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
      function verb(n) { return function (v) { return step([n, v]); }; }
      function step(op) {
          if (f) { throw new TypeError("Generator is already executing."); }
          while (_) { try {
              if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) { return t; }
              if (y = 0, t) { op = [op[0] & 2, t.value]; }
              switch (op[0]) {
                  case 0: case 1: t = op; break;
                  case 4: _.label++; return { value: op[1], done: false };
                  case 5: _.label++; y = op[1]; op = [0]; continue;
                  case 7: op = _.ops.pop(); _.trys.pop(); continue;
                  default:
                      if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                      if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                      if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                      if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                      if (t[2]) { _.ops.pop(); }
                      _.trys.pop(); continue;
              }
              op = body.call(thisArg, _);
          } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } }
          if (op[0] & 5) { throw op[1]; } return { value: op[0] ? op[1] : void 0, done: true };
      }
  }

  /**
   * Resource that fetches texture data over the network and stores it in a buffer.
   *
   * @class
   * @extends PIXI.Resource
   * @memberof PIXI
   */
  var BlobResource = /** @class */ (function (_super) {
      __extends$3(BlobResource, _super);
      /**
       * @param {string} url - the URL of the texture file
       * @param {boolean}[autoLoad] - whether to fetch the data immediately;
       *  you can fetch it later via {@link BlobResource#load}
       */
      function BlobResource(source, options) {
          if (options === void 0) { options = { width: 1, height: 1, autoLoad: true }; }
          var _this = this;
          var origin;
          var data;
          if (typeof source === 'string') {
              origin = source;
              data = new Uint8Array();
          }
          else {
              origin = null;
              data = source;
          }
          _this = _super.call(this, data, options) || this;
          /**
           * The URL of the texture file
           * @member {string}
           */
          _this.origin = origin;
          /**
           * The viewable buffer on the data
           * @member {ViewableBuffer}
           */
          // HINT: BlobResource allows "null" sources, assuming the child class provides an alternative
          _this.buffer = data ? new ViewableBuffer(data) : null;
          // Allow autoLoad = "undefined" still load the resource by default
          if (_this.origin && options.autoLoad !== false) {
              _this.load();
          }
          if (data && data.length) {
              _this.loaded = true;
              _this.onBlobLoaded(_this.buffer.rawBinaryData);
          }
          return _this;
      }
      BlobResource.prototype.onBlobLoaded = function (_data) {
          // TODO: Override this method
      };
      /**
       * Loads the blob
       */
      BlobResource.prototype.load = function () {
          return __awaiter(this, void 0, Promise, function () {
              var response, blob, arrayBuffer;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, fetch(this.origin)];
                      case 1:
                          response = _a.sent();
                          return [4 /*yield*/, response.blob()];
                      case 2:
                          blob = _a.sent();
                          return [4 /*yield*/, blob.arrayBuffer()];
                      case 3:
                          arrayBuffer = _a.sent();
                          this.data = new Uint32Array(arrayBuffer);
                          this.buffer = new ViewableBuffer(arrayBuffer);
                          this.loaded = true;
                          this.onBlobLoaded(arrayBuffer);
                          this.update();
                          return [2 /*return*/, this];
                  }
              });
          });
      };
      return BlobResource;
  }(BufferResource));

  /**
   * Resource for compressed texture formats, as follows: S3TC/DXTn (& their sRGB formats), ATC, ASTC, ETC 1/2, PVRTC.
   *
   * Compressed textures improve performance when rendering is texture-bound. The texture data stays compressed in
   * graphics memory, increasing memory locality and speeding up texture fetches. These formats can also be used to store
   * more detail in the same amount of memory.
   *
   * For most developers, container file formats are a better abstraction instead of directly handling raw texture
   * data. PixiJS provides native support for the following texture file formats (via {@link PIXI.Loader}):
   *
   * * **.dds** - the DirectDraw Surface file format stores DXTn (DXT-1,3,5) data. See {@link PIXI.DDSLoader}
   * * **.ktx** - the Khronos Texture Container file format supports storing all the supported WebGL compression formats.
   *  See {@link PIXI.KTXLoader}.
   * * **.basis** - the BASIS supercompressed file format stores texture data in an internal format that is transcoded
   *  to the compression format supported on the device at _runtime_. It also supports transcoding into a uncompressed
   *  format as a fallback; you must install the `@pixi/basis-loader`, `@pixi/basis-transcoder` packages separately to
   *  use these files. See {@link PIXI.BasisLoader}.
   *
   * The loaders for the aforementioned formats use `CompressedTextureResource` internally. It is strongly suggested that
   * they be used instead.
   *
   * ## Working directly with CompressedTextureResource
   *
   * Since `CompressedTextureResource` inherits `BlobResource`, you can provide it a URL pointing to a file containing
   * the raw texture data (with no file headers!):
   *
   * ```js
   * // The resource backing the texture data for your textures.
   * // NOTE: You can also provide a ArrayBufferView instead of a URL. This is used when loading data from a container file
   * //   format such as KTX, DDS, or BASIS.
   * const compressedResource = new PIXI.CompressedTextureResource("bunny.dxt5", {
   *   format: PIXI.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
   *   width: 256,
   *   height: 256
   * });
   *
   * // You can create a base-texture to the cache, so that future `Texture`s can be created using the `Texture.from` API.
   * const baseTexture = new PIXI.BaseTexture(compressedResource, { pmaMode: PIXI.ALPHA_MODES.NPM });
   *
   * // Create a Texture to add to the TextureCache
   * const texture = new PIXI.Texture(baseTexture);
   *
   * // Add baseTexture & texture to the global texture cache
   * PIXI.BaseTexture.addToCache(baseTexture, "bunny.dxt5");
   * PIXI.Texture.addToCache(texture, "bunny.dxt5");
   * ```
   *
   * @memberof PIXI
   */
  var CompressedTextureResource = /** @class */ (function (_super) {
      __extends$3(CompressedTextureResource, _super);
      /**
       * @param source - the buffer/URL holding the compressed texture data
       * @param options
       * @param {PIXI.INTERNAL_FORMATS} options.format - the compression format
       * @param {number} options.width - the image width in pixels.
       * @param {number} options.height - the image height in pixels.
       * @param {number} [options.level=1] - the mipmap levels stored in the compressed texture, including level 0.
       * @param {number} [options.levelBuffers] - the buffers for each mipmap level. `CompressedTextureResource` can allows you
       *      to pass `null` for `source`, for cases where each level is stored in non-contiguous memory.
       */
      function CompressedTextureResource(source, options) {
          var _this = _super.call(this, source, options) || this;
          _this.format = options.format;
          _this.levels = options.levels || 1;
          _this._width = options.width;
          _this._height = options.height;
          _this._extension = CompressedTextureResource._formatToExtension(_this.format);
          if (options.levelBuffers || _this.buffer) {
              // ViewableBuffer doesn't support byteOffset :-( so allow source to be Uint8Array
              _this._levelBuffers = options.levelBuffers
                  || CompressedTextureResource._createLevelBuffers(source instanceof Uint8Array ? source : _this.buffer.uint8View, _this.format, _this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode
                  _this.width, _this.height);
          }
          return _this;
      }
      /**
       * @override
       * @param renderer - A reference to the current renderer
       * @param _texture - the texture
       * @param _glTexture - texture instance for this webgl context
       */
      CompressedTextureResource.prototype.upload = function (renderer, _texture, _glTexture) {
          var gl = renderer.gl;
          var extension = renderer.context.extensions[this._extension];
          if (!extension) {
              throw new Error(this._extension + " textures are not supported on the current machine");
          }
          if (!this._levelBuffers) {
              // Do not try to upload data before BlobResource loads, unless the levelBuffers were provided directly!
              return false;
          }
          for (var i = 0, j = this.levels; i < j; i++) {
              var _a = this._levelBuffers[i], levelID = _a.levelID, levelWidth = _a.levelWidth, levelHeight = _a.levelHeight, levelBuffer = _a.levelBuffer;
              gl.compressedTexImage2D(gl.TEXTURE_2D, levelID, this.format, levelWidth, levelHeight, 0, levelBuffer);
          }
          return true;
      };
      /** @protected */
      CompressedTextureResource.prototype.onBlobLoaded = function () {
          this._levelBuffers = CompressedTextureResource._createLevelBuffers(this.buffer.uint8View, this.format, this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode
          this.width, this.height);
      };
      /**
       * Returns the key (to ContextSystem#extensions) for the WebGL extension supporting the compression format
       *
       * @private
       * @param format - the compression format to get the extension for.
       */
      CompressedTextureResource._formatToExtension = function (format) {
          if (format >= 0x83F0 && format <= 0x83F3) {
              return 's3tc';
          }
          else if (format >= 0x9270 && format <= 0x9279) {
              return 'etc';
          }
          else if (format >= 0x8C00 && format <= 0x8C03) {
              return 'pvrtc';
          }
          else if (format >= 0x8D64) {
              return 'etc1';
          }
          else if (format >= 0x8C92 && format <= 0x87EE) {
              return 'atc';
          }
          throw new Error('Invalid (compressed) texture format given!');
      };
      /**
       * Pre-creates buffer views for each mipmap level
       *
       * @private
       * @param buffer -
       * @param format - compression formats
       * @param levels - mipmap levels
       * @param blockWidth -
       * @param blockHeight -
       * @param imageWidth - width of the image in pixels
       * @param imageHeight - height of the image in pixels
       */
      CompressedTextureResource._createLevelBuffers = function (buffer, format, levels, blockWidth, blockHeight, imageWidth, imageHeight) {
          // The byte-size of the first level buffer
          var buffers = new Array(levels);
          var offset = buffer.byteOffset;
          var levelWidth = imageWidth;
          var levelHeight = imageHeight;
          var alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1);
          var alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1);
          var levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format];
          for (var i = 0; i < levels; i++) {
              buffers[i] = {
                  levelID: i,
                  levelWidth: levels > 1 ? levelWidth : alignedLevelWidth,
                  levelHeight: levels > 1 ? levelHeight : alignedLevelHeight,
                  levelBuffer: new Uint8Array(buffer.buffer, offset, levelSize)
              };
              offset += levelSize;
              // Calculate levelBuffer dimensions for next iteration
              levelWidth = (levelWidth >> 1) || 1;
              levelHeight = (levelHeight >> 1) || 1;
              alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1);
              alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1);
              levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format];
          }
          return buffers;
      };
      return CompressedTextureResource;
  }(BlobResource));

  /* eslint-enable camelcase */
  /**
   * Loader plugin for handling compressed textures for all platforms.
   *
   * @class
   * @memberof PIXI
   * @implements PIXI.ILoaderPlugin
   */
  var CompressedTextureLoader = /** @class */ (function () {
      function CompressedTextureLoader() {
      }
      /**
       * Called after a compressed-textures manifest is loaded.
       *
       * This will then load the correct compression format for the device. Your manifest should adhere
       * to the following schema:
       *
       * ```js
       * import { INTERNAL_FORMATS } from '@pixi/constants';
       *
       * type CompressedTextureManifest = {
       *  textures: Array<{ src: string, format?: keyof INTERNAL_FORMATS}>,
       *  cacheID: string;
       * };
       * ```
       *
       * This is an example of a .json manifest file
       *
       * ```json
       * {
       *   "cacheID":"asset",
       *   "textures":[
       *     { "src":"asset.fallback.png" },
       *     { "format":"COMPRESSED_RGBA_S3TC_DXT5_EXT", "src":"asset.s3tc.ktx" },
       *     { "format":"COMPRESSED_RGBA8_ETC2_EAC", "src":"asset.etc.ktx" },
       *     { "format":"RGBA_PVRTC_4BPPV1_IMG", "src":"asset.pvrtc.ktx" }
       *   ]
       * }
       * ```
       */
      CompressedTextureLoader.use = function (resource, next) {
          var data = resource.data;
          var loader = this;
          if (resource.type === exports.LoaderResource.TYPE.JSON
              && data
              && data.cacheID
              && data.textures) {
              var textures = data.textures;
              var textureURL = void 0;
              var fallbackURL = void 0;
              // Search for an extension that holds one the formats
              for (var i = 0, j = textures.length; i < j; i++) {
                  var texture = textures[i];
                  var url_1 = texture.src;
                  var format = texture.format;
                  if (!format) {
                      fallbackURL = url_1;
                  }
                  if (CompressedTextureLoader.textureFormats[format]) {
                      textureURL = url_1;
                      break;
                  }
              }
              textureURL = textureURL || fallbackURL;
              // Make sure we have a URL
              if (!textureURL) {
                  next(new Error("Cannot load compressed-textures in " + resource.url + ", make sure you provide a fallback"));
                  return;
              }
              if (textureURL === resource.url) {
                  // Prevent infinite loops
                  next(new Error('URL of compressed texture cannot be the same as the manifest\'s URL'));
                  return;
              }
              var loadOptions = {
                  crossOrigin: resource.crossOrigin,
                  metadata: resource.metadata.imageMetadata,
                  parentResource: resource
              };
              var resourcePath = url$1.resolve(resource.url.replace(loader.baseUrl, ''), textureURL);
              var resourceName = data.cacheID;
              // The appropriate loader should register the texture
              loader.add(resourceName, resourcePath, loadOptions, function (res) {
                  if (res.error) {
                      next(res.error);
                      return;
                  }
                  var _a = res.texture, texture = _a === void 0 ? null : _a, _b = res.textures, textures = _b === void 0 ? {} : _b;
                  // Make sure texture/textures is assigned to parent resource
                  Object.assign(resource, { texture: texture, textures: textures });
                  // Pass along any error
                  next();
              });
          }
          else {
              next();
          }
      };
      /**
       * Detects the available compressed texture extensions on the device.
       * @ignore
       */
      CompressedTextureLoader.add = function () {
          // Auto-detect WebGL compressed-texture extensions
          var canvas = document.createElement('canvas');
          var gl = canvas.getContext('webgl');
          if (!gl) {
              console.warn('WebGL not available for compressed textures. Silently failing.');
              return;
          }
          var extensions = {
              s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'),
              s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'),
              etc: gl.getExtension('WEBGL_compressed_texture_etc'),
              etc1: gl.getExtension('WEBGL_compressed_texture_etc1'),
              pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc')
                  || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'),
              atc: gl.getExtension('WEBGL_compressed_texture_atc'),
              astc: gl.getExtension('WEBGL_compressed_texture_astc')
          };
          CompressedTextureLoader.textureExtensions = extensions;
          CompressedTextureLoader.textureFormats = {};
          // Assign all available compressed-texture formats
          for (var extensionName in extensions) {
              var extension = extensions[extensionName];
              if (!extension) {
                  continue;
              }
              Object.assign(CompressedTextureLoader.textureFormats, Object.getPrototypeOf(extension));
          }
      };
      return CompressedTextureLoader;
  }());

  /**
   * Creates base-textures and textures for each compressed-texture resource and adds them into the global
   * texture cache. The first texture has two IDs - `${url}`, `${url}-1`; while the rest have an ID of the
   * form `${url}-i`.
   *
   * @param url - the original address of the resources
   * @param resources - the resources backing texture data
   * @ignore
   */
  function registerCompressedTextures(url, resources, metadata) {
      var result = {
          textures: {},
          texture: null,
      };
      if (!resources) {
          return result;
      }
      var textures = resources.map(function (resource) {
          return (new Texture(new BaseTexture(resource, Object.assign({
              mipmap: exports.MIPMAP_MODES.OFF,
              alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA
          }, metadata))));
      });
      textures.forEach(function (texture, i) {
          var baseTexture = texture.baseTexture;
          var cacheID = url + "-" + (i + 1);
          BaseTexture.addToCache(baseTexture, cacheID);
          Texture.addToCache(texture, cacheID);
          if (i === 0) {
              BaseTexture.addToCache(baseTexture, url);
              Texture.addToCache(texture, url);
              result.texture = texture;
          }
          result.textures[cacheID] = texture;
      });
      return result;
  }

  var _a$1, _b;
  // Set DDS files to be loaded as an ArrayBuffer
  exports.LoaderResource.setExtensionXhrType('dds', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER);
  var DDS_MAGIC_SIZE = 4;
  var DDS_HEADER_SIZE = 124;
  var DDS_HEADER_PF_SIZE = 32;
  var DDS_HEADER_DX10_SIZE = 20;
  // DDS file format magic word
  var DDS_MAGIC = 0x20534444;
  /**
   * DWORD offsets of the DDS file header fields (relative to file start).
   *
   * @ignore
   */
  var DDS_FIELDS = {
      SIZE: 1,
      FLAGS: 2,
      HEIGHT: 3,
      WIDTH: 4,
      MIPMAP_COUNT: 7,
      PIXEL_FORMAT: 19,
  };
  /**
   * DWORD offsets of the DDS PIXEL_FORMAT fields.
   *
   * @ignore
   */
  var DDS_PF_FIELDS = {
      SIZE: 0,
      FLAGS: 1,
      FOURCC: 2,
      RGB_BITCOUNT: 3,
      R_BIT_MASK: 4,
      G_BIT_MASK: 5,
      B_BIT_MASK: 6,
      A_BIT_MASK: 7
  };
  /**
   * DWORD offsets of the DDS_HEADER_DX10 fields.
   *
   * @ignore
   */
  var DDS_DX10_FIELDS = {
      DXGI_FORMAT: 0,
      RESOURCE_DIMENSION: 1,
      MISC_FLAG: 2,
      ARRAY_SIZE: 3,
      MISC_FLAGS2: 4
  };
  /**
   * @see https://docs.microsoft.com/en-us/windows/win32/api/dxgiformat/ne-dxgiformat-dxgi_format
   * @ignore
   */
  // This is way over-blown for us! Lend us a hand, and remove the ones that aren't used (but set the remaining
  // ones to their correct value)
  var DXGI_FORMAT;
  (function (DXGI_FORMAT) {
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_UNKNOWN"] = 0] = "DXGI_FORMAT_UNKNOWN";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_TYPELESS"] = 1] = "DXGI_FORMAT_R32G32B32A32_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_FLOAT"] = 2] = "DXGI_FORMAT_R32G32B32A32_FLOAT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_UINT"] = 3] = "DXGI_FORMAT_R32G32B32A32_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_SINT"] = 4] = "DXGI_FORMAT_R32G32B32A32_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_TYPELESS"] = 5] = "DXGI_FORMAT_R32G32B32_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_FLOAT"] = 6] = "DXGI_FORMAT_R32G32B32_FLOAT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_UINT"] = 7] = "DXGI_FORMAT_R32G32B32_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_SINT"] = 8] = "DXGI_FORMAT_R32G32B32_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_TYPELESS"] = 9] = "DXGI_FORMAT_R16G16B16A16_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_FLOAT"] = 10] = "DXGI_FORMAT_R16G16B16A16_FLOAT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UNORM"] = 11] = "DXGI_FORMAT_R16G16B16A16_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UINT"] = 12] = "DXGI_FORMAT_R16G16B16A16_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SNORM"] = 13] = "DXGI_FORMAT_R16G16B16A16_SNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SINT"] = 14] = "DXGI_FORMAT_R16G16B16A16_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_TYPELESS"] = 15] = "DXGI_FORMAT_R32G32_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_FLOAT"] = 16] = "DXGI_FORMAT_R32G32_FLOAT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_UINT"] = 17] = "DXGI_FORMAT_R32G32_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_SINT"] = 18] = "DXGI_FORMAT_R32G32_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G8X24_TYPELESS"] = 19] = "DXGI_FORMAT_R32G8X24_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT_S8X24_UINT"] = 20] = "DXGI_FORMAT_D32_FLOAT_S8X24_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"] = 21] = "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"] = 22] = "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_TYPELESS"] = 23] = "DXGI_FORMAT_R10G10B10A2_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UNORM"] = 24] = "DXGI_FORMAT_R10G10B10A2_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UINT"] = 25] = "DXGI_FORMAT_R10G10B10A2_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R11G11B10_FLOAT"] = 26] = "DXGI_FORMAT_R11G11B10_FLOAT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_TYPELESS"] = 27] = "DXGI_FORMAT_R8G8B8A8_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM"] = 28] = "DXGI_FORMAT_R8G8B8A8_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"] = 29] = "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UINT"] = 30] = "DXGI_FORMAT_R8G8B8A8_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SNORM"] = 31] = "DXGI_FORMAT_R8G8B8A8_SNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SINT"] = 32] = "DXGI_FORMAT_R8G8B8A8_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_TYPELESS"] = 33] = "DXGI_FORMAT_R16G16_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_FLOAT"] = 34] = "DXGI_FORMAT_R16G16_FLOAT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UNORM"] = 35] = "DXGI_FORMAT_R16G16_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UINT"] = 36] = "DXGI_FORMAT_R16G16_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SNORM"] = 37] = "DXGI_FORMAT_R16G16_SNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SINT"] = 38] = "DXGI_FORMAT_R16G16_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_TYPELESS"] = 39] = "DXGI_FORMAT_R32_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT"] = 40] = "DXGI_FORMAT_D32_FLOAT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT"] = 41] = "DXGI_FORMAT_R32_FLOAT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_UINT"] = 42] = "DXGI_FORMAT_R32_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_SINT"] = 43] = "DXGI_FORMAT_R32_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24G8_TYPELESS"] = 44] = "DXGI_FORMAT_R24G8_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D24_UNORM_S8_UINT"] = 45] = "DXGI_FORMAT_D24_UNORM_S8_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24_UNORM_X8_TYPELESS"] = 46] = "DXGI_FORMAT_R24_UNORM_X8_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X24_TYPELESS_G8_UINT"] = 47] = "DXGI_FORMAT_X24_TYPELESS_G8_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_TYPELESS"] = 48] = "DXGI_FORMAT_R8G8_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UNORM"] = 49] = "DXGI_FORMAT_R8G8_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UINT"] = 50] = "DXGI_FORMAT_R8G8_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SNORM"] = 51] = "DXGI_FORMAT_R8G8_SNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SINT"] = 52] = "DXGI_FORMAT_R8G8_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_TYPELESS"] = 53] = "DXGI_FORMAT_R16_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_FLOAT"] = 54] = "DXGI_FORMAT_R16_FLOAT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D16_UNORM"] = 55] = "DXGI_FORMAT_D16_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UNORM"] = 56] = "DXGI_FORMAT_R16_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UINT"] = 57] = "DXGI_FORMAT_R16_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SNORM"] = 58] = "DXGI_FORMAT_R16_SNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SINT"] = 59] = "DXGI_FORMAT_R16_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_TYPELESS"] = 60] = "DXGI_FORMAT_R8_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UNORM"] = 61] = "DXGI_FORMAT_R8_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UINT"] = 62] = "DXGI_FORMAT_R8_UINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SNORM"] = 63] = "DXGI_FORMAT_R8_SNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SINT"] = 64] = "DXGI_FORMAT_R8_SINT";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8_UNORM"] = 65] = "DXGI_FORMAT_A8_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R1_UNORM"] = 66] = "DXGI_FORMAT_R1_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R9G9B9E5_SHAREDEXP"] = 67] = "DXGI_FORMAT_R9G9B9E5_SHAREDEXP";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_B8G8_UNORM"] = 68] = "DXGI_FORMAT_R8G8_B8G8_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_G8R8_G8B8_UNORM"] = 69] = "DXGI_FORMAT_G8R8_G8B8_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_TYPELESS"] = 70] = "DXGI_FORMAT_BC1_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM"] = 71] = "DXGI_FORMAT_BC1_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM_SRGB"] = 72] = "DXGI_FORMAT_BC1_UNORM_SRGB";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_TYPELESS"] = 73] = "DXGI_FORMAT_BC2_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM"] = 74] = "DXGI_FORMAT_BC2_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM_SRGB"] = 75] = "DXGI_FORMAT_BC2_UNORM_SRGB";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_TYPELESS"] = 76] = "DXGI_FORMAT_BC3_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM"] = 77] = "DXGI_FORMAT_BC3_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM_SRGB"] = 78] = "DXGI_FORMAT_BC3_UNORM_SRGB";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_TYPELESS"] = 79] = "DXGI_FORMAT_BC4_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_UNORM"] = 80] = "DXGI_FORMAT_BC4_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_SNORM"] = 81] = "DXGI_FORMAT_BC4_SNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_TYPELESS"] = 82] = "DXGI_FORMAT_BC5_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_UNORM"] = 83] = "DXGI_FORMAT_BC5_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_SNORM"] = 84] = "DXGI_FORMAT_BC5_SNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G6R5_UNORM"] = 85] = "DXGI_FORMAT_B5G6R5_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G5R5A1_UNORM"] = 86] = "DXGI_FORMAT_B5G5R5A1_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM"] = 87] = "DXGI_FORMAT_B8G8R8A8_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM"] = 88] = "DXGI_FORMAT_B8G8R8X8_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"] = 89] = "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_TYPELESS"] = 90] = "DXGI_FORMAT_B8G8R8A8_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"] = 91] = "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_TYPELESS"] = 92] = "DXGI_FORMAT_B8G8R8X8_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"] = 93] = "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_TYPELESS"] = 94] = "DXGI_FORMAT_BC6H_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_UF16"] = 95] = "DXGI_FORMAT_BC6H_UF16";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_SF16"] = 96] = "DXGI_FORMAT_BC6H_SF16";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_TYPELESS"] = 97] = "DXGI_FORMAT_BC7_TYPELESS";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM"] = 98] = "DXGI_FORMAT_BC7_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM_SRGB"] = 99] = "DXGI_FORMAT_BC7_UNORM_SRGB";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AYUV"] = 100] = "DXGI_FORMAT_AYUV";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y410"] = 101] = "DXGI_FORMAT_Y410";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y416"] = 102] = "DXGI_FORMAT_Y416";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV12"] = 103] = "DXGI_FORMAT_NV12";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P010"] = 104] = "DXGI_FORMAT_P010";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P016"] = 105] = "DXGI_FORMAT_P016";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_420_OPAQUE"] = 106] = "DXGI_FORMAT_420_OPAQUE";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_YUY2"] = 107] = "DXGI_FORMAT_YUY2";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y210"] = 108] = "DXGI_FORMAT_Y210";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y216"] = 109] = "DXGI_FORMAT_Y216";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV11"] = 110] = "DXGI_FORMAT_NV11";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AI44"] = 111] = "DXGI_FORMAT_AI44";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_IA44"] = 112] = "DXGI_FORMAT_IA44";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P8"] = 113] = "DXGI_FORMAT_P8";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8P8"] = 114] = "DXGI_FORMAT_A8P8";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B4G4R4A4_UNORM"] = 115] = "DXGI_FORMAT_B4G4R4A4_UNORM";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P208"] = 116] = "DXGI_FORMAT_P208";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V208"] = 117] = "DXGI_FORMAT_V208";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V408"] = 118] = "DXGI_FORMAT_V408";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"] = 119] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"] = 120] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE";
      DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_FORCE_UINT"] = 121] = "DXGI_FORMAT_FORCE_UINT";
  })(DXGI_FORMAT || (DXGI_FORMAT = {}));
  /**
   * Possible values of the field {@link DDS_DX10_FIELDS.RESOURCE_DIMENSION}
   *
   * @ignore
   */
  var D3D10_RESOURCE_DIMENSION;
  (function (D3D10_RESOURCE_DIMENSION) {
      D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE1D"] = 2] = "DDS_DIMENSION_TEXTURE1D";
      D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE2D"] = 3] = "DDS_DIMENSION_TEXTURE2D";
      D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE3D"] = 6] = "DDS_DIMENSION_TEXTURE3D";
  })(D3D10_RESOURCE_DIMENSION || (D3D10_RESOURCE_DIMENSION = {}));
  var PF_FLAGS = 1;
  // PIXEL_FORMAT flags
  var DDPF_ALPHA = 0x2;
  var DDPF_FOURCC = 0x4;
  var DDPF_RGB = 0x40;
  var DDPF_YUV = 0x200;
  var DDPF_LUMINANCE = 0x20000;
  // Four character codes for DXTn formats
  var FOURCC_DXT1 = 0x31545844;
  var FOURCC_DXT3 = 0x33545844;
  var FOURCC_DXT5 = 0x35545844;
  var FOURCC_DX10 = 0x30315844;
  // Cubemap texture flag (for DDS_DX10_FIELDS.MISC_FLAG)
  var DDS_RESOURCE_MISC_TEXTURECUBE = 0x4;
  /**
   * Maps `FOURCC_*` formats to internal formats (see {@link PIXI.INTERNAL_FORMATS}).
   *
   * @ignore
   */
  var FOURCC_TO_FORMAT = (_a$1 = {},
      _a$1[FOURCC_DXT1] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT,
      _a$1[FOURCC_DXT3] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT,
      _a$1[FOURCC_DXT5] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
      _a$1);
  /**
   * Maps {@link DXGI_FORMAT} to types/internal-formats (see {@link PIXI.TYPES}, {@link PIXI.INTERNAL_FORMATS})
   *
   * @ignore
   */
  var DXGI_TO_FORMAT = (_b = {},
      // WEBGL_compressed_texture_s3tc
      _b[DXGI_FORMAT.DXGI_FORMAT_BC1_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT,
      _b[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT,
      _b[DXGI_FORMAT.DXGI_FORMAT_BC2_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT,
      _b[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT,
      _b[DXGI_FORMAT.DXGI_FORMAT_BC3_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
      _b[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
      // WEBGL_compressed_texture_s3tc_srgb
      _b[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,
      _b[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,
      _b[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT,
      _b);
  /**
   * @class
   * @memberof PIXI
   * @implements PIXI.ILoaderPlugin
   * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide
   */
  var DDSLoader = /** @class */ (function () {
      function DDSLoader() {
      }
      /**
       * Registers a DDS compressed texture
       * @see PIXI.Loader.loaderMiddleware
       * @param resource - loader resource that is checked to see if it is a DDS file
       * @param next - callback Function to call when done
       */
      DDSLoader.use = function (resource, next) {
          if (resource.extension === 'dds' && resource.data) {
              try {
                  Object.assign(resource, registerCompressedTextures(resource.name || resource.url, DDSLoader.parse(resource.data), resource.metadata));
              }
              catch (err) {
                  next(err);
                  return;
              }
          }
          next();
      };
      /** Parses the DDS file header, generates base-textures, and puts them into the texture cache. */
      DDSLoader.parse = function (arrayBuffer) {
          var data = new Uint32Array(arrayBuffer);
          var magicWord = data[0];
          if (magicWord !== DDS_MAGIC) {
              throw new Error('Invalid DDS file magic word');
          }
          var header = new Uint32Array(arrayBuffer, 0, DDS_HEADER_SIZE / Uint32Array.BYTES_PER_ELEMENT);
          // DDS header fields
          var height = header[DDS_FIELDS.HEIGHT];
          var width = header[DDS_FIELDS.WIDTH];
          var mipmapCount = header[DDS_FIELDS.MIPMAP_COUNT];
          // PIXEL_FORMAT fields
          var pixelFormat = new Uint32Array(arrayBuffer, DDS_FIELDS.PIXEL_FORMAT * Uint32Array.BYTES_PER_ELEMENT, DDS_HEADER_PF_SIZE / Uint32Array.BYTES_PER_ELEMENT);
          var formatFlags = pixelFormat[PF_FLAGS];
          // File contains compressed texture(s)
          if (formatFlags & DDPF_FOURCC) {
              var fourCC = pixelFormat[DDS_PF_FIELDS.FOURCC];
              // File contains one DXTn compressed texture
              if (fourCC !== FOURCC_DX10) {
                  var internalFormat_1 = FOURCC_TO_FORMAT[fourCC];
                  var dataOffset_1 = DDS_MAGIC_SIZE + DDS_HEADER_SIZE;
                  var texData = new Uint8Array(arrayBuffer, dataOffset_1);
                  var resource = new CompressedTextureResource(texData, {
                      format: internalFormat_1,
                      width: width,
                      height: height,
                      levels: mipmapCount // CompressedTextureResource will separate the levelBuffers for us!
                  });
                  return [resource];
              }
              // FOURCC_DX10 indicates there is a 20-byte DDS_HEADER_DX10 after DDS_HEADER
              var dx10Offset = DDS_MAGIC_SIZE + DDS_HEADER_SIZE;
              var dx10Header = new Uint32Array(data.buffer, dx10Offset, DDS_HEADER_DX10_SIZE / Uint32Array.BYTES_PER_ELEMENT);
              var dxgiFormat = dx10Header[DDS_DX10_FIELDS.DXGI_FORMAT];
              var resourceDimension = dx10Header[DDS_DX10_FIELDS.RESOURCE_DIMENSION];
              var miscFlag = dx10Header[DDS_DX10_FIELDS.MISC_FLAG];
              var arraySize = dx10Header[DDS_DX10_FIELDS.ARRAY_SIZE];
              // Map dxgiFormat to PIXI.INTERNAL_FORMATS
              var internalFormat_2 = DXGI_TO_FORMAT[dxgiFormat];
              if (internalFormat_2 === undefined) {
                  throw new Error("DDSLoader cannot parse texture data with DXGI format " + dxgiFormat);
              }
              if (miscFlag === DDS_RESOURCE_MISC_TEXTURECUBE) {
                  // FIXME: Anybody excited about cubemap compressed textures?
                  throw new Error('DDSLoader does not support cubemap textures');
              }
              if (resourceDimension === D3D10_RESOURCE_DIMENSION.DDS_DIMENSION_TEXTURE3D) {
                  // FIXME: Anybody excited about 3D compressed textures?
                  throw new Error('DDSLoader does not supported 3D texture data');
              }
              // Uint8Array buffers of image data, including all mipmap levels in each image
              var imageBuffers = new Array();
              var dataOffset = DDS_MAGIC_SIZE
                  + DDS_HEADER_SIZE
                  + DDS_HEADER_DX10_SIZE;
              if (arraySize === 1) {
                  // No need bothering with the imageSize calculation!
                  imageBuffers.push(new Uint8Array(arrayBuffer, dataOffset));
              }
              else {
                  // Calculate imageSize for each texture, and then locate each image's texture data
                  var pixelSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[internalFormat_2];
                  var imageSize = 0;
                  var levelWidth = width;
                  var levelHeight = height;
                  for (var i = 0; i < mipmapCount; i++) {
                      var alignedLevelWidth = Math.max(1, (levelWidth + 3) & ~3);
                      var alignedLevelHeight = Math.max(1, (levelHeight + 3) & ~3);
                      var levelSize = alignedLevelWidth * alignedLevelHeight * pixelSize;
                      imageSize += levelSize;
                      levelWidth = levelWidth >>> 1;
                      levelHeight = levelHeight >>> 1;
                  }
                  var imageOffset = dataOffset;
                  // NOTE: Cubemaps have 6-images per texture (but they aren't supported so ^_^)
                  for (var i = 0; i < arraySize; i++) {
                      imageBuffers.push(new Uint8Array(arrayBuffer, imageOffset, imageSize));
                      imageOffset += imageSize;
                  }
              }
              // Uint8Array -> CompressedTextureResource, and we're done!
              return imageBuffers.map(function (buffer) { return new CompressedTextureResource(buffer, {
                  format: internalFormat_2,
                  width: width,
                  height: height,
                  levels: mipmapCount
              }); });
          }
          if (formatFlags & DDPF_RGB) {
              // FIXME: We might want to allow uncompressed *.dds files?
              throw new Error('DDSLoader does not support uncompressed texture data.');
          }
          if (formatFlags & DDPF_YUV) {
              // FIXME: Does anybody need this feature?
              throw new Error('DDSLoader does not supported YUV uncompressed texture data.');
          }
          if (formatFlags & DDPF_LUMINANCE) {
              // FIXME: Microsoft says older DDS filers use this feature! Probably not worth the effort!
              throw new Error('DDSLoader does not support single-channel (lumninance) texture data!');
          }
          if (formatFlags & DDPF_ALPHA) {
              // FIXME: I'm tired! See above =)
              throw new Error('DDSLoader does not support single-channel (alpha) texture data!');
          }
          throw new Error('DDSLoader failed to load a texture file due to an unknown reason!');
      };
      return DDSLoader;
  }());

  var _a$2, _b$1, _c;
  // Set KTX files to be loaded as an ArrayBuffer
  exports.LoaderResource.setExtensionXhrType('ktx', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER);
  /**
   * The 12-byte KTX file identifier
   *
   * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.1
   * @ignore
   */
  var FILE_IDENTIFIER = [0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A];
  /**
   * The value stored in the "endianness" field.
   *
   * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.2
   * @ignore
   */
  var ENDIANNESS = 0x04030201;
  /**
   * Byte offsets of the KTX file header fields
   *
   * @ignore
   */
  var KTX_FIELDS = {
      FILE_IDENTIFIER: 0,
      ENDIANNESS: 12,
      GL_TYPE: 16,
      GL_TYPE_SIZE: 20,
      GL_FORMAT: 24,
      GL_INTERNAL_FORMAT: 28,
      GL_BASE_INTERNAL_FORMAT: 32,
      PIXEL_WIDTH: 36,
      PIXEL_HEIGHT: 40,
      PIXEL_DEPTH: 44,
      NUMBER_OF_ARRAY_ELEMENTS: 48,
      NUMBER_OF_FACES: 52,
      NUMBER_OF_MIPMAP_LEVELS: 56,
      BYTES_OF_KEY_VALUE_DATA: 60
  };
  /**
   * Byte size of the file header fields in {@code KTX_FIELDS}
   *
   * @ignore
   */
  var FILE_HEADER_SIZE = 64;
  /**
   * Maps {@link PIXI.TYPES} to the bytes taken per component, excluding those ones that are bit-fields.
   *
   * @ignore
   */
  var TYPES_TO_BYTES_PER_COMPONENT = (_a$2 = {},
      _a$2[exports.TYPES.UNSIGNED_BYTE] = 1,
      _a$2[exports.TYPES.UNSIGNED_SHORT] = 2,
      _a$2[exports.TYPES.INT] = 4,
      _a$2[exports.TYPES.UNSIGNED_INT] = 4,
      _a$2[exports.TYPES.FLOAT] = 4,
      _a$2[exports.TYPES.HALF_FLOAT] = 8,
      _a$2);
  /**
   * Number of components in each {@link PIXI.FORMATS}
   *
   * @ignore
   */
  var FORMATS_TO_COMPONENTS = (_b$1 = {},
      _b$1[exports.FORMATS.RGBA] = 4,
      _b$1[exports.FORMATS.RGB] = 3,
      _b$1[exports.FORMATS.RG] = 2,
      _b$1[exports.FORMATS.RED] = 1,
      _b$1[exports.FORMATS.LUMINANCE] = 1,
      _b$1[exports.FORMATS.LUMINANCE_ALPHA] = 2,
      _b$1[exports.FORMATS.ALPHA] = 1,
      _b$1);
  /**
   * Number of bytes per pixel in bit-field types in {@link PIXI.TYPES}
   *
   * @ignore
   */
  var TYPES_TO_BYTES_PER_PIXEL = (_c = {},
      _c[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = 2,
      _c[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = 2,
      _c[exports.TYPES.UNSIGNED_SHORT_5_6_5] = 2,
      _c);
  /**
   * Loader plugin for handling KTX texture container files.
   *
   * This KTX loader does not currently support the following features:
   * * cube textures
   * * 3D textures
   * * vendor-specific key/value data parsing
   * * endianness conversion for big-endian machines
   * * embedded *.basis files
   *
   * It does supports the following features:
   * * multiple textures per file
   * * mipmapping (only for compressed formats)
   *
   * @class
   * @memberof PIXI
   * @implements PIXI.ILoaderPlugin
   */
  var KTXLoader = /** @class */ (function () {
      function KTXLoader() {
      }
      /**
       * Called after a KTX file is loaded.
       *
       * This will parse the KTX file header and add a {@code BaseTexture} to the texture
       * cache.
       *
       * @see PIXI.Loader.loaderMiddleware
       * @param resource - loader resource that is checked to see if it is a KTX file
       * @param next - callback Function to call when done
       */
      KTXLoader.use = function (resource, next) {
          if (resource.extension === 'ktx' && resource.data) {
              try {
                  var url_1 = resource.name || resource.url;
                  var _a = KTXLoader.parse(url_1, resource.data), compressed = _a.compressed, uncompressed = _a.uncompressed;
                  if (compressed) {
                      Object.assign(resource, registerCompressedTextures(url_1, compressed, resource.metadata));
                  }
                  else if (uncompressed) {
                      var textures_1 = {};
                      uncompressed.forEach(function (image, i) {
                          var texture = new Texture(new BaseTexture(image.resource, {
                              mipmap: exports.MIPMAP_MODES.OFF,
                              alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA,
                              type: image.type,
                              format: image.format,
                          }));
                          var cacheID = url_1 + "-" + (i + 1);
                          BaseTexture.addToCache(texture.baseTexture, cacheID);
                          Texture.addToCache(texture, cacheID);
                          if (i === 0) {
                              textures_1[url_1] = texture;
                              BaseTexture.addToCache(texture.baseTexture, url_1);
                              Texture.addToCache(texture, url_1);
                          }
                          textures_1[cacheID] = texture;
                      });
                      Object.assign(resource, { textures: textures_1 });
                  }
              }
              catch (err) {
                  next(err);
                  return;
              }
          }
          next();
      };
      /** Parses the KTX file header, generates base-textures, and puts them into the texture cache. */
      KTXLoader.parse = function (url, arrayBuffer) {
          var dataView = new DataView(arrayBuffer);
          if (!KTXLoader.validate(url, dataView)) {
              return null;
          }
          var littleEndian = dataView.getUint32(KTX_FIELDS.ENDIANNESS, true) === ENDIANNESS;
          var glType = dataView.getUint32(KTX_FIELDS.GL_TYPE, littleEndian);
          // const glTypeSize = dataView.getUint32(KTX_FIELDS.GL_TYPE_SIZE, littleEndian);
          var glFormat = dataView.getUint32(KTX_FIELDS.GL_FORMAT, littleEndian);
          var glInternalFormat = dataView.getUint32(KTX_FIELDS.GL_INTERNAL_FORMAT, littleEndian);
          var pixelWidth = dataView.getUint32(KTX_FIELDS.PIXEL_WIDTH, littleEndian);
          var pixelHeight = dataView.getUint32(KTX_FIELDS.PIXEL_HEIGHT, littleEndian) || 1; // "pixelHeight = 0" -> "1"
          var pixelDepth = dataView.getUint32(KTX_FIELDS.PIXEL_DEPTH, littleEndian) || 1; // ^^
          var numberOfArrayElements = dataView.getUint32(KTX_FIELDS.NUMBER_OF_ARRAY_ELEMENTS, littleEndian) || 1; // ^^
          var numberOfFaces = dataView.getUint32(KTX_FIELDS.NUMBER_OF_FACES, littleEndian);
          var numberOfMipmapLevels = dataView.getUint32(KTX_FIELDS.NUMBER_OF_MIPMAP_LEVELS, littleEndian);
          var bytesOfKeyValueData = dataView.getUint32(KTX_FIELDS.BYTES_OF_KEY_VALUE_DATA, littleEndian);
          // Whether the platform architecture is little endian. If littleEndian !== platformLittleEndian, then the
          // file contents must be endian-converted!
          // TODO: Endianness conversion
          // const platformLittleEndian = new Uint8Array((new Uint32Array([ENDIANNESS])).buffer)[0] === 0x01;
          if (pixelHeight === 0 || pixelDepth !== 1) {
              throw new Error('Only 2D textures are supported');
          }
          if (numberOfFaces !== 1) {
              throw new Error('CubeTextures are not supported by KTXLoader yet!');
          }
          if (numberOfArrayElements !== 1) {
              // TODO: Support splitting array-textures into multiple BaseTextures
              throw new Error('WebGL does not support array textures');
          }
          // TODO: 8x4 blocks for 2bpp pvrtc
          var blockWidth = 4;
          var blockHeight = 4;
          var alignedWidth = (pixelWidth + 3) & ~3;
          var alignedHeight = (pixelHeight + 3) & ~3;
          var imageBuffers = new Array(numberOfArrayElements);
          var imagePixels = pixelWidth * pixelHeight;
          if (glType === 0) {
              // Align to 16 pixels (4x4 blocks)
              imagePixels = alignedWidth * alignedHeight;
          }
          var imagePixelByteSize;
          if (glType !== 0) {
              // Uncompressed texture format
              if (TYPES_TO_BYTES_PER_COMPONENT[glType]) {
                  imagePixelByteSize = TYPES_TO_BYTES_PER_COMPONENT[glType] * FORMATS_TO_COMPONENTS[glFormat];
              }
              else {
                  imagePixelByteSize = TYPES_TO_BYTES_PER_PIXEL[glType];
              }
          }
          else {
              imagePixelByteSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[glInternalFormat];
          }
          if (imagePixelByteSize === undefined) {
              throw new Error('Unable to resolve the pixel format stored in the *.ktx file!');
          }
          var imageByteSize = imagePixels * imagePixelByteSize;
          var mipByteSize = imageByteSize;
          var mipWidth = pixelWidth;
          var mipHeight = pixelHeight;
          var alignedMipWidth = alignedWidth;
          var alignedMipHeight = alignedHeight;
          var imageOffset = FILE_HEADER_SIZE + bytesOfKeyValueData;
          for (var mipmapLevel = 0; mipmapLevel < numberOfMipmapLevels; mipmapLevel++) {
              var imageSize = dataView.getUint32(imageOffset, littleEndian);
              var elementOffset = imageOffset + 4;
              for (var arrayElement = 0; arrayElement < numberOfArrayElements; arrayElement++) {
                  // TODO: Maybe support 3D textures? :-)
                  // for (let zSlice = 0; zSlice < pixelDepth; zSlice)
                  var mips = imageBuffers[arrayElement];
                  if (!mips) {
                      mips = imageBuffers[arrayElement] = new Array(numberOfMipmapLevels);
                  }
                  mips[mipmapLevel] = {
                      levelID: mipmapLevel,
                      // don't align mipWidth when texture not compressed! (glType not zero)
                      levelWidth: numberOfMipmapLevels > 1 || glType !== 0 ? mipWidth : alignedMipWidth,
                      levelHeight: numberOfMipmapLevels > 1 || glType !== 0 ? mipHeight : alignedMipHeight,
                      levelBuffer: new Uint8Array(arrayBuffer, elementOffset, mipByteSize)
                  };
                  elementOffset += mipByteSize;
              }
              // HINT: Aligns to 4-byte boundary after jumping imageSize (in lieu of mipPadding)
              imageOffset += imageSize + 4; // (+4 to jump the imageSize field itself)
              imageOffset = imageOffset % 4 !== 0 ? imageOffset + 4 - (imageOffset % 4) : imageOffset;
              // Calculate mipWidth, mipHeight for _next_ iteration
              mipWidth = (mipWidth >> 1) || 1;
              mipHeight = (mipHeight >> 1) || 1;
              alignedMipWidth = (mipWidth + blockWidth - 1) & ~(blockWidth - 1);
              alignedMipHeight = (mipHeight + blockHeight - 1) & ~(blockHeight - 1);
              // Each mipmap level is 4-times smaller?
              mipByteSize = alignedMipWidth * alignedMipHeight * imagePixelByteSize;
          }
          // We use the levelBuffers feature of CompressedTextureResource b/c texture data is image-major, not level-major.
          if (glType !== 0) {
              return {
                  uncompressed: imageBuffers.map(function (levelBuffers) {
                      var buffer = levelBuffers[0].levelBuffer;
                      var convertToInt = false;
                      if (glType === exports.TYPES.FLOAT) {
                          buffer = new Float32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4);
                      }
                      else if (glType === exports.TYPES.UNSIGNED_INT) {
                          convertToInt = true;
                          buffer = new Uint32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4);
                      }
                      else if (glType === exports.TYPES.INT) {
                          convertToInt = true;
                          buffer = new Int32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4);
                      }
                      return {
                          resource: new BufferResource(buffer, {
                              width: levelBuffers[0].levelWidth,
                              height: levelBuffers[0].levelHeight,
                          }),
                          type: glType,
                          format: convertToInt ? KTXLoader.convertFormatToInteger(glFormat) : glFormat,
                      };
                  })
              };
          }
          return {
              compressed: imageBuffers.map(function (levelBuffers) { return new CompressedTextureResource(null, {
                  format: glInternalFormat,
                  width: pixelWidth,
                  height: pixelHeight,
                  levels: numberOfMipmapLevels,
                  levelBuffers: levelBuffers,
              }); })
          };
      };
      /** Checks whether the arrayBuffer contains a valid *.ktx file. */
      KTXLoader.validate = function (url, dataView) {
          // NOTE: Do not optimize this into 3 32-bit integer comparison because the endianness
          // of the data is not specified.
          for (var i = 0; i < FILE_IDENTIFIER.length; i++) {
              if (dataView.getUint8(i) !== FILE_IDENTIFIER[i]) {
                  console.error(url + " is not a valid *.ktx file!");
                  return false;
              }
          }
          return true;
      };
      KTXLoader.convertFormatToInteger = function (format) {
          switch (format) {
              case exports.FORMATS.RGBA: return exports.FORMATS.RGBA_INTEGER;
              case exports.FORMATS.RGB: return exports.FORMATS.RGB_INTEGER;
              case exports.FORMATS.RG: return exports.FORMATS.RG_INTEGER;
              case exports.FORMATS.RED: return exports.FORMATS.RED_INTEGER;
              default: return format;
          }
      };
      return KTXLoader;
  }());

  /*!
   * @pixi/particle-container - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/particle-container is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$4 = function(d, b) {
      extendStatics$4 = 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$4(d, b);
  };

  function __extends$4(d, b) {
      extendStatics$4(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  /**
   * 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).
   *
   * 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);
   * }
   * ```
   *
   * And here you have a hundred sprites that will be rendered at the speed of light.
   *
   * @memberof PIXI
   */
  var ParticleContainer = /** @class */ (function (_super) {
      __extends$4(ParticleContainer, _super);
      /**
       * @param maxSize - The maximum number of particles that can be rendered by the container.
       *  Affects size of allocated buffers.
       * @param 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;
          }
          _this._properties = [false, true, false, false, false];
          _this._maxSize = maxSize;
          _this._batchSize = batchSize;
          _this._buffers = null;
          _this._bufferUpdateIDs = [];
          _this._updateID = 0;
          _this.interactiveChildren = false;
          _this.blendMode = exports.BLEND_MODES.NORMAL;
          _this.autoResize = autoResize;
          _this.roundPixels = true;
          _this.baseTexture = null;
          _this.setProperties(properties);
          _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 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];
          }
      };
      ParticleContainer.prototype.updateTransform = function () {
          // TODO don't need to!
          this.displayObjectUpdateTransform();
      };
      Object.defineProperty(ParticleContainer.prototype, "tint", {
          /**
           * 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.
           *
           * @default 0xFFFFFF
           */
          get: function () {
              return this._tint;
          },
          set: function (value) {
              this._tint = value;
              hex2rgb(value, this.tintRgb);
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Renders the container using the WebGL renderer.
       *
       * @param 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
       *
       * @param 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 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;
  }(Container));

  /*
   * @author Mat Groves
   *
   * Big thanks to the very clever Matt DesLauriers <mattdesl> 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.
   *
   * @private
   * @memberof PIXI
   */
  var ParticleBuffer = /** @class */ (function () {
      /**
       * @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 Geometry();
          this.indexBuffer = null;
          this.size = size;
          this.dynamicProperties = [];
          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 || exports.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. */
      ParticleBuffer.prototype.initBuffers = function () {
          var geometry = this.geometry;
          var dynamicOffset = 0;
          this.indexBuffer = new Buffer(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 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 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 === exports.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 === exports.TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4);
          }
      };
      /**
       * Uploads the dynamic properties.
       *
       * @param children - The children to upload.
       * @param startIndex - The index to start at.
       * @param 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 === exports.TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset);
          }
          this.dynamicBuffer._updateID++;
      };
      /**
       * Uploads the static properties.
       *
       * @param children - The children to upload.
       * @param startIndex - The index to start at.
       * @param 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 === exports.TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset);
          }
          this.staticBuffer._updateID++;
      };
      /** Destroys the ParticleBuffer. */
      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;
  }());

  var fragment$1 = "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}";

  var vertex$1 = "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 <mattdesl> 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.
   *
   * @memberof PIXI
   */
  var ParticleRenderer = /** @class */ (function (_super) {
      __extends$4(ParticleRenderer, _super);
      /**
       * @param 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;
          _this.shader = null;
          _this.properties = null;
          _this.tempMatrix = new 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: exports.TYPES.UNSIGNED_BYTE,
                  uploadFunction: _this.uploadTint,
                  offset: 0,
              } ];
          _this.shader = Shader.from(vertex$1, fragment$1, {});
          _this.state = State.for2d();
          return _this;
      }
      /**
       * Renders the particle container object.
       *
       * @param 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 = 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 = 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 container - The container to render using this ParticleRenderer
       * @return - The buffers
       */
      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 container - The container to render using this ParticleRenderer
       * @return - The generated buffer
       */
      ParticleRenderer.prototype._generateOneMoreBuffer = function (container) {
          var batchSize = container._batchSize;
          var dynamicPropertyFlags = container._properties;
          return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize);
      };
      /**
       * Uploads the vertices.
       *
       * @param children - the array of display objects to render
       * @param startIndex - the index to start from in the children array
       * @param amount - the amount of children that will have their vertices uploaded
       * @param array - The vertices to upload.
       * @param stride - Stride to use for iteration.
       * @param 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 children - the array of display objects to render
       * @param startIndex - the index to start from in the children array
       * @param amount - the amount of children that will have their positions uploaded
       * @param array - The vertices to upload.
       * @param stride - Stride to use for iteration.
       * @param 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 children - the array of display objects to render
       * @param startIndex - the index to start from in the children array
       * @param amount - the amount of children that will have their rotation uploaded
       * @param array - The vertices to upload.
       * @param stride - Stride to use for iteration.
       * @param 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 children - the array of display objects to render
       * @param startIndex - the index to start from in the children array
       * @param amount - the amount of children that will have their rotation uploaded
       * @param array - The vertices to upload.
       * @param stride - Stride to use for iteration.
       * @param 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 children - the array of display objects to render
       * @param startIndex - the index to start from in the children array
       * @param amount - the amount of children that will have their rotation uploaded
       * @param array - The vertices to upload.
       * @param stride - Stride to use for iteration.
       * @param 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
                  ? 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;
  }(ObjectRenderer));

  /*!
   * @pixi/graphics - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/graphics is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * 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 = {}));
  /**
   * Support line caps in `PIXI.LineStyle` for graphics.
   *
   * @see PIXI.Graphics#lineStyle
   *
   * @name LINE_CAP
   * @memberof PIXI
   * @static
   * @enum {string}
   * @property {string} BUTT - 'butt': don't add any cap at line ends (leaves orthogonal edges)
   * @property {string} ROUND - 'round': add semicircle at ends
   * @property {string} SQUARE - 'square': add square at end (like `BUTT` except more length at end)
   */

  (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=true - 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.
   *
   * @memberof PIXI
   */
  var FillStyle = /** @class */ (function () {
      function FillStyle() {
          /**
           * The hex color value used when coloring the Graphics object.
           *
           * @default 0xFFFFFF
           */
          this.color = 0xFFFFFF;
          /** The alpha value used when filling the Graphics object. */
          this.alpha = 1.0;
          /**
           * The texture to be used for the fill.
           *
           * @default 0
           */
          this.texture = Texture.WHITE;
          /**
           * The transform applied to the texture.
           *
           * @default null
           */
          this.matrix = null;
          /** If the current fill is visible. */
          this.visible = false;
          this.reset();
      }
      /** Clones the object */
      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;
      };
      /** Reset */
      FillStyle.prototype.reset = function () {
          this.color = 0xFFFFFF;
          this.alpha = 1;
          this.texture = Texture.WHITE;
          this.matrix = null;
          this.visible = false;
      };
      /** Destroy and don't use after this. */
      FillStyle.prototype.destroy = function () {
          this.texture = null;
          this.matrix = null;
      };
      return FillStyle;
  }());

  /*! *****************************************************************************
  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$5 = function(d, b) {
      extendStatics$5 = 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$5(d, b);
  };

  function __extends$5(d, b) {
      extendStatics$5(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  function fixOrientation(points, hole) {
      var _a, _b;
      if (hole === void 0) { hole = false; }
      var m = points.length;
      if (m < 6) {
          return;
      }
      var area = 0;
      for (var i = 0, x1 = points[m - 2], y1 = points[m - 1]; i < m; i += 2) {
          var x2 = points[i];
          var y2 = points[i + 1];
          area += (x2 - x1) * (y2 + y1);
          x1 = x2;
          y1 = y2;
      }
      if ((!hole && area > 0) || (hole && area <= 0)) {
          var n = m / 2;
          for (var i = n + (n % 2); i < m; i += 2) {
              var i1 = m - i - 2;
              var i2 = m - i - 1;
              var i3 = i;
              var i4 = i + 1;
              _a = [points[i3], points[i1]], points[i1] = _a[0], points[i3] = _a[1];
              _b = [points[i4], points[i2]], points[i2] = _b[0], points[i4] = _b[1];
          }
      }
  }
  /**
   * 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) {
              fixOrientation(points, false);
              var holeArray = [];
              // Process holes..
              for (var i = 0; i < holes.length; i++) {
                  var hole = holes[i];
                  fixOrientation(hole.points, true);
                  holeArray.push(points.length / 2);
                  points = points.concat(hole.points);
              }
              // sort color
              var triangles = earcut_1(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]);
              }
          }
      },
  };

  // 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 points = graphicsData.points;
          var x;
          var y;
          var dx;
          var dy;
          var rx;
          var ry;
          if (graphicsData.type === exports.SHAPES.CIRC) {
              var circle = graphicsData.shape;
              x = circle.x;
              y = circle.y;
              rx = ry = circle.radius;
              dx = dy = 0;
          }
          else if (graphicsData.type === exports.SHAPES.ELIP) {
              var ellipse = graphicsData.shape;
              x = ellipse.x;
              y = ellipse.y;
              rx = ellipse.width;
              ry = ellipse.height;
              dx = dy = 0;
          }
          else {
              var roundedRect = graphicsData.shape;
              var halfWidth = roundedRect.width / 2;
              var halfHeight = roundedRect.height / 2;
              x = roundedRect.x + halfWidth;
              y = roundedRect.y + halfHeight;
              rx = ry = Math.max(0, Math.min(roundedRect.radius, Math.min(halfWidth, halfHeight)));
              dx = halfWidth - rx;
              dy = halfHeight - ry;
          }
          // Choose a number of segments such that the maximum absolute deviation from the circle is approximately 0.029
          var n = Math.ceil(2.3 * Math.sqrt(rx + ry));
          var m = (n * 8) + (dx ? 4 : 0) + (dy ? 4 : 0);
          points.length = m;
          if (m === 0) {
              return;
          }
          if (n === 0) {
              points.length = 8;
              points[0] = points[6] = x + dx;
              points[1] = points[3] = y + dy;
              points[2] = points[4] = x - dx;
              points[5] = points[7] = y - dy;
              return;
          }
          var j1 = 0;
          var j2 = (n * 4) + (dx ? 2 : 0) + 2;
          var j3 = j2;
          var j4 = m;
          {
              var x0 = dx + rx;
              var y0 = dy;
              var x1 = x + x0;
              var x2 = x - x0;
              var y1 = y + y0;
              points[j1++] = x1;
              points[j1++] = y1;
              points[--j2] = y1;
              points[--j2] = x2;
              if (dy) {
                  var y2 = y - y0;
                  points[j3++] = x2;
                  points[j3++] = y2;
                  points[--j4] = y2;
                  points[--j4] = x1;
              }
          }
          for (var i = 1; i < n; i++) {
              var a = Math.PI / 2 * (i / n);
              var x0 = dx + (Math.cos(a) * rx);
              var y0 = dy + (Math.sin(a) * ry);
              var x1 = x + x0;
              var x2 = x - x0;
              var y1 = y + y0;
              var y2 = y - y0;
              points[j1++] = x1;
              points[j1++] = y1;
              points[--j2] = y1;
              points[--j2] = x2;
              points[j3++] = x2;
              points[j3++] = y2;
              points[--j4] = y2;
              points[--j4] = x1;
          }
          {
              var x0 = dx;
              var y0 = dy + ry;
              var x1 = x + x0;
              var x2 = x - x0;
              var y1 = y + y0;
              var y2 = y - y0;
              points[j1++] = x1;
              points[j1++] = y1;
              points[--j4] = y2;
              points[--j4] = x1;
              if (dx) {
                  points[j1++] = x2;
                  points[j1++] = y1;
                  points[--j4] = y2;
                  points[--j4] = x2;
              }
          }
      },
      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 x;
          var y;
          if (graphicsData.type !== exports.SHAPES.RREC) {
              var circle = graphicsData.shape;
              x = circle.x;
              y = circle.y;
          }
          else {
              var roundedRect = graphicsData.shape;
              x = roundedRect.x + (roundedRect.width / 2);
              y = roundedRect.y + (roundedRect.height / 2);
          }
          var matrix = graphicsData.matrix;
          // 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);
          vertPos++;
          verts.push(points[0], points[1]);
          for (var i = 2; i < points.length; i += 2) {
              verts.push(points[i], points[i + 1]);
              // add some uvs
              indices.push(vertPos++, center, vertPos);
          }
          indices.push(center + 1, center, vertPos);
      },
  };

  /**
   * 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);
      },
  };

  /**
   * 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);
          // Handle case when first curve points overlaps and earcut fails to triangulate
          if (i === 0 && points[points.length - 2] === x && points[points.length - 1] === y) {
              continue;
          }
          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) {
          if (Graphics.nextRoundedRectBehavior) {
              buildCircle.build(graphicsData);
              return;
          }
          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 {
              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);
          }
      },
      triangulate: function (graphicsData, graphicsGeometry) {
          if (Graphics.nextRoundedRectBehavior) {
              buildCircle.triangulate(graphicsData, graphicsGeometry);
              return;
          }
          var points = graphicsData.points;
          var verts = graphicsGeometry.points;
          var indices = graphicsGeometry.indices;
          var vecPos = verts.length / 2;
          var triangles = earcut_1(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]);
          }
      },
  };

  /**
   * 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<number>} 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<number>} 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)
      {
          const r1x = cx - nxtPx;
          const r1y = cy - nxtPy;

          if (r1x === 0)
          {
              if (r1y > 0)
              {
                  angleDiff = -angleDiff;
              }
          }
          else if (r1x >= -GRAPHICS_CURVES.epsilon)
          {
              angleDiff = -angleDiff;
          }
      }*/
      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)));
          }
          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 Point(points[0], points[1]);
      var lastPoint = new Point(points[points.length - 2], points[points.length - 1]);
      var closedShape = shape.type !== exports.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 displacement 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);
          /* Is the inside miter point too far away, creating a spike? */
          var smallerInsideSegmentSq = Math.min((dx0 * dx0) + (dy0 * dy0), (dx1 * dx1) + (dy1 * dy1));
          var insideWeight = clockwise ? innerWeight : outerWeight;
          var smallerInsideDiagonalSq = smallerInsideSegmentSq + (insideWeight * insideWeight * widthSquared);
          var insideMiterOk = pdist <= smallerInsideDiagonalSq;
          if (insideMiterOk) {
              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);
                  }
              }
              else {
                  verts.push(imx, imy);
                  verts.push(omx, omy);
              }
          }
          else // inside miter is NOT ok
           {
              verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex
              verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex
              if (style.join === exports.LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) { ; }
              else if (style.join === exports.LINE_JOIN.ROUND) {
                  if (clockwise) /* arc is outside */ {
                      indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 2;
                  }
                  else /* arc is inside */ {
                      indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 2;
                  }
              }
              else {
                  if (clockwise) {
                      verts.push(omx, omy); // inner miter point
                      verts.push(omx, omy); // inner miter point
                  }
                  else {
                      verts.push(imx, imy); // outer miter point
                      verts.push(imx, imy); // outer miter point
                  }
                  indexCount += 2;
              }
              verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's inner vertex
              verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex
              indexCount += 2;
          }
      }
      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 !== exports.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);
      }
  }

  /**
   * Utilities for arc curves.
   *
   * @private
   */
  var ArcUtils = /** @class */ (function () {
      function ArcUtils() {
      }
      /**
       * The arcTo() method creates an arc/curve between two tangents on the canvas.
       *
       * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
       *
       * @private
       * @param x1 - The x-coordinate of the beginning of the arc
       * @param y1 - The y-coordinate of the beginning of the arc
       * @param x2 - The x-coordinate of the end of the arc
       * @param y2 - The y-coordinate of the end of the arc
       * @param radius - The radius of the arc
       * @return - If the arc length is valid, return center of circle, radius and other info otherwise `null`.
       */
      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;
          }
          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 */
      /**
       * The arc method creates an arc/curve (used to create circles, or parts of circles).
       *
       * @private
       * @param startX - Start x location of arc
       * @param startY - Start y location of arc
       * @param cx - The x-coordinate of the center of the circle
       * @param cy - The y-coordinate of the center of the circle
       * @param radius - The radius of the circle
       * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position
       *  of the arc's circle)
       * @param endAngle - The ending angle, in radians
       * @param anticlockwise - Specifies whether the drawing should be
       *  counter-clockwise or clockwise. False is default, and indicates clockwise, while true
       *  indicates counter-clockwise.
       * @param points - Collection of points to add to
       */
      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) / 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;
  }());

  /**
   * Utilities for bezier curves
   *
   * @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 fromX - Starting point x
       * @param fromY - Starting point y
       * @param cpX - Control point x
       * @param cpY - Control point y
       * @param cpX2 - Second Control point x
       * @param cpY2 - Second Control point y
       * @param toX - Destination point x
       * @param toY - Destination point y
       * @return - 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 result;
      };
      /**
       * Calculate the points for a bezier curve and then draws it.
       *
       * Ignored from docs since it is not directly exposed.
       *
       * @ignore
       * @param cpX - Control point x
       * @param cpY - Control point y
       * @param cpX2 - Second Control point x
       * @param cpY2 - Second Control point y
       * @param toX - Destination point x
       * @param toY - Destination point y
       * @param points - Path array to push points into
       */
      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;
  }());

  /**
   * Utilities for quadratic curves.
   *
   * @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 fromX - x-coordinate of curve start point
       * @param fromY - y-coordinate of curve start point
       * @param cpX - x-coordinate of curve control point
       * @param cpY - y-coordinate of curve control point
       * @param toX - x-coordinate of curve end point
       * @param toY - y-coordinate of curve end point
       * @return - 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 cpX - Control point x
       * @param cpY - Control point y
       * @param toX - Destination point x
       * @param toY - Destination point y
       * @param 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;
  }());

  /**
   * A structure to hold interim batch objects for Graphics.
   *
   * @memberof PIXI.graphicsUtils
   */
  var BatchPart = /** @class */ (function () {
      function BatchPart() {
          this.reset();
      }
      /** Begin batch part. */
      BatchPart.prototype.begin = function (style, startIndex, attribStart) {
          this.reset();
          this.style = style;
          this.start = startIndex;
          this.attribStart = attribStart;
      };
      /** End batch part. */
      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;
  }());

  /**
   * Generalized convenience utilities for Graphics.
   *
   * @namespace graphicsUtils
   * @memberof PIXI
   */
  var _a$3;
  /**
   * Map of fill commands for each shape type.
   *
   * @memberof PIXI.graphicsUtils
   * @member {Object} FILL_COMMANDS
   */
  var FILL_COMMANDS = (_a$3 = {},
      _a$3[exports.SHAPES.POLY] = buildPoly,
      _a$3[exports.SHAPES.CIRC] = buildCircle,
      _a$3[exports.SHAPES.ELIP] = buildCircle,
      _a$3[exports.SHAPES.RECT] = buildRectangle,
      _a$3[exports.SHAPES.RREC] = buildRoundedRectangle,
      _a$3);
  /**
   * Batch pool, stores unused batches for preventing allocations.
   *
   * @memberof PIXI.graphicsUtils
   * @member {Array<PIXI.graphicsUtils.BatchPart>} BATCH_POOL
   */
  var BATCH_POOL = [];
  /**
   * Draw call pool, stores unused draw calls for preventing allocations.
   *
   * @memberof PIXI.graphicsUtils
   * @member {Array<PIXI.BatchDrawCall>} DRAW_CALL_POOL
   */
  var DRAW_CALL_POOL = [];

  /**
   * A class to contain data useful for Graphics objects
   *
   * @memberof PIXI
   */
  var GraphicsData = /** @class */ (function () {
      /**
       * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
       * @param fillStyle - the width of the line to draw
       * @param lineStyle - the color of the line to draw
       * @param matrix - Transform matrix
       */
      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 collection of points. */
          this.points = [];
          /** The collection of holes. */
          this.holes = [];
          this.shape = shape;
          this.lineStyle = lineStyle;
          this.fillStyle = fillStyle;
          this.matrix = matrix;
          this.type = shape.type;
      }
      /**
       * Creates a new GraphicsData object with the same values as this one.
       *
       * @return - Cloned GraphicsData object
       */
      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;
  }());

  var tmpPoint = new Point();
  var tmpBounds = new Bounds();
  /**
   * 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.
   *
   * @memberof PIXI
   */
  var GraphicsGeometry = /** @class */ (function (_super) {
      __extends$5(GraphicsGeometry, _super);
      // eslint-disable-next-line @typescript-eslint/no-useless-constructor
      function GraphicsGeometry() {
          var _this = _super.call(this) || this;
          /**
           * Minimal distance between points that are considered different.
           * Affects line tesselation.
           */
          _this.closePointEps = 1e-4;
          /** Padding to add to the bounds. */
          _this.boundsPadding = 0;
          _this.uvsFloat32 = null;
          _this.indicesUint16 = null;
          _this.batchable = false;
          /** An array of points to draw, 2 numbers per point */
          _this.points = [];
          /** The collection of colors */
          _this.colors = [];
          /** The UVs collection */
          _this.uvs = [];
          /** The indices of the vertices */
          _this.indices = [];
          /** Reference to the texture IDs. */
          _this.textureIds = [];
          /**
           * The collection of drawn shapes.
           *
           * @member {PIXI.GraphicsData[]}
           */
          _this.graphicsData = [];
          /**
           * List of current draw calls drived from the batches.
           *
           * @member {PIXI.BatchDrawCall[]}
           */
          _this.drawCalls = [];
          /** Batches need to regenerated if the geometry is updated. */
          _this.batchDirty = -1;
          /**
           * Intermediate abstract format sent to batch system.
           * Can be converted to drawCalls or to batchable objects.
           *
           * @member {PIXI.graphicsUtils.BatchPart[]}
           */
          _this.batches = [];
          /** Used to detect if the graphics object has changed. */
          _this.dirty = 0;
          /** Used to check if the cache is dirty. */
          _this.cacheDirty = -1;
          /** Used to detect if we cleared the graphicsData. */
          _this.clearDirty = 0;
          /** Index of the last batched shape in the stack of calls. */
          _this.shapeIndex = 0;
          /** Cached bounds. */
          _this._bounds = new Bounds();
          /** The bounds dirty flag. */
          _this.boundsDirty = -1;
          return _this;
      }
      Object.defineProperty(GraphicsGeometry.prototype, "bounds", {
          /**
           * Get the current bounds of the graphic geometry.
           *
           * @readonly
           */
          get: function () {
              if (this.boundsDirty !== this.dirty) {
                  this.boundsDirty = this.dirty;
                  this.calculateBounds();
              }
              return this._bounds;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Call if you changed graphicsData manually.
       * Empties all batch buffers.
       */
      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]);
          }
          this.drawCalls.length = 0;
          for (var i = 0; i < this.batches.length; i++) {
              var batchPart = this.batches[i];
              batchPart.reset();
              BATCH_POOL.push(batchPart);
          }
          this.batches.length = 0;
      };
      /**
       * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
       *
       * @return - This GraphicsGeometry object. Good for chaining method calls
       */
      GraphicsGeometry.prototype.clear = function () {
          if (this.graphicsData.length > 0) {
              this.invalidate();
              this.clearDirty++;
              this.graphicsData.length = 0;
          }
          return this;
      };
      /**
       * 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 fillStyle - Defines style of the fill.
       * @param lineStyle - Defines style of the lines.
       * @param matrix - Transform applied to the points of the shape.
       * @return - Returns geometry for chaining.
       */
      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;
      };
      /**
       * 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 matrix - Transform applied to the points of the shape.
       * @return - Returns geometry for chaining.
       */
      GraphicsGeometry.prototype.drawHole = function (shape, matrix) {
          if (matrix === void 0) { matrix = null; }
          if (!this.graphicsData.length) {
              return null;
          }
          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;
      };
      /** Destroys the GraphicsGeometry object. */
      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();
          }
          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;
      };
      /**
       * Check to see if a point is contained within this geometry.
       *
       * @param point - Point to check if it's contained.
       * @return {Boolean} `true` if the point is contained within geometry.
       */
      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;
              }
              // 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;
      };
      /**
       * Generates intermediate batch data. Either gets converted to drawCalls
       * or used to convert to batch objects directly by the Graphics object.
       *
       * @param allow32Indices - Allow using 32-bit indices for preventing artifacts when more that 65535 vertices
       */
      GraphicsGeometry.prototype.updateBatches = function (allow32Indices) {
          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);
              }
              if (fillStyle.visible || lineStyle.visible) {
                  this.processHoles(data.holes);
              }
              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 = exports.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);
              }
          }
          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();
          }
      };
      /**
       * Affinity check
       *
       * @param styleA
       * @param styleB
       */
      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;
      };
      /** Test geometry for batching process. */
      GraphicsGeometry.prototype.validateBatching = function () {
          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;
      };
      /** Offset the indices so that it works with the batcher. */
      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;
              }
          }
      };
      /**
       * Checks to see if this graphics geometry can be batched.
       * Currently it needs to be small enough and not contain any native lines.
       */
      GraphicsGeometry.prototype.isBatchable = function () {
          // prevent heavy mesh batching
          if (this.points.length > 0xffff * 2) {
              return false;
          }
          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);
      };
      /** Converts intermediate batches data to drawCalls. */
      GraphicsGeometry.prototype.buildDrawCalls = function () {
          var TICK = ++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 BatchDrawCall();
              currentGroup.texArray = new BatchTextureArray();
          }
          currentGroup.texArray.count = 0;
          currentGroup.start = 0;
          currentGroup.size = 0;
          currentGroup.type = exports.DRAW_MODES.TRIANGLES;
          var textureCount = 0;
          var currentTexture = null;
          var textureId = 0;
          var native = false;
          var drawMode = exports.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 ? exports.DRAW_MODES.LINES : exports.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 BatchDrawCall();
                                  currentGroup.texArray = new 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 = exports.WRAP_MODES.REPEAT;
                      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, data.attribStart);
              this.addTextureIds(textureIds, textureId, data.attribSize, data.attribStart);
          }
          BaseTexture._globalBatch = TICK;
          // upload..
          // merge for now!
          this.packAttributes();
      };
      /** Packs attributes to single buffer. */
      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);
      };
      /** Process fill part of Graphics. */
      GraphicsGeometry.prototype.processFill = function (data) {
          if (data.holes.length) {
              buildPoly.triangulate(data, this);
          }
          else {
              var command = FILL_COMMANDS[data.type];
              command.triangulate(data, this);
          }
      };
      /** Process line part of Graphics. */
      GraphicsGeometry.prototype.processLine = function (data) {
          buildLine(data, this);
          for (var i = 0; i < data.holes.length; i++) {
              buildLine(data.holes[i], this);
          }
      };
      /** Process the holes data. */
      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);
              }
          }
      };
      /** Update the local bounds of the object. Expensive to use performance-wise. */
      GraphicsGeometry.prototype.calculateBounds = function () {
          var bounds = this._bounds;
          var sequenceBounds = tmpBounds;
          var curMatrix = 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 || Matrix.IDENTITY;
              var lineWidth = 0.0;
              if (lineStyle && lineStyle.visible) {
                  lineWidth = lineStyle.width * Math.max(0, lineStyle.alignment);
              }
              if (curMatrix !== nextMatrix) {
                  if (!sequenceBounds.isEmpty()) {
                      bounds.addBoundsMatrix(sequenceBounds, curMatrix);
                      sequenceBounds.clear();
                  }
                  curMatrix = nextMatrix;
              }
              if (type === exports.SHAPES.RECT || type === exports.SHAPES.RREC) {
                  var rect = shape;
                  sequenceBounds.addFramePad(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, lineWidth, lineWidth);
              }
              else if (type === exports.SHAPES.CIRC) {
                  var circle = shape;
                  sequenceBounds.addFramePad(circle.x, circle.y, circle.x, circle.y, circle.radius + lineWidth, circle.radius + lineWidth);
              }
              else if (type === exports.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);
      };
      /**
       * Transform points using matrix.
       *
       * @param points - Points to transform
       * @param matrix - Transform matrix
       */
      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;
          }
      };
      /**
       * Add colors.
       *
       * @param colors - List of colors to add to
       * @param color - Color to add
       * @param alpha - Alpha to use
       * @param size - Number of colors to add
       * @param offset
       */
      GraphicsGeometry.prototype.addColors = function (colors, color, alpha, size, offset) {
          if (offset === void 0) { offset = 0; }
          // TODO use the premultiply bits Ivan added
          var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16);
          var rgba = premultiplyTint(rgb, alpha);
          colors.length = Math.max(colors.length, offset + size);
          for (var i = 0; i < size; i++) {
              colors[offset + i] = rgba;
          }
      };
      /** Add texture id that the shader/fragment wants to use. */
      GraphicsGeometry.prototype.addTextureIds = function (textureIds, id, size, offset) {
          if (offset === void 0) { offset = 0; }
          textureIds.length = Math.max(textureIds.length, offset + size);
          for (var i = 0; i < size; i++) {
              textureIds[offset + i] = id;
          }
      };
      /**
       * Generates the UVs for a shape.
       *
       * @param verts - Vertices
       * @param uvs - UVs
       * @param texture - Reference to Texture
       * @param start - Index buffer start index.
       * @param size - The size/length for index buffer.
       * @param matrix - Optional transform for all points.
       */
      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);
          }
      };
      /**
       * Modify uvs array according to position of texture region
       * Does not work with rotated or trimmed textures
       *
       * @param uvs - array
       * @param texture - region
       * @param start - starting index for uvs
       * @param size - how many points to adjust
       */
      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;
          }
      };
      /**
       * The maximum number of points to consider an object "batchable",
       * able to be batched by the renderer's batch system.
  \    */
      GraphicsGeometry.BATCHABLE_SIZE = 100;
      return GraphicsGeometry;
  }(BatchGeometry));

  /**
   * Represents the line style for Graphics.
   *
   * @memberof PIXI
   */
  var LineStyle = /** @class */ (function (_super) {
      __extends$5(LineStyle, _super);
      function LineStyle() {
          var _this = _super !== null && _super.apply(this, arguments) || this;
          /** The width (thickness) of any lines drawn. */
          _this.width = 0;
          /** The alignment of any lines drawn (0.5 = middle, 1 = outer, 0 = inner). WebGL only. */
          _this.alignment = 0.5;
          /** If true the lines will be draw using LINES instead of TRIANGLE_STRIP. */
          _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. */
          _this.miterLimit = 10;
          return _this;
      }
      /** Clones the object. */
      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;
      };
      /** 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));

  var temp = new Float32Array(3);
  // a default shaders map used by graphics..
  var DEFAULT_SHADERS = {};
  /**
   * The Graphics class is primarily used to render primitive shapes such as lines, circles and
   * rectangles to the display, and to color and fill them.  However, you can also use a Graphics
   * object to build a list of primitives to use as a mask, or as a complex hitArea.
   *
   * Please note that due to legacy naming conventions, the behavior of some functions in this class
   * can be confusing.  Each call to `drawRect()`, `drawPolygon()`, etc. actually stores that primitive
   * in the Geometry class's GraphicsGeometry object for later use in rendering or hit testing - the
   * functions do not directly draw anything to the screen.  Similarly, the `clear()` function doesn't
   * change the screen, it simply resets the list of primitives, which can be useful if you want to
   * rebuild the contents of an existing Graphics object.
   *
   * Once a GraphicsGeometry list is built, you can re-use it in other Geometry objects as
   * an optimization, by passing it into a new Geometry object's constructor.  Because of this
   * ability, it's important to call `destroy()` on Geometry objects once you are done with them, to
   * properly dereference each GraphicsGeometry and prevent memory leaks.
   *
   * @memberof PIXI
   */
  var Graphics = /** @class */ (function (_super) {
      __extends$5(Graphics, _super);
      /**
       * @param geometry - 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;
          /**
           * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU.
           * Can be shared between multiple Graphics objects.
           */
          _this.shader = null;
          /** Renderer plugin for batching */
          _this.pluginName = 'batch';
          /**
           * Current path
           *
           * @readonly
           */
          _this.currentPath = null;
          /** A collections of batches! These can be drawn by the renderer batch system. */
          _this.batches = [];
          /** Update dirty for limiting calculating tints for batches. */
          _this.batchTint = -1;
          /** Update dirty for limiting calculating batches.*/
          _this.batchDirty = -1;
          /** Copy of the object vertex data. */
          _this.vertexData = null;
          /** Current fill style. */
          _this._fillStyle = new FillStyle();
          /** Current line style. */
          _this._lineStyle = new LineStyle();
          /** Current shape transform matrix. */
          _this._matrix = null;
          /** Current hole mode is enabled. */
          _this._holeMode = false;
          /**
           * 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.state = State.for2d();
          _this._geometry = geometry || new GraphicsGeometry();
          _this._geometry.refCount++;
          /**
           * 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._transformID = -1;
          // Set default
          _this.tint = 0xFFFFFF;
          _this.blendMode = exports.BLEND_MODES.NORMAL;
          return _this;
      }
      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.
           *
           * @readonly
           */
          get: function () {
              return this._geometry;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * 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)
       *
       * @return - A clone of the graphics object
       */
      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.  Note that, since each
           * primitive in the GraphicsGeometry list is rendered sequentially, modes
           * such as `PIXI.BLEND_MODES.ADD` and `PIXI.BLEND_MODES.MULTIPLY` will
           * be applied per-primitive.
           *
           * @default PIXI.BLEND_MODES.NORMAL
           */
          set: function (value) {
              this.state.blendMode = value;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Graphics.prototype, "tint", {
          /**
           * The tint applied to each graphic shape. This is a hex value. A value of
           * 0xFFFFFF will remove any tint effect.
           *
           * @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.
           *
           * @readonly
           */
          get: function () {
              return this._fillStyle;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Graphics.prototype, "line", {
          /**
           * The current line style.
           *
           * @readonly
           */
          get: function () {
              return this._lineStyle;
          },
          enumerable: false,
          configurable: true
      });
      Graphics.prototype.lineStyle = function (options, color, alpha, alignment, native) {
          if (options === void 0) { options = null; }
          if (color === void 0) { color = 0x0; }
          if (alpha === void 0) { alpha = 1; }
          if (alignment === void 0) { alignment = 0.5; }
          if (native === void 0) { native = false; }
          // Support non-object params: (width, color, alpha, alignment, native)
          if (typeof options === 'number') {
              options = { width: options, color: color, alpha: alpha, alignment: alignment, native: native };
          }
          return this.lineTextureStyle(options);
      };
      /**
       * Like line style but support texture for line fill.
       *
       * @param 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 = outer).
       *        WebGL only.
       * @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) {
          // Apply defaults
          options = Object.assign({
              width: 0,
              texture: 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();
              }
              Object.assign(this._lineStyle, { visible: visible }, options);
          }
          return this;
      };
      /**
       * Start a polygon object internally.
       *
       * @protected
       */
      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 Polygon();
                  this.currentPath.closeStroke = false;
                  this.currentPath.points.push(points[len - 2], points[len - 1]);
              }
          }
          else {
              this.currentPath = new Polygon();
              this.currentPath.closeStroke = false;
          }
      };
      /**
       * Finish the polygon object.
       *
       * @protected
       */
      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;
              }
          }
      };
      /**
       * Moves the current drawing position to x, y.
       *
       * @param x - the X coordinate to move to
       * @param y - the Y coordinate to move to
       * @return - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.moveTo = function (x, y) {
          this.startPoly();
          this.currentPath.points[0] = x;
          this.currentPath.points[1] = y;
          return this;
      };
      /**
       * 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 x - the X coordinate to draw to
       * @param y - the Y coordinate to draw to
       * @return - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.lineTo = function (x, y) {
          if (!this.currentPath) {
              this.moveTo(0, 0);
          }
          // 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;
      };
      /** Initialize the curve */
      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);
          }
      };
      /**
       * 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 cpX - Control point x
       * @param cpY - Control point y
       * @param toX - Destination point x
       * @param toY - Destination point y
       * @return - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) {
          this._initCurve();
          var points = this.currentPath.points;
          if (points.length === 0) {
              this.moveTo(0, 0);
          }
          QuadraticUtils.curveTo(cpX, cpY, toX, toY, points);
          return this;
      };
      /**
       * Calculate the points for a bezier curve and then draws it.
       *
       * @param cpX - Control point x
       * @param cpY - Control point y
       * @param cpX2 - Second Control point x
       * @param cpY2 - Second Control point y
       * @param toX - Destination point x
       * @param toY - Destination point y
       * @return This Graphics object. Good for chaining method calls
       */
      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;
      };
      /**
       * The arcTo() method creates an arc/curve between two tangents on the canvas.
       *
       * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
       *
       * @param x1 - The x-coordinate of the first tangent point of the arc
       * @param y1 - The y-coordinate of the first tangent point of the arc
       * @param x2 - The x-coordinate of the end of the arc
       * @param y2 - The y-coordinate of the end of the arc
       * @param radius - The radius of the arc
       * @return - This Graphics object. Good for chaining method calls
       */
      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);
          }
          return this;
      };
      /**
       * The arc method creates an arc/curve (used to create circles, or parts of circles).
       *
       * @param cx - The x-coordinate of the center of the circle
       * @param cy - The y-coordinate of the center of the circle
       * @param radius - The radius of the circle
       * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position
       *  of the arc's circle)
       * @param endAngle - The ending angle, in radians
       * @param anticlockwise - Specifies whether the drawing should be
       *  counter-clockwise or clockwise. False is default, and indicates clockwise, while true
       *  indicates counter-clockwise.
       * @return - This Graphics object. Good for chaining method calls
       */
      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 += PI_2;
          }
          else if (anticlockwise && startAngle <= endAngle) {
              startAngle += 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;
      };
      /**
       * Specifies a simple one-color fill that subsequent calls to other Graphics methods
       * (such as lineTo() or drawCircle()) use when drawing.
       *
       * @param color - the color of the fill
       * @param alpha - the alpha of the fill
       * @return - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.beginFill = function (color, alpha) {
          if (color === void 0) { color = 0; }
          if (alpha === void 0) { alpha = 1; }
          return this.beginTextureFill({ texture: Texture.WHITE, color: color, alpha: alpha });
      };
      /**
       * Begin the texture fill
       *
       * @param 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) {
          // Apply defaults
          options = Object.assign({
              texture: 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;
      };
      /**
       * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
       *
       * @return - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.endFill = function () {
          this.finishPoly();
          this._fillStyle.reset();
          return this;
      };
      /**
       * Draws a rectangle shape.
       *
       * @param x - The X coord of the top-left of the rectangle
       * @param y - The Y coord of the top-left of the rectangle
       * @param width - The width of the rectangle
       * @param height - The height of the rectangle
       * @return - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.drawRect = function (x, y, width, height) {
          return this.drawShape(new Rectangle(x, y, width, height));
      };
      /**
       * Draw a rectangle shape with rounded/beveled corners.
       *
       * @param x - The X coord of the top-left of the rectangle
       * @param y - The Y coord of the top-left of the rectangle
       * @param width - The width of the rectangle
       * @param height - The height of the rectangle
       * @param radius - Radius of the rectangle corners
       * @return - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) {
          return this.drawShape(new RoundedRectangle(x, y, width, height, radius));
      };
      /**
       * Draws a circle.
       *
       * @param x - The X coordinate of the center of the circle
       * @param y - The Y coordinate of the center of the circle
       * @param radius - The radius of the circle
       * @return - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.drawCircle = function (x, y, radius) {
          return this.drawShape(new Circle(x, y, radius));
      };
      /**
       * Draws an ellipse.
       *
       * @param x - The X coordinate of the center of the ellipse
       * @param y - The Y coordinate of the center of the ellipse
       * @param width - The half width of the ellipse
       * @param height - The half height of the ellipse
       * @return - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.drawEllipse = function (x, y, width, height) {
          return this.drawShape(new 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 - This Graphics object. Good for chaining method calls
       */
      Graphics.prototype.drawPolygon = function () {
          var arguments$1 = arguments;

          var path = [];
          for (var _i = 0; _i < arguments.length; _i++) {
              path[_i] = arguments$1[_i];
          }
          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;
          }
          else if (Array.isArray(path[0])) {
              points = path[0];
          }
          else {
              points = path;
          }
          var shape = new 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 - 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;
      };
      /**
       * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
       *
       * @return - This Graphics object. Good for chaining method calls
       */
      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;
      };
      /**
       * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and
       * masked with gl.scissor.
       *
       * @returns - True if only 1 rect.
       */
      Graphics.prototype.isFastRect = function () {
          var data = this._geometry.graphicsData;
          return data.length === 1
              && data[0].shape.type === exports.SHAPES.RECT
              && !data[0].matrix
              && !data[0].holes.length
              && !(data[0].lineStyle.visible && data[0].lineStyle.width);
      };
      /**
       * Renders the object using the WebGL renderer
       *
       * @param renderer - The renderer
       */
      Graphics.prototype._render = function (renderer) {
          this.finishPoly();
          var geometry = this._geometry;
          var hasuint32 = renderer.context.supports.uint32Indices;
          // batch part..
          // batch it!
          geometry.updateBatches(hasuint32);
          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. */
      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: 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
       *
       * @param renderer - The renderer
       */
      Graphics.prototype._renderBatched = function (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
       *
       * @param 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 */
      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
       *
       * @param 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 MAX_TEXTURES = renderer.plugins.batch.MAX_TEXTURES;
                  var sampleValues = new Int32Array(MAX_TEXTURES);
                  for (var i = 0; i < MAX_TEXTURES; i++) {
                      sampleValues[i] = i;
                  }
                  var uniforms = {
                      tint: new Float32Array([1, 1, 1, 1]),
                      translationMatrix: new Matrix(),
                      default: UniformGroup.from({ uSamplers: sampleValues }, true),
                  };
                  var program = renderer.plugins[pluginName]._shader.program;
                  DEFAULT_SHADERS[pluginName] = new Shader(program, uniforms);
              }
              shader = DEFAULT_SHADERS[pluginName];
          }
          return shader;
      };
      /** Retrieves the bounds of the graphic shape as a rectangle object. */
      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 point - the point to test
       * @return - the result of the test
       */
      Graphics.prototype.containsPoint = function (point) {
          this.worldTransform.applyInverse(point, Graphics._TEMP_POINT);
          return this._geometry.containsPoint(Graphics._TEMP_POINT);
      };
      /** Recalculate the tint by applying tint to batches using Graphics tint. */
      Graphics.prototype.calculateTints = function () {
          if (this.batchTint !== this.tint) {
              this.batchTint = this.tint;
              var tintRGB = 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, recalculate the vertices.
       */
      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 - 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;
              // ensure that the polygon is completed, and is available for hit detection
              // (even if the graphics is not rendered yet)
              this.finishPoly();
          }
          return this;
      };
      /**
       * Apply a matrix to the positional data.
       *
       * @param matrix - Matrix to use for transform current shape.
       * @return - 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 - Returns itself.
       */
      Graphics.prototype.beginHole = function () {
          this.finishPoly();
          this._holeMode = true;
          return this;
      };
      /**
       * End adding holes to the last draw shape.
       *
       * @return - Returns itself.
       */
      Graphics.prototype.endHole = function () {
          this.finishPoly();
          this._holeMode = false;
          return this;
      };
      /**
       * Destroys the Graphics object.
       *
       * @param 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) {
          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);
      };
      /**
       * New rendering behavior for rounded rectangles: circular arcs instead of quadratic bezier curves.
       * In the next major release, we'll enable this by default.
       */
      Graphics.nextRoundedRectBehavior = false;
      /**
       * Temporary point to use for containsPoint.
       *
       * @private
       */
      Graphics._TEMP_POINT = new Point();
      return Graphics;
  }(Container));

  var graphicsUtils = {
      buildPoly: buildPoly,
      buildCircle: buildCircle,
      buildRectangle: buildRectangle,
      buildRoundedRectangle: buildRoundedRectangle,
      buildLine: buildLine,
      ArcUtils: ArcUtils,
      BezierUtils: BezierUtils,
      QuadraticUtils: QuadraticUtils,
      BatchPart: BatchPart,
      FILL_COMMANDS: FILL_COMMANDS,
      BATCH_POOL: BATCH_POOL,
      DRAW_CALL_POOL: DRAW_CALL_POOL
  };

  /*!
   * @pixi/sprite - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/sprite is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$6 = function(d, b) {
      extendStatics$6 = 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$6(d, b);
  };

  function __extends$6(d, b) {
      extendStatics$6(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  var tempPoint = new 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"]);
   *   ...
   * }
   * ```
   *
   * @memberof PIXI
   */
  var Sprite = /** @class */ (function (_super) {
      __extends$6(Sprite, _super);
      /** @param texture - The texture for this sprite. */
      function Sprite(texture) {
          var _this = _super.call(this) || this;
          _this._anchor = new ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0));
          _this._texture = null;
          _this._width = 0;
          _this._height = 0;
          _this._tint = null;
          _this._tintRGB = null;
          _this.tint = 0xFFFFFF;
          _this.blendMode = exports.BLEND_MODES.NORMAL;
          _this._cachedTint = 0xFFFFFF;
          _this.uvs = null;
          // call texture setter
          _this.texture = texture || Texture.EMPTY;
          _this.vertexData = new Float32Array(8);
          _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.pluginName = 'batch';
          /**
           * Used to fast check if a sprite is.. a sprite!
           * @member {boolean}
           */
          _this.isSprite = true;
          _this._roundPixels = settings.ROUND_PIXELS;
          return _this;
      }
      /** When the texture is updated, this event will fire to update the scale and frame. */
      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 = sign$1(this.scale.x) * this._width / this._texture.orig.width;
          }
          if (this._height) {
              this.scale.y = sign$1(this.scale.y) * this._height / this._texture.orig.height;
          }
      };
      /** Called when the anchor position updates. */
      Sprite.prototype._onAnchorUpdate = function () {
          this._transformID = -1;
          this._transformTrimmedID = -1;
      };
      /** Calculates worldTransform * vertices, store it in vertexData. */
      Sprite.prototype.calculateVertices = function () {
          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) {
              var resolution = settings.RESOLUTION;
              for (var i = 0; i < vertexData.length; ++i) {
                  vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution);
              }
          }
      };
      /**
       * 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.
       */
      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;
      };
      /**
       *
       * Renders the object using the WebGL renderer
       *
       * @param 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);
      };
      /** Updates the bounds of the sprite. */
      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);
          }
      };
      /**
       * Gets the local bounds of the sprite object.
       *
       * @param rect - Optional output rectangle.
       * @return The bounds.
       */
      Sprite.prototype.getLocalBounds = function (rect) {
          // we can do a fast local bounds if the sprite has no children!
          if (this.children.length === 0) {
              if (!this._localBounds) {
                  this._localBounds = new Bounds();
              }
              this._localBounds.minX = this._texture.orig.width * -this._anchor._x;
              this._localBounds.minY = this._texture.orig.height * -this._anchor._y;
              this._localBounds.maxX = this._texture.orig.width * (1 - this._anchor._x);
              this._localBounds.maxY = this._texture.orig.height * (1 - this._anchor._y);
              if (!rect) {
                  if (!this._localBoundsRect) {
                      this._localBoundsRect = new Rectangle();
                  }
                  rect = this._localBoundsRect;
              }
              return this._localBounds.getRectangle(rect);
          }
          return _super.prototype.getLocalBounds.call(this, rect);
      };
      /**
       * Tests if a point is inside this sprite
       *
       * @param point - the point to test
       * @return The result of the test
       */
      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;
      };
      /**
       * Destroys this sprite and optionally its texture and children.
       *
       * @param options - Options parameter. A boolean will act as if all options
       *  have been set to that value
       * @param [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 [options.texture=false] - Should it destroy the current texture of the sprite as well
       * @param [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
       */
      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..
      /**
       * 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 {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from
       * @param {object} [options] - See {@link PIXI.BaseTexture}'s constructor for options.
       * @return The newly created sprite
       */
      Sprite.from = function (source, options) {
          var texture = (source instanceof Texture)
              ? source
              : 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}.
           *
           * @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. */
          get: function () {
              return Math.abs(this.scale.x) * this._texture.orig.width;
          },
          set: function (value) {
              var s = sign$1(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. */
          get: function () {
              return Math.abs(this.scale.y) * this._texture.orig.height;
          },
          set: function (value) {
              var s = sign$1(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).
           */
          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.
           *
           * @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. */
          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 || 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;
  }(Container));

  /*!
   * @pixi/text - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/text is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$7 = function(d, b) {
      extendStatics$7 = 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$7(d, b);
  };

  function __extends$7(d, b) {
      extendStatics$7(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
   */

  (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).
   *
   * @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);
      }
      /**
       * Creates a new TextStyle object with the same values as this one.
       * Note that the only the properties of the object are cloned.
       *
       * @return New cloned TextStyle object
       */
      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. */
          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. */
          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. */
          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. */
          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. */
          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'. */
          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. */
          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", {
          /**
           * 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 PIXI.TEXT_GRADIENT
           */
          get: function () {
              return this._fillGradientType;
          },
          set: function (fillGradientType) {
              if (this._fillGradientType !== fillGradientType) {
                  this._fillGradientType = fillGradientType;
                  this.styleID++;
              }
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(TextStyle.prototype, "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.
           */
          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 font family. */
          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", {
          /**
           * The font size
           * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em')
           */
          get: function () {
              return this._fontSize;
          },
          set: function (fontSize) {
              if (this._fontSize !== fontSize) {
                  this._fontSize = fontSize;
                  this.styleID++;
              }
          },
          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. */
          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. */
          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. */
          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.
           */
          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.
           */
          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", {
          /**
           * A canvas fillstyle that will be used on the text stroke
           * e.g 'blue', '#FCFF00'
           */
          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 0
           */
          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. */
          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. */
          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. */
          get: function () {
              return this._wordWrapWidth;
          },
          set: function (wordWrapWidth) {
              if (this._wordWrapWidth !== wordWrapWidth) {
                  this._wordWrapWidth = wordWrapWidth;
                  this.styleID++;
              }
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Generates a font style string to use for `TextMetrics.measureFont()`.
       *
       * @return Font style string, for passing to `TextMetrics.measureFont()`
       */
      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(',');
          }
          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(',');
      };
      return TextStyle;
  }());
  /**
   * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
   * @private
   * @param color
   * @return The color as a string.
   */
  function getSingleColor(color) {
      if (typeof color === 'number') {
          return 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 array1 - First array to compare
   * @param array2 - Second array to compare
   * @return 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 target - Target object to copy properties into
   * @param source - Source object for the properties to copy
   * @param 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)
   * ```
   *
   * @memberof PIXI
   */
  var TextMetrics = /** @class */ (function () {
      /**
       * @param text - the text that was measured
       * @param style - the style that was measured
       * @param width - the measured width of the text
       * @param height - the measured height of the text
       * @param lines - an array of the lines of text broken by new lines and wrapping if specified in style
       * @param lineWidths - an array of the line widths for each line matched to `lines`
       * @param lineHeight - the measured line height for this style
       * @param maxLineWidth - the maximum line width for all measured lines
       * @param {PIXI.IFontMetrics} fontProperties - the font properties object from TextMetrics.measureFont
       */
      function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) {
          this.text = text;
          this.style = style;
          this.width = width;
          this.height = height;
          this.lines = lines;
          this.lineWidths = lineWidths;
          this.lineHeight = lineHeight;
          this.maxLineWidth = maxLineWidth;
          this.fontProperties = fontProperties;
      }
      /**
       * Measures the supplied string of text and returns a Rectangle.
       *
       * @param text - The text to measure.
       * @param style - The text style to use for measuring
       * @param wordWrap - Override for if word-wrap should be applied to the text.
       * @param canvas - optional specification of the canvas to use for measuring.
       * @return 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.
       *
       * @param text - String to apply word wrapping to
       * @param style - the style to use when wrapping
       * @param canvas - optional specification of the canvas to use for measuring.
       * @return 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 = Object.create(null);
          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.
       *
       * @param line    - The line of text to add
       * @param newLine - Add new line character to end
       * @return A formatted line
       */
      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
       *
       * @param key            - The key
       * @param letterSpacing  - The letter spacing
       * @param cache          - The cache
       * @param context        - The canvas context
       * @return The from cache.
       */
      TextMetrics.getFromCache = function (key, letterSpacing, cache, context) {
          var width = cache[key];
          if (typeof width !== 'number') {
              var spacing = ((key.length) * letterSpacing);
              width = context.measureText(key).width + spacing;
              cache[key] = width;
          }
          return width;
      };
      /**
       * Determines whether we should collapse breaking spaces.
       *
       * @param whiteSpace - The TextStyle property whiteSpace
       * @return Should collapse
       */
      TextMetrics.collapseSpaces = function (whiteSpace) {
          return (whiteSpace === 'normal' || whiteSpace === 'pre-line');
      };
      /**
       * Determines whether we should collapse newLine chars.
       *
       * @param whiteSpace - The white space
       * @return  should collapse
       */
      TextMetrics.collapseNewlines = function (whiteSpace) {
          return (whiteSpace === 'normal');
      };
      /**
       * Trims breaking whitespaces from string.
       *
       * @param  text - The text
       * @return Trimmed string
       */
      TextMetrics.trimRight = function (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.
       *
       * @param  char - The character
       * @return 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.
       *
       * It allows one to determine whether char should be a breaking whitespace
       * For example certain characters in CJK langs or numbers.
       * It must return a boolean.
       *
       * @param char     - The character
       * @param [nextChar] - The next character
       * @return True if whitespace, False otherwise.
       */
      TextMetrics.isBreakingSpace = function (char, _nextChar) {
          if (typeof char !== 'string') {
              return false;
          }
          return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0);
      };
      /**
       * Splits a string into words, breaking-spaces and newLine characters
       *
       * @param  text - The text
       * @return  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];
              var nextChar = text[i + 1];
              if (TextMetrics.isBreakingSpace(char, nextChar) || TextMetrics.isNewline(char)) {
                  if (token !== '') {
                      tokens.push(token);
                      token = '';
                  }
                  tokens.push(char);
                  continue;
              }
              token += char;
          }
          if (token !== '') {
              tokens.push(token);
          }
          return tokens;
      };
      /**
       * 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  token       - The token
       * @param  breakWords - The style attr break words
       * @return Whether to break word or not
       */
      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  char        - The character
       * @param  nextChar    - The next character
       * @param  token       - The token/word the characters are from
       * @param  index       - The index in the token of the char
       * @param  breakWords - The style attr break words
       * @return 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  token - The token to split
       * @return The characters of the token
       */
      TextMetrics.wordWrapSplit = function (token) {
          return token.split('');
      };
      /**
       * Calculates the ascent, descent and fontSize of a given font-style
       *
       * @param font - String representing the style of the font
       * @return 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 = Math.ceil(TextMetrics.HEIGHT_MULTIPLIER * 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 = 0; j < line; j += 4) {
                  if (imagedata[idx + j] !== 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.
       *
       * @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 {
              TextMetrics._fonts = {};
          }
      };
      return TextMetrics;
  }());
  /**
   * 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);
          var context = c.getContext('2d');
          if (context && context.measureText) {
              return c;
          }
          return 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;
  /**
   * Height multiplier for setting height of canvas to calculate font metrics.
   *
   * @static
   * @memberof PIXI.TextMetrics
   * @name HEIGHT_MULTIPLIER
   * @type {number}
   * @default 2.00
   */
  TextMetrics.HEIGHT_MULTIPLIER = 2.0;
  /**
   * 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.
   *
   * @memberof PIXI
   * @typedef {object} IFontMetrics
   * @property {number} ascent - Font ascent
   * @property {number} descent - Font descent
   * @property {number} fontSize - Font size
   */

  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 text,
   * 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'});
   * ```
   *
   * @memberof PIXI
   */
  var Text = /** @class */ (function (_super) {
      __extends$7(Text, _super);
      /**
       * @param text - The string that you would like the text to display
       * @param {object|PIXI.TextStyle} [style] - The style parameters
       * @param 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 = Texture.from(canvas);
          texture.orig = new Rectangle();
          texture.trim = new Rectangle();
          _this = _super.call(this, texture) || this;
          _this._ownCanvas = ownCanvas;
          _this.canvas = canvas;
          _this.context = _this.canvas.getContext('2d');
          _this._resolution = settings.RESOLUTION;
          _this._autoResolution = true;
          _this._text = null;
          _this._style = null;
          _this._styleListener = null;
          _this._font = '';
          _this.text = text;
          _this.style = style;
          _this.localStyleID = -1;
          return _this;
      }
      /**
       * 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 respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called.
       */
      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.ceil((Math.max(1, width) + (style.padding * 2))) * this._resolution);
          this.canvas.height = Math.ceil(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;
              // we only want the drop shadow, so put text way off-screen
              var dsOffsetText = isShadowPass ? Math.ceil(Math.max(1, height) + (style.padding * 2)) : 0;
              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 = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor));
                  var dropShadowBlur = style.dropShadowBlur * this._resolution;
                  var dropShadowDistance = style.dropShadowDistance * this._resolution;
                  context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")";
                  context.shadowBlur = dropShadowBlur;
                  context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance;
                  context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * 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 = 'black';
                  context.shadowBlur = 0;
                  context.shadowOffsetX = 0;
                  context.shadowOffsetY = 0;
              }
              var linePositionYShift = (lineHeight - fontProperties.fontSize) / 2;
              if (!Text.nextLineHeightBehavior || lineHeight - fontProperties.fontSize < 0) {
                  linePositionYShift = 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
                      + linePositionYShift;
                  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 text - The text to draw
       * @param x - Horizontal position to draw the text
       * @param y - Vertical position to draw the text
       * @param isStroke - Is this drawing for the outside stroke of the
       *  text? If not, it's for the inside fill
       */
      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;
          // Checking that we can use moddern canvas2D api
          // https://developer.chrome.com/origintrials/#/view_trial/3585991203293757441
          // note: this is unstable API, Chrome less 94 use a `textLetterSpacing`, newest use a letterSpacing
          // eslint-disable-next-line max-len
          var supportLetterSpacing = Text.experimentalLetterSpacing
              && ('letterSpacing' in CanvasRenderingContext2D.prototype
                  || 'textLetterSpacing' in CanvasRenderingContext2D.prototype);
          if (letterSpacing === 0 || supportLetterSpacing) {
              if (supportLetterSpacing) {
                  this.context.letterSpacing = letterSpacing;
                  this.context.textLetterSpacing = letterSpacing;
              }
              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);
              }
              var textStr = '';
              for (var j = i + 1; j < stringArray.length; ++j) {
                  textStr += stringArray[j];
              }
              currentWidth = this.context.measureText(textStr).width;
              currentPosition += previousWidth - currentWidth + letterSpacing;
              previousWidth = currentWidth;
          }
      };
      /** Updates texture size based on canvas size. */
      Text.prototype.updateTexture = function () {
          var canvas = this.canvas;
          if (this._style.trim) {
              var trimmed = 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 = canvas.width / this._resolution;
          texture.trim.height = texture._frame.height = 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);
          texture.updateUvs();
          // Recursively updates transform of all objects from the root to this one
          this._recursivePostUpdateTransform();
          this.dirty = false;
      };
      /**
       * Renders the object using the WebGL renderer
       *
       * @param renderer - The renderer
       */
      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);
      };
      /**
       * Gets the local bounds of the text object.
       *
       * @param rect - The output rectangle.
       * @return The bounds.
       */
      Text.prototype.getLocalBounds = function (rect) {
          this.updateText(true);
          return _super.prototype.getLocalBounds.call(this, rect);
      };
      /** Calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. */
      Text.prototype._calculateBounds = function () {
          this.updateText(true);
          this.calculateVertices();
          // if we have already done this on THIS frame.
          this._bounds.addQuad(this.vertexData);
      };
      /**
       * Generates the fill style. Can automatically generate a gradient based on the fill style being an array
       *
       * @param style - The style.
       * @param lines - The lines of text.
       * @return The fill style
       */
      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 = (this.canvas.width / this._resolution) - dropShadowCorrection - (padding * 2);
          var height = (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
              // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc
              var textHeight = metrics.fontProperties.fontSize + style.strokeThickness;
              for (var i = 0; i < lines.length; i++) {
                  var lastLineBottom = (metrics.lineHeight * (i - 1)) + textHeight;
                  var thisLineTop = metrics.lineHeight * i;
                  var thisLineGradientStart = thisLineTop;
                  // Handle case where last & this line overlap
                  if (i > 0 && lastLineBottom > thisLineTop) {
                      thisLineGradientStart = (thisLineTop + lastLineBottom) / 2;
                  }
                  var thisLineBottom = thisLineTop + textHeight;
                  var nextLineTop = metrics.lineHeight * (i + 1);
                  var thisLineGradientEnd = thisLineBottom;
                  // Handle case where this & next line overlap
                  if (i + 1 < lines.length && nextLineTop < thisLineBottom) {
                      thisLineGradientEnd = (thisLineBottom + nextLineTop) / 2;
                  }
                  // textHeight, but as a 0-1 size in global gradient stop space
                  var gradStopLineHeight = (thisLineGradientEnd - thisLineGradientStart) / height;
                  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 = Math.min(1, Math.max(0, (thisLineGradientStart / height) + (lineStop * gradStopLineHeight)));
                      // There's potential for floating point precision issues at the seams between gradient repeats.
                      globalStop = Number(globalStop.toFixed(5));
                      gradient.addColorStop(globalStop, fill[j]);
                  }
              }
          }
          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;
      };
      /**
       * 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 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 (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 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. */
          get: function () {
              this.updateText(true);
              return Math.abs(this.scale.x) * this._texture.orig.width;
          },
          set: function (value) {
              this.updateText(true);
              var s = sign$1(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. */
          get: function () {
              this.updateText(true);
              return Math.abs(this.scale.y) * this._texture.orig.height;
          },
          set: function (value) {
              this.updateText(true);
              var s = sign$1(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.
           */
          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'. */
          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.
           *
           * @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
      });
      /**
       * New behavior for `lineHeight` that's meant to mimic HTML text. A value of `true` will
       * make sure the first baseline is offset by the `lineHeight` value if it is greater than `fontSize`.
       * A value of `false` will use the legacy behavior and not change the baseline of the first line.
       * In the next major release, we'll enable this by default.
       */
      Text.nextLineHeightBehavior = false;
      /**
       * New rendering behavior for letter-spacing which uses Chrome's new native API. This will
       * lead to more accurate letter-spacing results because it does not try to manually draw
       * each character. However, this Chrome API is experimental and may not serve all cases yet.
       */
      Text.experimentalLetterSpacing = false;
      return Text;
  }(Sprite));

  /*!
   * @pixi/prepare - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/prepare is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * Default number of uploads per frame using prepare plugin.
   *
   * @static
   * @memberof PIXI.settings
   * @name UPLOADS_PER_FRAME
   * @type {number}
   * @default 4
   */
  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$8 = function(d, b) {
      extendStatics$8 = 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$8(d, b);
  };

  function __extends$8(d, b) {
      extendStatics$8(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.
   *
   * @memberof PIXI
   */
  var CountLimiter = /** @class */ (function () {
      /**
       * @param maxItemsPerFrame - The maximum number of items that can be prepared each frame.
       */
      function CountLimiter(maxItemsPerFrame) {
          this.maxItemsPerFrame = maxItemsPerFrame;
          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 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 item - Display object to check
   * @param queue - Collection of items to upload
   * @return 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 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 item - Display object to check
   * @param queue - Collection of items to upload
   * @return If a PIXI.Texture object was found.
   */
  function findBaseTexture(item, queue) {
      if (item.baseTexture instanceof 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 item - Display object to check
   * @param queue - Collection of items to upload
   * @return If a PIXI.Texture object was found.
   */
  function findTexture(item, queue) {
      if (item._texture && item._texture instanceof 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 helper - Not used by this upload handler
   * @param item - Item to check
   * @return If item was uploaded.
   */
  function drawText(_helper, item) {
      if (item instanceof 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 helper - Not used by this upload handler
   * @param item - Item to check
   * @return If item was uploaded.
   */
  function calculateTextStyle(_helper, item) {
      if (item instanceof TextStyle) {
          var font = item.toFontString();
          TextMetrics.measureFont(font);
          return true;
      }
      return false;
  }
  /**
   * Built-in hook to find Text objects.
   *
   * @private
   * @param item - Display object to check
   * @param queue - Collection of items to upload
   * @return if a PIXI.Text object was found.
   */
  function findText(item, queue) {
      if (item instanceof 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 item - Display object to check
   * @param queue - Collection of items to upload
   * @return If a PIXI.TextStyle object was found.
   */
  function findTextStyle(item, queue) {
      if (item instanceof 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
   * @memberof PIXI
   */
  var BasePrepare = /** @class */ (function () {
      /**
       * @param {PIXI.AbstractRenderer} renderer - A reference to the current renderer
       */
      function BasePrepare(renderer) {
          var _this = this;
          this.limiter = new CountLimiter(settings.UPLOADS_PER_FRAME);
          this.renderer = renderer;
          this.uploadHookHelper = null;
          this.queue = [];
          this.addHooks = [];
          this.uploadHooks = [];
          this.completes = [];
          this.ticking = false;
          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);
      }
      /**
       * 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 (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.system.addOnce(this.tick, this, exports.UPDATE_PRIORITY.UTILITY);
              }
          }
          else if (done) {
              done();
          }
      };
      /**
       * Handle tick update
       *
       * @private
       */
      BasePrepare.prototype.tick = function () {
          setTimeout(this.delayedTick, 0);
      };
      /**
       * 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 () {
          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();
              }
          }
          // 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]();
              }
          }
          else {
              // if we are not finished, on the next rAF do this again
              Ticker.system.addOnce(this.tick, this, exports.UPDATE_PRIORITY.UTILITY);
          }
      };
      /**
       * 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 Instance of plugin for chaining.
       */
      BasePrepare.prototype.registerFindHook = function (addHook) {
          if (addHook) {
              this.addHooks.push(addHook);
          }
          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 Instance of plugin for chaining.
       */
      BasePrepare.prototype.registerUploadHook = function (uploadHook) {
          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 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;
              }
          }
          // Get children recursively
          if (item instanceof Container) {
              for (var i = item.children.length - 1; i >= 0; i--) {
                  this.add(item.children[i]);
              }
          }
          return this;
      };
      /** Destroys the plugin, don't use after this. */
      BasePrepare.prototype.destroy = function () {
          if (this.ticking) {
              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;
  }());

  /**
   * Built-in hook to upload PIXI.Texture objects to the GPU.
   *
   * @private
   * @param renderer - instance of the webgl renderer
   * @param item - Item to check
   * @return If item was uploaded.
   */
  function uploadBaseTextures(renderer, item) {
      if (item instanceof 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 renderer - instance of the webgl renderer
   * @param item - Item to check
   * @return If item was uploaded.
   */
  function uploadGraphics(renderer, item) {
      if (!(item instanceof 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 item - Display object to check
   * @param queue - Collection of items to upload
   * @return if a PIXI.Graphics object was found.
   */
  function findGraphics(item, queue) {
      if (item instanceof 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();
   * });
   *
   *
   * @memberof PIXI
   */
  var Prepare = /** @class */ (function (_super) {
      __extends$8(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));

  /**
   * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified
   * number of milliseconds per frame.
   *
   * @memberof PIXI
   */
  var TimeLimiter = /** @class */ (function () {
      /** @param maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. */
      function TimeLimiter(maxMilliseconds) {
          this.maxMilliseconds = maxMilliseconds;
          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 - If the item is allowed to be uploaded.
       */
      TimeLimiter.prototype.allowedToUpload = function () {
          return Date.now() - this.frameStart < this.maxMilliseconds;
      };
      return TimeLimiter;
  }());

  /*!
   * @pixi/spritesheet - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/spritesheet is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * 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.
   *
   * @memberof PIXI
   */
  var Spritesheet = /** @class */ (function () {
      /**
       * @param baseTexture - Reference to the source BaseTexture object.
       * @param {Object} data - Spritesheet image data.
       * @param 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; }
          this._texture = texture instanceof Texture ? texture : null;
          this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture;
          this.textures = {};
          this.animations = {};
          this.data = data;
          var resource = this.baseTexture.resource;
          this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null));
          this._frames = this.data.frames;
          this._frameKeys = Object.keys(this._frames);
          this._batchIndex = 0;
          this._callback = null;
      }
      /**
       * Generate the resolution from the filename or fallback
       * to the meta.scale field of the JSON data.
       *
       * @param resolutionFilename - The filename to use for resolving
       *        the default resolution.
       * @return Resolution to use for spritesheet.
       */
      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 = 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 (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
       *
       * @param 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 Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution);
                  if (data.rotated) {
                      frame = new 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 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 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 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
                  Texture.addToCache(this.textures[i], i);
              }
              frameIndex++;
          }
      };
      /** Parse animations config. */
      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]);
              }
          }
      };
      /** The parse has completed. */
      Spritesheet.prototype._parseComplete = function () {
          var callback = this._callback;
          this._callback = null;
          this._batchIndex = 0;
          callback.call(this, this.textures);
      };
      /** Begin the next batch of textures. */
      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);
      };
      /**
       * Destroy Spritesheet and don't use after this.
       *
       * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well
       */
      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;
      };
      /** The maximum number of Textures to build per process. */
      Spritesheet.BATCH_SIZE = 1000;
      return Spritesheet;
  }());
  /**
   * Reference to Spritesheet object created.
   * @member {PIXI.Spritesheet} spritesheet
   * @memberof PIXI.LoaderResource
   * @instance
   */
  /**
   * Dictionary of textures from Spritesheet.
   * @member {object<string, PIXI.Texture>} textures
   * @memberof PIXI.LoaderResource
   * @instance
   */

  /**
   * {@link PIXI.Loader} middleware for loading texture atlases that have been created with
   * TexturePacker or similar JSON-based spritesheet.
   *
   * This middleware automatically generates Texture resources.
   *
   * If you're using Webpack or other bundlers and plan on bundling the atlas' JSON,
   * use the {@link PIXI.Spritesheet} class to directly parse the JSON.
   *
   * The Loader's image Resource name is automatically appended with `"_image"`.
   * If a Resource with this name is already loaded, the Loader will skip parsing the
   * Spritesheet. The code below will generate an internal Loader Resource called `"myatlas_image"`.
   *
   * @example
   * loader.add('myatlas', 'path/to/myatlas.json');
   * loader.load(() => {
   *   loader.resources.myatlas; // atlas JSON resource
   *   loader.resources.myatlas_image; // atlas Image resource
   * });
   *
   * @memberof PIXI
   */
  var SpritesheetLoader = /** @class */ (function () {
      function SpritesheetLoader() {
      }
      /**
       * Called after a resource is loaded.
       *
       * @see PIXI.Loader.loaderMiddleware
       * @param resource
       * @param next
       */
      SpritesheetLoader.use = function (resource, next) {
          var _a, _b;
          // 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 !== exports.LoaderResource.TYPE.JSON
              || !resource.data.frames
              || loader.resources[imageResourceName]) {
              next();
              return;
          }
          // Check and add the multi atlas
          // Heavily influenced and based on https://github.com/rocket-ua/pixi-tps-loader/blob/master/src/ResourceLoader.js
          // eslint-disable-next-line camelcase
          var multiPacks = (_b = (_a = resource.data) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b.related_multi_packs;
          if (Array.isArray(multiPacks)) {
              var _loop_1 = function (item) {
                  if (typeof item !== 'string') {
                      return "continue";
                  }
                  var itemName = item.replace('.json', '');
                  var itemUrl = url$1.resolve(resource.url.replace(loader.baseUrl, ''), item);
                  // Check if the file wasn't already added as multipacks are redundant
                  if (loader.resources[itemName]
                      || Object.values(loader.resources).some(function (r) { return url$1.format(url$1.parse(r.url)) === itemUrl; })) {
                      return "continue";
                  }
                  var options = {
                      crossOrigin: resource.crossOrigin,
                      loadType: exports.LoaderResource.LOAD_TYPE.XHR,
                      xhrType: exports.LoaderResource.XHR_RESPONSE_TYPE.JSON,
                      parentResource: resource,
                      metadata: resource.metadata
                  };
                  loader.add(itemName, itemUrl, options);
              };
              for (var _i = 0, multiPacks_1 = multiPacks; _i < multiPacks_1.length; _i++) {
                  var item = multiPacks_1[_i];
                  _loop_1(item);
              }
          }
          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();
              });
          });
      };
      /**
       * Get the spritesheets root path
       *
       * @param resource - Resource to check path
       * @param 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 url$1.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image);
      };
      return SpritesheetLoader;
  }());

  /*!
   * @pixi/sprite-tiling - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/sprite-tiling is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$9 = function(d, b) {
      extendStatics$9 = 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$9(d, b);
  };

  function __extends$9(d, b) {
      extendStatics$9(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  var tempPoint$1 = new Point();
  /**
   * A tiling sprite is a fast way of rendering a tiling image.
   *
   * @memberof PIXI
   */
  var TilingSprite = /** @class */ (function (_super) {
      __extends$9(TilingSprite, _super);
      /**
       * @param texture - The texture of the tiling sprite.
       * @param width - The width of the tiling sprite.
       * @param height - The height of the tiling sprite.
       */
      function TilingSprite(texture, width, height) {
          if (width === void 0) { width = 100; }
          if (height === void 0) { height = 100; }
          var _this = _super.call(this, texture) || this;
          _this.tileTransform = new Transform();
          // The width of the tiling sprite
          _this._width = width;
          // The height of the tiling sprite
          _this._height = height;
          _this.uvMatrix = _this.texture.uvMatrix || new TextureMatrix(texture);
          /**
           * Plugin that is responsible for rendering this element.
           * Allows to customize the rendering process without overriding '_render' method.
           *
           * @default 'tilingSprite'
           */
          _this.pluginName = 'tilingSprite';
          _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. */
          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. */
          get: function () {
              return this.tileTransform.position;
          },
          set: function (value) {
              this.tileTransform.position.copyFrom(value);
          },
          enumerable: false,
          configurable: true
      });
      /**
       * @protected
       */
      TilingSprite.prototype._onTextureUpdate = function () {
          if (this.uvMatrix) {
              this.uvMatrix.texture = this._texture;
          }
          this._cachedTint = 0xFFFFFF;
      };
      /**
       * Renders the object using the WebGL renderer
       *
       * @param renderer - The renderer
       */
      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);
      };
      /** Updates the bounds of the tiling sprite. */
      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);
      };
      /**
       * Gets the local bounds of the sprite object.
       *
       * @param rect - Optional output rectangle.
       * @return The bounds.
       */
      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 Rectangle();
                  }
                  rect = this._localBoundsRect;
              }
              return this._bounds.getRectangle(rect);
          }
          return _super.prototype.getLocalBounds.call(this, rect);
      };
      /**
       * Checks if a point is inside this tiling sprite.
       *
       * @param point - The point to check.
       * @return Whether or not the sprite contains the point.
       */
      TilingSprite.prototype.containsPoint = function (point) {
          this.worldTransform.applyInverse(point, tempPoint$1);
          var width = this._width;
          var height = this._height;
          var x1 = -width * this.anchor._x;
          if (tempPoint$1.x >= x1 && tempPoint$1.x < x1 + width) {
              var y1 = -height * this.anchor._y;
              if (tempPoint$1.y >= y1 && tempPoint$1.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 (options) {
          _super.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 {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
       */
      TilingSprite.from = function (source, options) {
          var texture = (source instanceof Texture)
              ? source
              : Texture.from(source, options);
          return new TilingSprite(texture, options.width, options.height);
      };
      Object.defineProperty(TilingSprite.prototype, "width", {
          /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */
          get: function () {
              return this._width;
          },
          set: function (value) {
              this._width = value;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(TilingSprite.prototype, "height", {
          /** The height of the TilingSprite, setting this will actually modify the scale to achieve the value set. */
          get: function () {
              return this._height;
          },
          set: function (value) {
              this._height = value;
          },
          enumerable: false,
          configurable: true
      });
      return TilingSprite;
  }(Sprite));

  var fragmentSimpleSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-Simple-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n    vec4 texSample = texture2D(uSampler, vTextureCoord);\n    gl_FragColor = texSample * uColor;\n}\n";

  var gl1VertexSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nattribute 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 gl1FragmentSrc = "#version 100\n#ifdef GL_EXT_shader_texture_lod\n    #extension GL_EXT_shader_texture_lod : enable\n#endif\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nvarying 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 + ceil(uClampOffset - vTextureCoord);\n    coord = (uMapCoord * vec3(coord, 1.0)).xy;\n    vec2 unclamped = coord;\n    coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n    #ifdef GL_EXT_shader_texture_lod\n        vec4 texSample = unclamped == coord\n            ? texture2D(uSampler, coord) \n            : texture2DLodEXT(uSampler, coord, 0);\n    #else\n        vec4 texSample = texture2D(uSampler, coord);\n    #endif\n\n    gl_FragColor = texSample * uColor;\n}\n";

  var gl2VertexSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-300\n\nprecision lowp float;\n\nin vec2 aVertexPosition;\nin vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nout 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 gl2FragmentSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nin vec2 vTextureCoord;\n\nout vec4 fragmentColor;\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 + ceil(uClampOffset - vTextureCoord);\n    coord = (uMapCoord * vec3(coord, 1.0)).xy;\n    vec2 unclamped = coord;\n    coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n    vec4 texSample = texture(uSampler, coord, unclamped == coord ? 0.0f : -32.0f);// lod-bias very negative to force lod 0\n\n    fragmentColor = texSample * uColor;\n}\n";

  var tempMat$1 = new Matrix();
  /**
   * WebGL renderer plugin for tiling sprites
   *
   * @class
   * @memberof PIXI
   * @extends PIXI.ObjectRenderer
   */
  var TilingSpriteRenderer = /** @class */ (function (_super) {
      __extends$9(TilingSpriteRenderer, _super);
      /**
       * constructor for renderer
       *
       * @param {PIXI.Renderer} renderer - The renderer this tiling awesomeness works for.
       */
      function TilingSpriteRenderer(renderer) {
          var _this = _super.call(this, renderer) || this;
          // WebGL version is not available during initialization!
          renderer.runners.contextChange.add(_this);
          _this.quad = new QuadUv();
          /**
           * The WebGL state in which this renderer will work.
           *
           * @member {PIXI.State}
           * @readonly
           */
          _this.state = State.for2d();
          return _this;
      }
      /**
       * Creates shaders when context is initialized.
       */
      TilingSpriteRenderer.prototype.contextChange = function () {
          var renderer = this.renderer;
          var uniforms = { globals: renderer.globalUniforms };
          this.simpleShader = Shader.from(gl1VertexSrc, fragmentSimpleSrc, uniforms);
          this.shader = renderer.context.webGLVersion > 1
              ? Shader.from(gl2VertexSrc, gl2FragmentSrc, uniforms)
              : Shader.from(gl1VertexSrc, gl1FragmentSrc, uniforms);
      };
      /**
       * @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);
          var anchorX = ts.uvRespectAnchor ? ts.anchor.x : 0;
          var anchorY = ts.uvRespectAnchor ? ts.anchor.y : 0;
          vertices = quad.uvs;
          vertices[0] = vertices[6] = -anchorX;
          vertices[1] = vertices[3] = -anchorY;
          vertices[2] = vertices[4] = 1.0 - anchorX;
          vertices[5] = vertices[7] = 1.0 - anchorY;
          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 === exports.WRAP_MODES.CLAMP) {
                      baseTex.wrapMode = exports.WRAP_MODES.REPEAT;
                  }
              }
              else {
                  isSimple = baseTex.wrapMode !== exports.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$1.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$1.invert();
          if (isSimple) {
              tempMat$1.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$1.toArray(true);
          shader.uniforms.uColor = 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 = correctBlendMode(ts.blendMode, baseTex.alphaMode);
          renderer.state.set(this.state);
          renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0);
      };
      return TilingSpriteRenderer;
  }(ObjectRenderer));

  /*!
   * @pixi/mesh - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/mesh is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$a = function(d, b) {
      extendStatics$a = 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$a(d, b);
  };

  function __extends$a(d, b) {
      extendStatics$a(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.
   *
   * @memberof PIXI
   */
  var MeshBatchUvs = /** @class */ (function () {
      /**
       * @param uvBuffer - Buffer with normalized uv's
       * @param uvMatrix - Material UV matrix
       */
      function MeshBatchUvs(uvBuffer, uvMatrix) {
          this.uvBuffer = uvBuffer;
          this.uvMatrix = uvMatrix;
          this.data = null;
          this._bufferUpdateId = -1;
          this._textureUpdateId = -1;
          this._updateID = 0;
      }
      /**
       * Updates
       *
       * @param forceUpdate - force the update
       */
      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$2 = new Point();
  var tempPolygon = new 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 your 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!
   *
   * @memberof PIXI
   */
  var Mesh = /** @class */ (function (_super) {
      __extends$a(Mesh, _super);
      /**
       * @param geometry - The geometry the mesh will use.
       * @param {PIXI.MeshMaterial} shader - The shader the mesh will use.
       * @param 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 drawMode - The drawMode, can be any of the {@link PIXI.DRAW_MODES} constants.
       */
      function Mesh(geometry, shader, state, drawMode) {
          if (drawMode === void 0) { drawMode = exports.DRAW_MODES.TRIANGLES; }
          var _this = _super.call(this) || this;
          _this.geometry = geometry;
          _this.shader = shader;
          _this.state = state || State.for2d();
          _this.drawMode = drawMode;
          _this.start = 0;
          _this.size = 0;
          _this.uvs = null;
          _this.indices = null;
          _this.vertexData = new Float32Array(1);
          _this.vertexDirty = -1;
          _this._transformID = -1;
          _this._roundPixels = settings.ROUND_PIXELS;
          _this.batchUvs = null;
          return _this;
      }
      Object.defineProperty(Mesh.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 objects.
           */
          get: function () {
              return this._geometry;
          },
          set: function (value) {
              if (this._geometry === value) {
                  return;
              }
              if (this._geometry) {
                  this._geometry.refCount--;
                  if (this._geometry.refCount === 0) {
                      this._geometry.dispose();
                  }
              }
              this._geometry = value;
              if (this._geometry) {
                  this._geometry.refCount++;
              }
              this.vertexDirty = -1;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Mesh.prototype, "uvBuffer", {
          /**
           * To change mesh uv's, change its uvBuffer data and increment its _updateID.
           *
           * @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.
           *
           * @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}. */
          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.
           *
           * @default PIXI.BLEND_MODES.NORMAL;
           */
          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}
           *
           * @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.
           *
           * Null for non-MeshMaterial shaders
           *
           * @default 0xFFFFFF
           */
          get: function () {
              return 'tint' in this.shader ? this.shader.tint : null;
          },
          set: function (value) {
              this.shader.tint = value;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(Mesh.prototype, "texture", {
          /**
           * The texture that the Mesh uses.
           *
           * Null for non-MeshMaterial shaders
           */
          get: function () {
              return 'texture' in this.shader ? this.shader.texture : null;
          },
          set: function (value) {
              this.shader.texture = value;
          },
          enumerable: false,
          configurable: true
      });
      /**
       * Standard renderer draw.
       *
       * @param renderer - Instance to renderer.
       */
      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;
          var shader = this.shader;
          // TODO benchmark check for attribute size..
          if (shader.batchable
              && this.drawMode === exports.DRAW_MODES.TRIANGLES
              && vertices.length < Mesh.BATCHABLE_SIZE * 2) {
              this._renderToBatch(renderer);
          }
          else {
              this._renderDefault(renderer);
          }
      };
      /**
       * Standard non-batching way of rendering.
       *
       * @param renderer - Instance to renderer.
       */
      Mesh.prototype._renderDefault = function (renderer) {
          var shader = this.shader;
          shader.alpha = this.worldAlpha;
          if (shader.update) {
              shader.update();
          }
          renderer.batch.flush();
          // bind and sync uniforms..
          shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true);
          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);
      };
      /**
       * Rendering by using the Batch system.
       *
       * @param renderer - Instance to renderer.
       */
      Mesh.prototype._renderToBatch = function (renderer) {
          var geometry = this.geometry;
          var shader = this.shader;
          if (shader.uvMatrix) {
              shader.uvMatrix.update();
              this.calculateUvs();
          }
          // set properties for batching..
          this.calculateVertices();
          this.indices = geometry.indexBuffer.data;
          this._tintRGB = shader._tintRGB;
          this._texture = 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. */
      Mesh.prototype.calculateVertices = function () {
          var geometry = this.geometry;
          var verticesBuffer = geometry.buffers[0];
          var vertices = verticesBuffer.data;
          var vertexDirtyId = verticesBuffer._updateID;
          if (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) {
              var resolution = settings.RESOLUTION;
              for (var i = 0; i < vertexData.length; ++i) {
                  vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution);
              }
          }
          this.vertexDirty = vertexDirtyId;
      };
      /** Updates uv field based on from geometry uv's or batchUvs. */
      Mesh.prototype.calculateUvs = function () {
          var geomUvs = this.geometry.buffers[1];
          var shader = this.shader;
          if (!shader.uvMatrix.isSimple) {
              if (!this.batchUvs) {
                  this.batchUvs = new MeshBatchUvs(geomUvs, shader.uvMatrix);
              }
              this.batchUvs.update();
              this.uvs = this.batchUvs.data;
          }
          else {
              this.uvs = geomUvs.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.
       */
      Mesh.prototype._calculateBounds = function () {
          this.calculateVertices();
          this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length);
      };
      /**
       * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES.
       *
       * @param point - The point to test.
       * @return - The result of the test.
       */
      Mesh.prototype.containsPoint = function (point) {
          if (!this.getBounds().contains(point.x, point.y)) {
              return false;
          }
          this.worldTransform.applyInverse(point, tempPoint$2);
          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$2.x, tempPoint$2.y)) {
                  return true;
              }
          }
          return false;
      };
      Mesh.prototype.destroy = function (options) {
          _super.prototype.destroy.call(this, options);
          if (this._cachedTexture) {
              this._cachedTexture.destroy();
              this._cachedTexture = null;
          }
          this.geometry = null;
          this.shader = null;
          this.state = null;
          this.uvs = null;
          this.indices = null;
          this.vertexData = null;
      };
      /**
       * The maximum number of vertices to consider batchable. Generally, the complexity
       * of the geometry.
       */
      Mesh.BATCHABLE_SIZE = 100;
      return Mesh;
  }(Container));

  var fragment$2 = "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 vertex$2 = "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";

  /**
   * Slightly opinionated default shader for PixiJS 2D objects.
   *
   * @memberof PIXI
   */
  var MeshMaterial = /** @class */ (function (_super) {
      __extends$a(MeshMaterial, _super);
      /**
       * @param uSampler - Texture that material uses to render.
       * @param 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.
       */
      function MeshMaterial(uSampler, options) {
          var _this = this;
          var uniforms = {
              uSampler: uSampler,
              alpha: 1,
              uTextureMatrix: 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 || Program.from(vertex$2, fragment$2), uniforms) || this;
          _this._colorDirty = false;
          _this.uvMatrix = new TextureMatrix(uSampler);
          _this.batchable = options.program === undefined;
          _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. */
          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
           */
          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.
           *
           * @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
      });
      /**
       * Gets called automatically by the Mesh. Intended to be overridden for custom
       * {@link MeshMaterial} objects.
       */
      MeshMaterial.prototype.update = function () {
          if (this._colorDirty) {
              this._colorDirty = false;
              var baseTexture = this.texture.baseTexture;
              premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode);
          }
          if (this.uvMatrix.update()) {
              this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord;
          }
      };
      return MeshMaterial;
  }(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]);
   *
   * ```
   *
   * @memberof PIXI
   */
  var MeshGeometry = /** @class */ (function (_super) {
      __extends$a(MeshGeometry, _super);
      /**
       * @param {Float32Array|number[]} [vertices] - Positional data on geometry.
       * @param {Float32Array|number[]} [uvs] - Texture UVs.
       * @param {Uint16Array|number[]} [index] - IndexBuffer
       */
      function MeshGeometry(vertices, uvs, index) {
          var _this = _super.call(this) || this;
          var verticesBuffer = new Buffer(vertices);
          var uvsBuffer = new Buffer(uvs, true);
          var indexBuffer = new Buffer(index, true, true);
          _this.addAttribute('aVertexPosition', verticesBuffer, 2, false, exports.TYPES.FLOAT)
              .addAttribute('aTextureCoord', uvsBuffer, 2, false, exports.TYPES.FLOAT)
              .addIndex(indexBuffer);
          _this._updateId = -1;
          return _this;
      }
      Object.defineProperty(MeshGeometry.prototype, "vertexDirtyId", {
          /**
           * If the vertex position is updated.
           *
           * @readonly
           * @private
           */
          get: function () {
              return this.buffers[0]._updateID;
          },
          enumerable: false,
          configurable: true
      });
      return MeshGeometry;
  }(Geometry));

  /*!
   * @pixi/text-bitmap - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/text-bitmap is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$b = function(d, b) {
      extendStatics$b = 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$b(d, b);
  };

  function __extends$b(d, b) {
      extendStatics$b(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.
   *
   * @memberof PIXI
   */
  var BitmapFontData = /** @class */ (function () {
      function BitmapFontData() {
          this.info = [];
          this.common = [];
          this.page = [];
          this.char = [];
          this.kerning = [];
          this.distanceField = [];
      }
      return BitmapFontData;
  }());

  /**
   * BitmapFont format that's Text-based.
   *
   * @private
   */
  var TextFormat = /** @class */ (function () {
      function TextFormat() {
      }
      /**
       * Check if resource refers to txt font data.
       *
       * @param data
       * @return - True if resource could be treated as font data, false otherwise.
       */
      TextFormat.test = function (data) {
          return typeof data === 'string' && data.indexOf('info face=') === 0;
      };
      /**
       * Convert text font data to a javascript object.
       *
       * @param txt - Raw string data to be converted
       * @return - 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: [],
              kernings: [],
              distanceField: [],
          };
          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),
          }); });
          rawData.distanceField.forEach(function (df) { return font.distanceField.push({
              distanceRange: parseInt(df.distanceRange, 10),
              fieldType: df.fieldType,
          }); });
          return font;
      };
      return TextFormat;
  }());

  /**
   * BitmapFont format that's XML-based.
   *
   * @private
   */
  var XMLFormat = /** @class */ (function () {
      function XMLFormat() {
      }
      /**
       * Check if resource refers to xml font data.
       *
       * @param data
       * @return - True if resource could be treated as font data, false otherwise.
       */
      XMLFormat.test = function (data) {
          return data instanceof XMLDocument
              && data.getElementsByTagName('page').length
              && data.getElementsByTagName('info')[0].getAttribute('face') !== null;
      };
      /**
       * Convert the XML into BitmapFontData that we can use.
       *
       * @param xml
       * @return - 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');
          var distanceField = xml.getElementsByTagName('distanceField');
          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),
              });
          }
          for (var i = 0; i < distanceField.length; i++) {
              data.distanceField.push({
                  fieldType: distanceField[i].getAttribute('fieldType'),
                  distanceRange: parseInt(distanceField[i].getAttribute('distanceRange'), 10),
              });
          }
          return data;
      };
      return XMLFormat;
  }());

  /**
   * BitmapFont format that's XML-based.
   *
   * @private
   */
  var XMLStringFormat = /** @class */ (function () {
      function XMLStringFormat() {
      }
      /**
       * Check if resource refers to text xml font data.
       *
       * @param data
       * @return - True if resource could be treated as font data, false otherwise.
       */
      XMLStringFormat.test = function (data) {
          if (typeof data === 'string' && data.indexOf('<font>') > -1) {
              var xml = new globalThis.DOMParser().parseFromString(data, 'text/xml');
              return XMLFormat.test(xml);
          }
          return false;
      };
      /**
       * Convert the text XML into BitmapFontData that we can use.
       *
       * @param xmlTxt
       * @return - Data to use for BitmapFont
       */
      XMLStringFormat.parse = function (xmlTxt) {
          var xml = new globalThis.DOMParser().parseFromString(xmlTxt, 'text/xml');
          return XMLFormat.parse(xml);
      };
      return XMLStringFormat;
  }());

  // Registered formats, maybe make this extensible in the future?
  var formats = [
      TextFormat,
      XMLFormat,
      XMLStringFormat ];
  /**
   * 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 = (canvas.width / resolution) - dropShadowCorrection - (padding * 2);
      var height = (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 === 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 = 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;
      if (style.dropShadow) {
          var dropShadowColor = style.dropShadowColor;
          var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor));
          var dropShadowBlur = style.dropShadowBlur * resolution;
          var dropShadowDistance = style.dropShadowDistance * resolution;
          context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")";
          context.shadowBlur = dropShadowBlur;
          context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance;
          context.shadowOffsetY = Math.sin(style.dropShadowAngle) * dropShadowDistance;
      }
      else {
          context.shadowColor = 'black';
          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(1, 0, 0, 1, 0, 0); // defaults needed for older browsers (e.g. Opera 29)
      context.fillStyle = 'rgba(0, 0, 0, 0)';
  }

  /**
   * Ponyfill for IE because it doesn't support `Array.from`
   * @private
   */
  function splitTextToCharacters(text) {
      return Array.from ? Array.from(text) : text.split('');
  }

  /**
   * 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, splitTextToCharacters(item));
          }
      }
      if (result.length === 0) {
          throw new Error('[BitmapFont]: Empty set when resolving characters.');
      }
      return result;
  }

  /**
   * Ponyfill for IE because it doesn't support `codePointAt`
   * @private
   */
  function extractCharCode(str) {
      return str.codePointAt ? str.codePointAt(0) : str.charCodeAt(0);
  }

  /**
   * BitmapFont represents a typeface available for use with the BitmapText class. Use the `install`
   * method for adding a font to be used.
   *
   * @memberof PIXI
   */
  var BitmapFont = /** @class */ (function () {
      /**
       * @param data
       * @param textures
       * @param ownsTextures - Setting to `true` will destroy page textures
       *        when the font is uninstalled.
       */
      function BitmapFont(data, textures, ownsTextures) {
          var _a, _b;
          var info = data.info[0];
          var common = data.common[0];
          var page = data.page[0];
          var distanceField = data.distanceField[0];
          var res = getResolutionOfUrl(page.file);
          var pageTextures = {};
          this._ownsTextures = ownsTextures;
          this.font = info.face;
          this.size = info.size;
          this.lineHeight = common.lineHeight / res;
          this.chars = {};
          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 _c = data.page[i], id = _c.id, file = _c.file;
              pageTextures[id] = textures instanceof Array
                  ? textures[i] : textures[file];
              // only MSDF and SDF fonts need no-premultiplied-alpha
              if ((distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) && distanceField.fieldType !== 'none') {
                  pageTextures[id].baseTexture.alphaMode = exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA;
              }
          }
          // parse letters
          for (var i = 0; i < data.char.length; i++) {
              var _d = data.char[i], id = _d.id, page_1 = _d.page;
              var _e = data.char[i], x = _e.x, y = _e.y, width = _e.width, height = _e.height, xoffset = _e.xoffset, yoffset = _e.yoffset, xadvance = _e.xadvance;
              x /= res;
              y /= res;
              width /= res;
              height /= res;
              xoffset /= res;
              yoffset /= res;
              xadvance /= res;
              var rect = new 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 Texture(pageTextures[page_1].baseTexture, rect),
                  page: page_1,
              };
          }
          // parse kernings
          for (var i = 0; i < data.kerning.length; i++) {
              var _f = data.kerning[i], first = _f.first, second = _f.second, amount = _f.amount;
              first /= res;
              second /= res;
              amount /= res;
              if (this.chars[second]) {
                  this.chars[second].kerning[first] = amount;
              }
          }
          // Store distance field information
          this.distanceFieldRange = distanceField === null || distanceField === void 0 ? void 0 : distanceField.distanceRange;
          this.distanceFieldType = (_b = (_a = distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : 'none';
      }
      /** Remove references to created glyph textures. */
      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) {
              if (this._ownsTextures) {
                  this.pageTextures[id].destroy(true);
              }
              this.pageTextures[id] = null;
          }
          // Set readonly null.
          this.chars = null;
          this.pageTextures = null;
      };
      /**
       * Register a new bitmap font.
       *
       * @param data - The
       *        characters map that could be provided as xml or raw string.
       * @param textures - List of textures for each page.
       * @param ownsTextures - Set to `true` to destroy page textures
       *        when the font is uninstalled. By default fonts created with
       *        `BitmapFont.from` or from the `BitmapFontLoader` are `true`.
       * @return {PIXI.BitmapFont} Result font object with font, size, lineHeight
       *         and char fields.
       */
      BitmapFont.install = function (data, textures, ownsTextures) {
          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 Texture) {
              textures = [textures];
          }
          var font = new BitmapFont(fontData, textures, ownsTextures);
          BitmapFont.available[font.font] = font;
          return font;
      };
      /**
       * Remove bitmap font by name.
       *
       * @param name - Name of the font to uninstall.
       */
      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 name - The name of the custom font to use with BitmapText.
       * @param style - Style options to render with BitmapFont.
       * @param 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 Font generated by style options.
       * @example
       * PIXI.BitmapFont.from("TitleFont", {
       *     fontFamily: "Arial",
       *     fontSize: 12,
       *     strokeThickness: 2,
       *     fill: "purple"
       * });
       *
       * const title = new PIXI.BitmapText("This is the title", { fontName: "TitleFont" });
       */
      BitmapFont.from = function (name, textStyle, options) {
          if (!name) {
              throw new Error('[BitmapFont] Property `name` is required.');
          }
          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 TextStyle ? textStyle : new 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 BaseTexture(canvas, { resolution: resolution });
                  textures.push(new Texture(baseTexture));
                  fontData.page.push({
                      id: textures.length - 1,
                      file: '',
                  });
              }
              // Measure glyph dimensions
              var metrics = 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 = extractCharCode(metrics.text);
              // 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);
          }
          // Brute-force kerning info, this can be expensive b/c it's an O(n²),
          // but we're using measureText which is native and fast.
          for (var i = 0, len = charsList.length; i < len; i++) {
              var first = charsList[i];
              for (var j = 0; j < len; j++) {
                  var second = charsList[j];
                  var c1 = context.measureText(first).width;
                  var c2 = context.measureText(second).width;
                  var total = context.measureText(first + second).width;
                  var amount = total - (c1 + c2);
                  if (amount) {
                      fontData.kerning.push({
                          first: extractCharCode(first),
                          second: extractCharCode(second),
                          amount: amount,
                      });
                  }
              }
          }
          var font = new BitmapFont(fontData, textures, true);
          // Make it easier to replace a font
          if (BitmapFont.available[name] !== undefined) {
              BitmapFont.uninstall(name);
          }
          BitmapFont.available[name] = font;
          return font;
      };
      /**
       * This character set includes all the letters in the alphabet (both lower- and upper- case).
       *
       * @type {string[][]}
       * @example
       * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.ALPHA })
       */
      BitmapFont.ALPHA = [['a', 'z'], ['A', 'Z'], ' '];
      /**
       * This character set includes all decimal digits (from 0 to 9).
       *
       * @type {string[][]}
       * @example
       * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.NUMERIC })
       */
      BitmapFont.NUMERIC = [['0', '9']];
      /**
       * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`.
       *
       * @type {string[][]}
       */
      BitmapFont.ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' '];
      /**
       * This character set consists of all the ASCII table.
       *
       * @member {string[][]}
       * @see http://www.asciitable.com/
       */
      BitmapFont.ASCII = [[' ', '~']];
      /**
       * Collection of default options when using `BitmapFont.from`.
       *
       * @property {number} resolution=1
       * @property {number} textureWidth=512
       * @property {number} textureHeight=512
       * @property {number} padding=4
       * @property {string|string[]|string[][]} chars = PIXI.BitmapFont.ALPHANUMERIC
       */
      BitmapFont.defaultOptions = {
          resolution: 1,
          textureWidth: 512,
          textureHeight: 512,
          padding: 4,
          chars: BitmapFont.ALPHANUMERIC,
      };
      /** Collection of available/installed fonts. */
      BitmapFont.available = {};
      return BitmapFont;
  }());

  var msdfFrag = "// Pixi texture info\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\n\r\n// Tint\r\nuniform vec4 uColor;\r\n\r\n// on 2D applications fwidth is screenScale / glyphAtlasScale * distanceFieldRange\r\nuniform float uFWidth;\r\n\r\nvoid main(void) {\r\n\r\n  // To stack MSDF and SDF we need a non-pre-multiplied-alpha texture.\r\n  vec4 texColor = texture2D(uSampler, vTextureCoord);\r\n\r\n  // MSDF\r\n  float median = texColor.r + texColor.g + texColor.b -\r\n                  min(texColor.r, min(texColor.g, texColor.b)) -\r\n                  max(texColor.r, max(texColor.g, texColor.b));\r\n  // SDF\r\n  median = min(median, texColor.a);\r\n\r\n  float screenPxDistance = uFWidth * (median - 0.5);\r\n  float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);\r\n\r\n  // NPM Textures, NPM outputs\r\n  gl_FragColor = vec4(uColor.rgb, uColor.a * alpha);\r\n\r\n}\r\n";

  var msdfVert = "// Mesh material default fragment\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTextureMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n    gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n    vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n";

  // If we ever need more than two pools, please make a Dict or something better.
  var pageMeshDataDefaultPageMeshData = [];
  var pageMeshDataMSDFPageMeshData = [];
  var charRenderDataPool = [];
  /**
   * 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.
   *
   * You can also use SDF, MSDF and MTSDF BitmapFonts for vector-like scaling appearance provided by:
   * https://github.com/soimy/msdf-bmfont-xml for SDF and MSDF fnt files or
   * https://github.com/Chlumsky/msdf-atlas-gen for SDF, MSDF and MTSDF json files
   *
   * 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!", {
   *   fontName: "Desyrel",
   *   fontSize: 35,
   *   align: "right"
   * });
   * ```
   *
   * @memberof PIXI
   */
  var BitmapText = /** @class */ (function (_super) {
      __extends$b(BitmapText, _super);
      /**
       * @param text - A string that you would like the text to display.
       * @param 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', 'right' or 'justify'),
       *      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;
          /**
           * Private tracker for the current tint.
           *
           * @private
           */
          _this._tint = 0xFFFFFF;
          // 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 + "\"");
          }
          _this._activePagesMeshData = [];
          _this._textWidth = 0;
          _this._textHeight = 0;
          _this._align = align;
          _this._tint = tint;
          _this._fontName = fontName;
          _this._fontSize = fontSize || BitmapFont.available[fontName].size;
          _this._text = text;
          _this._maxWidth = maxWidth;
          _this._maxLineHeight = 0;
          _this._letterSpacing = letterSpacing;
          _this._anchor = new ObservablePoint(function () { _this.dirty = true; }, _this, 0, 0);
          _this._roundPixels = settings.ROUND_PIXELS;
          _this.dirty = true;
          _this._textureCache = {};
          return _this;
      }
      /**
       * Renders text and updates it when needed. This should only be called
       * if the BitmapFont is regenerated.
       */
      BitmapText.prototype.updateText = function () {
          var _a;
          var data = BitmapFont.available[this._fontName];
          var scale = this._fontSize / data.size;
          var pos = new Point();
          var chars = [];
          var lineWidths = [];
          var lineSpaces = [];
          var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' ';
          var charsInput = splitTextToCharacters(text);
          var maxWidth = this._maxWidth * data.size / this._fontSize;
          var pageMeshDataPool = data.distanceFieldType === 'none'
              ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData;
          var prevCharCode = null;
          var lastLineWidth = 0;
          var maxLineWidth = 0;
          var line = 0;
          var lastBreakPos = -1;
          var lastBreakWidth = 0;
          var spacesRemoved = 0;
          var maxLineHeight = 0;
          var spaceCount = 0;
          for (var i = 0; i < charsInput.length; i++) {
              var char = charsInput[i];
              var charCode = extractCharCode(char);
              if ((/(?:\s)/).test(char)) {
                  lastBreakPos = i;
                  lastBreakWidth = lastLineWidth;
                  spaceCount++;
              }
              if (char === '\r' || char === '\n') {
                  lineWidths.push(lastLineWidth);
                  lineSpaces.push(-1);
                  maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
                  ++line;
                  ++spacesRemoved;
                  pos.x = 0;
                  pos.y += data.lineHeight;
                  prevCharCode = null;
                  spaceCount = 0;
                  continue;
              }
              var charData = data.chars[charCode];
              if (!charData) {
                  continue;
              }
              if (prevCharCode && charData.kerning[prevCharCode]) {
                  pos.x += charData.kerning[prevCharCode];
              }
              var charRenderData = charRenderDataPool.pop() || {
                  texture: Texture.EMPTY,
                  line: 0,
                  charCode: 0,
                  prevSpaces: 0,
                  position: new 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;
              charRenderData.prevSpaces = spaceCount;
              chars.push(charRenderData);
              lastLineWidth = charRenderData.position.x + Math.max(charData.xAdvance, charData.texture.orig.width);
              pos.x += charData.xAdvance + this._letterSpacing;
              maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height));
              prevCharCode = charCode;
              if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) {
                  ++spacesRemoved;
                  removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos);
                  i = lastBreakPos;
                  lastBreakPos = -1;
                  lineWidths.push(lastBreakWidth);
                  lineSpaces.push(chars.length > 0 ? chars[chars.length - 1].prevSpaces : 0);
                  maxLineWidth = Math.max(maxLineWidth, lastBreakWidth);
                  line++;
                  pos.x = 0;
                  pos.y += data.lineHeight;
                  prevCharCode = null;
                  spaceCount = 0;
              }
          }
          var lastChar = charsInput[charsInput.length - 1];
          if (lastChar !== '\r' && lastChar !== '\n') {
              if ((/(?:\s)/).test(lastChar)) {
                  lastLineWidth = lastBreakWidth;
              }
              lineWidths.push(lastLineWidth);
              maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
              lineSpaces.push(-1);
          }
          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;
              }
              else if (this._align === 'justify') {
                  alignOffset = lineSpaces[i] < 0 ? 0 : (maxLineWidth - lineWidths[i]) / lineSpaces[i];
              }
              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 MeshGeometry();
                      var material = void 0;
                      var meshBlendMode = void 0;
                      if (data.distanceFieldType === 'none') {
                          material = new MeshMaterial(Texture.EMPTY);
                          meshBlendMode = exports.BLEND_MODES.NORMAL;
                      }
                      else {
                          material = new MeshMaterial(Texture.EMPTY, { program: Program.from(msdfVert, msdfFrag), uniforms: { uFWidth: 0 } });
                          meshBlendMode = exports.BLEND_MODES.NORMAL_NPM;
                      }
                      var mesh = new Mesh(geometry, material);
                      mesh.blendMode = meshBlendMode;
                      pageMeshData = {
                          index: 0,
                          indexCount: 0,
                          vertexCount: 0,
                          uvsCount: 0,
                          total: 0,
                          mesh: mesh,
                          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..
                  var _textureCache = this._textureCache;
                  _textureCache[baseTextureUid] = _textureCache[baseTextureUid] || new Texture(texture.baseTexture);
                  pageMeshData.mesh.texture = _textureCache[baseTextureUid];
                  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.BATCHABLE_SIZE * 2) {
                  pageMeshData.vertices = new Float32Array(4 * 2 * total);
                  pageMeshData.uvs = new Float32Array(4 * 2 * total);
                  pageMeshData.indices = new Uint16Array(6 * total);
              }
              else {
                  var total_1 = pageMeshData.total;
                  var vertices = pageMeshData.vertices;
                  // Clear the garbage at the end of the vertices buffer. This will prevent the bounds miscalculation.
                  for (var i_1 = total_1 * 4 * 2; i_1 < vertices.length; i_1++) {
                      vertices[i_1] = 0;
                  }
              }
              // 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 offset = char.position.x + (lineAlignOffsets[char.line] * (this._align === 'justify' ? char.prevSpaces : 1));
              if (this._roundPixels) {
                  offset = Math.round(offset);
              }
              var xPos = offset * 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_2 = 0; i_2 < pageMeshData.total; i_2++) {
                      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]);
          }
      };
      BitmapText.prototype.updateTransform = function () {
          this.validate();
          this.containerUpdateTransform();
      };
      BitmapText.prototype._render = function (renderer) {
          // Update the uniform
          var _a = BitmapFont.available[this._fontName], distanceFieldRange = _a.distanceFieldRange, distanceFieldType = _a.distanceFieldType, size = _a.size;
          if (distanceFieldType !== 'none') {
              // Inject the shader code with the correct value
              var _b = this.worldTransform, a = _b.a, b = _b.b, c = _b.c, d = _b.d;
              var dx = Math.sqrt((a * a) + (b * b));
              var dy = Math.sqrt((c * c) + (d * d));
              var worldScale = (Math.abs(dx) + Math.abs(dy)) / 2;
              var fontScale = this._fontSize / size;
              for (var _i = 0, _c = this._activePagesMeshData; _i < _c.length; _i++) {
                  var mesh = _c[_i];
                  mesh.mesh.shader.uniforms.uFWidth = worldScale * distanceFieldRange * fontScale * renderer.resolution;
              }
          }
          _super.prototype._render.call(this, renderer);
      };
      /**
       * Validates text before calling parent's getLocalBounds
       *
       * @return - The rectangular bounding area
       */
      BitmapText.prototype.getLocalBounds = function () {
          this.validate();
          return _super.prototype.getLocalBounds.call(this);
      };
      /**
       * Updates text when needed
       *
       * @private
       */
      BitmapText.prototype.validate = function () {
          if (this.dirty) {
              this.updateText();
              this.dirty = false;
          }
      };
      Object.defineProperty(BitmapText.prototype, "tint", {
          /**
           * The tint of the BitmapText object.
           *
           * @default 0xffffff
           */
          get: function () {
              return this._tint;
          },
          set: function (value) {
              if (this._tint === value)
                  { return; }
              this._tint = value;
              for (var i = 0; i < this._activePagesMeshData.length; i++) {
                  this._activePagesMeshData[i].mesh.tint = value;
              }
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BitmapText.prototype, "align", {
          /**
           * The alignment of the BitmapText object.
           *
           * @member {string}
           * @default 'left'
           */
          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", {
          /** The name of the BitmapFont. */
          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. */
          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", {
          /**
           * 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.
           */
          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 text of the BitmapText object. */
          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", {
          /**
           * 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.
           */
          get: function () {
              return this._maxWidth;
          },
          set: function (value) {
              if (this._maxWidth === value) {
                  return;
              }
              this._maxWidth = value;
              this.dirty = true;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BitmapText.prototype, "maxLineHeight", {
          /**
           * The max line height. This is useful when trying to use the total height of the Text,
           * i.e. when trying to vertically align.
           *
           * @readonly
           */
          get: function () {
              this.validate();
              return this._maxLineHeight;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BitmapText.prototype, "textWidth", {
          /**
           * The width of the overall text, different from fontSize,
           * which is defined in the style object.
           *
           * @readonly
           */
          get: function () {
              this.validate();
              return this._textWidth;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BitmapText.prototype, "letterSpacing", {
          /** Additional space between characters. */
          get: function () {
              return this._letterSpacing;
          },
          set: function (value) {
              if (this._letterSpacing !== value) {
                  this._letterSpacing = value;
                  this.dirty = true;
              }
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BitmapText.prototype, "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}
           *
           * @default PIXI.settings.ROUND_PIXELS
           */
          get: function () {
              return this._roundPixels;
          },
          set: function (value) {
              if (value !== this._roundPixels) {
                  this._roundPixels = value;
                  this.dirty = true;
              }
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BitmapText.prototype, "textHeight", {
          /**
           * The height of the overall text, different from fontSize,
           * which is defined in the style object.
           *
           * @readonly
           */
          get: function () {
              this.validate();
              return this._textHeight;
          },
          enumerable: false,
          configurable: true
      });
      BitmapText.prototype.destroy = function (options) {
          var _textureCache = this._textureCache;
          for (var id in _textureCache) {
              var texture = _textureCache[id];
              texture.destroy();
              delete _textureCache[id];
          }
          this._textureCache = null;
          _super.prototype.destroy.call(this, options);
      };
      BitmapText.styleDefaults = {
          align: 'left',
          tint: 0xFFFFFF,
          maxWidth: 0,
          letterSpacing: 0,
      };
      return BitmapText;
  }(Container));

  /**
   * {@link PIXI.Loader Loader} middleware for loading
   * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}.
   *
   * @memberof PIXI
   */
  var BitmapFontLoader = /** @class */ (function () {
      function BitmapFontLoader() {
      }
      /**
       * Called when the plugin is installed.
       *
       * @see PIXI.Loader.registerPlugin
       */
      BitmapFontLoader.add = function () {
          exports.LoaderResource.setExtensionXhrType('fnt', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT);
      };
      /**
       * Called after a resource is loaded.
       *
       * @see PIXI.Loader.loaderMiddleware
       * @param {PIXI.LoaderResource} resource
       * @param {function} next
       */
      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, true);
                  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: exports.LoaderResource.LOAD_TYPE.IMAGE,
                      metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata),
                      parentResource: resource,
                  };
                  this.add(url, options, completed);
              }
          }
      };
      /** Get folder path from a resource. */
      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;
      };
      /**
       * Replacement for NodeJS's path.dirname
       *
       * @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;
  }());

  /*!
   * @pixi/filter-alpha - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/filter-alpha is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$c = function(d, b) {
      extendStatics$c = 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$c(d, b);
  };

  function __extends$c(d, b) {
      extendStatics$c(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  var fragment$3 = "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.
   *
   * @memberof PIXI.filters
   */
  var AlphaFilter = /** @class */ (function (_super) {
      __extends$c(AlphaFilter, _super);
      /**
       * @param alpha - 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, defaultVertex$2, fragment$3, { uAlpha: 1 }) || this;
          _this.alpha = alpha;
          return _this;
      }
      Object.defineProperty(AlphaFilter.prototype, "alpha", {
          /**
           * Coefficient for alpha multiplication
           *
           * @default 1
           */
          get: function () {
              return this.uniforms.uAlpha;
          },
          set: function (value) {
              this.uniforms.uAlpha = value;
          },
          enumerable: false,
          configurable: true
      });
      return AlphaFilter;
  }(Filter));

  /*!
   * @pixi/filter-blur - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/filter-blur is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$d = function(d, b) {
      extendStatics$d = 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(d, b);
  };

  function __extends$d(d, b) {
      extendStatics$d(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  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;
  }

  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$1 = [
      '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$1;
      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;
  }

  /*!
   * @pixi/constants - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/constants is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */
  /**
   * 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$2;
  (function (ENV) {
      ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY";
      ENV[ENV["WEBGL"] = 1] = "WEBGL";
      ENV[ENV["WEBGL2"] = 2] = "WEBGL2";
  })(ENV$2 || (ENV$2 = {}));
  /**
   * 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$2;
  (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$2 || (RENDERER_TYPE$2 = {}));
  /**
   * 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$2;
  (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$2 || (BUFFER_BITS$2 = {}));
  /**
   * 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$2;
  (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$2 || (BLEND_MODES$2 = {}));
  /**
   * 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$2;
  (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$2 || (DRAW_MODES$2 = {}));
  /**
   * Various GL texture/resources formats.
   *
   * @memberof PIXI
   * @static
   * @name FORMATS
   * @enum {number}
   * @property {number} RGBA=6408
   * @property {number} RGB=6407
   * @property {number} RG=33319
   * @property {number} RED=6403
   * @property {number} RGBA_INTEGER=36249
   * @property {number} RGB_INTEGER=36248
   * @property {number} RG_INTEGER=33320
   * @property {number} RED_INTEGER=36244
   * @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$2;
  (function (FORMATS) {
      FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
      FORMATS[FORMATS["RGB"] = 6407] = "RGB";
      FORMATS[FORMATS["RG"] = 33319] = "RG";
      FORMATS[FORMATS["RED"] = 6403] = "RED";
      FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
      FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
      FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
      FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
      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$2 || (FORMATS$2 = {}));
  /**
   * 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$2;
  (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$2 || (TARGETS$2 = {}));
  /**
   * 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} UNSIGNED_INT=5125
   * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
   * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
   * @property {number} UNSIGNED_INT_24_8=34042
   * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
   * @property {number} BYTE=5120
   * @property {number} SHORT=5122
   * @property {number} INT=5124
   * @property {number} FLOAT=5126
   * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
   * @property {number} HALF_FLOAT=36193
   */
  var TYPES$2;
  (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["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
      TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
      TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
      TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
      TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
      TYPES[TYPES["BYTE"] = 5120] = "BYTE";
      TYPES[TYPES["SHORT"] = 5122] = "SHORT";
      TYPES[TYPES["INT"] = 5124] = "INT";
      TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
      TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
      TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
  })(TYPES$2 || (TYPES$2 = {}));
  /**
   * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
   * WebGL1 works only with FLOAT.
   *
   * @memberof PIXI
   * @static
   * @name SAMPLER_TYPES
   * @enum {number}
   * @property {number} FLOAT=0
   * @property {number} INT=1
   * @property {number} UINT=2
   */
  var SAMPLER_TYPES$2;
  (function (SAMPLER_TYPES) {
      SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
      SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
      SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
  })(SAMPLER_TYPES$2 || (SAMPLER_TYPES$2 = {}));
  /**
   * 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$2;
  (function (SCALE_MODES) {
      SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
      SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
  })(SCALE_MODES$2 || (SCALE_MODES$2 = {}));
  /**
   * 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$2;
  (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$2 || (WRAP_MODES$2 = {}));
  /**
   * 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
   * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
   *   that supports buffering each level-of-detail.
   */
  var MIPMAP_MODES$2;
  (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["ON_MANUAL"] = 3] = "ON_MANUAL";
  })(MIPMAP_MODES$2 || (MIPMAP_MODES$2 = {}));
  /**
   * 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$2;
  (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["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
  })(ALPHA_MODES$2 || (ALPHA_MODES$2 = {}));
  /**
   * Configure whether filter textures are cleared after binding.
   *
   * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
   * this and skip clearing as an optimization.
   *
   * @name CLEAR_MODES
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
   * @property {number} CLEAR - Always clear the filter texture.
   * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
   * @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$2;
  (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$2 || (CLEAR_MODES$2 = {}));
  /**
   * 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$2;
  (function (GC_MODES) {
      GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
      GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
  })(GC_MODES$2 || (GC_MODES$2 = {}));
  /**
   * 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$2;
  (function (PRECISION) {
      PRECISION["LOW"] = "lowp";
      PRECISION["MEDIUM"] = "mediump";
      PRECISION["HIGH"] = "highp";
  })(PRECISION$2 || (PRECISION$2 = {}));
  /**
   * 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$2;
  (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$2 || (MASK_TYPES$2 = {}));
  /**
   * 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$2;
  (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$2 || (MSAA_QUALITY$2 = {}));
  /**
   * Constants for various buffer types in Pixi
   *
   * @see PIXI.BUFFER_TYPE
   *
   * @name BUFFER_TYPE
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
   * @property {number} ARRAY_BUFFER - buffer type for using attribute data
   * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
   */
  var BUFFER_TYPE$2;
  (function (BUFFER_TYPE) {
      BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
      BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
      // NOT YET SUPPORTED
      BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
  })(BUFFER_TYPE$2 || (BUFFER_TYPE$2 = {}));

  /**
   * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object.
   *
   * @memberof PIXI.filters
   */
  var BlurFilterPass = /** @class */ (function (_super) {
      __extends$d(BlurFilterPass, _super);
      /**
       * @param horizontal - Do pass along the x-axis (`true`) or y-axis (`false`).
       * @param strength - The strength of the blur filter.
       * @param quality - The quality of the blur filter.
       * @param resolution - The resolution of the blur filter.
       * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15.
       */
      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.FILTER_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;
      }
      /**
       * Applies the filter.
       *
       * @param filterManager - The manager.
       * @param input - The input target.
       * @param output - The output target.
       * @param clearMode - How to clear
       */
      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);
              }
          }
          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
              }
          }
          // 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$2.CLEAR);
              for (var i = 1; i < this.passes - 1; i++) {
                  filterManager.bindAndClear(flip, CLEAR_MODES$2.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.
           *
           * @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
           * quality bluring but the lower the performance.
           *
           * @default 4
           */
          get: function () {
              return this._quality;
          },
          set: function (value) {
              this._quality = value;
              this.passes = value;
          },
          enumerable: false,
          configurable: true
      });
      return BlurFilterPass;
  }(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.
   *
   * @memberof PIXI.filters
   */
  var BlurFilter = /** @class */ (function (_super) {
      __extends$d(BlurFilter, _super);
      /**
       * @param strength - The strength of the blur filter.
       * @param quality - The quality of the blur filter.
       * @param [resolution=PIXI.settings.FILTER_RESOLUTION] - The resolution of the blur filter.
       * @param kernelSize - 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.FILTER_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;
      }
      /**
       * Applies the filter.
       *
       * @param filterManager - The manager.
       * @param input - The input target.
       * @param output - The output target.
       * @param clearMode - How to clear
       */
      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$2.CLEAR);
              this.blurYFilter.apply(filterManager, renderTarget, output, clearMode);
              filterManager.returnFilterTexture(renderTarget);
          }
          else if (yStrength) {
              this.blurYFilter.apply(filterManager, input, output, clearMode);
          }
          else {
              this.blurXFilter.apply(filterManager, input, output, clearMode);
          }
      };
      BlurFilter.prototype.updatePadding = function () {
          if (this._repeatEdgePixels) {
              this.padding = 0;
          }
          else {
              this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2;
          }
      };
      Object.defineProperty(BlurFilter.prototype, "blur", {
          /**
           * Sets the strength of both the blurX and blurY properties simultaneously
           *
           * @default 2
           */
          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", {
          /**
           * Sets the number of passes for blur. More passes means higher quality bluring.
           *
           * @default 1
           */
          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", {
          /**
           * Sets the strength of the blurX property
           *
           * @default 2
           */
          get: function () {
              return this.blurXFilter.blur;
          },
          set: function (value) {
              this.blurXFilter.blur = value;
              this.updatePadding();
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BlurFilter.prototype, "blurY", {
          /**
           * Sets the strength of the blurY property
           *
           * @default 2
           */
          get: function () {
              return this.blurYFilter.blur;
          },
          set: function (value) {
              this.blurYFilter.blur = value;
              this.updatePadding();
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BlurFilter.prototype, "blendMode", {
          /**
           * Sets the blendmode of the filter
           *
           * @default PIXI.BLEND_MODES.NORMAL
           */
          get: function () {
              return this.blurYFilter.blendMode;
          },
          set: function (value) {
              this.blurYFilter.blendMode = value;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(BlurFilter.prototype, "repeatEdgePixels", {
          /**
           * If set to true the edge of the target will be clamped
           *
           * @default false
           */
          get: function () {
              return this._repeatEdgePixels;
          },
          set: function (value) {
              this._repeatEdgePixels = value;
              this.updatePadding();
          },
          enumerable: false,
          configurable: true
      });
      return BlurFilter;
  }(Filter));

  /*!
   * @pixi/filter-color-matrix - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/filter-color-matrix is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$e = function(d, b) {
      extendStatics$e = 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$e(d, b);
  };

  function __extends$e(d, b) {
      extendStatics$e(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  var fragment$4 = "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 <clement@goodboydigital.com>
   * @memberof PIXI.filters
   */
  var ColorMatrixFilter = /** @class */ (function (_super) {
      __extends$e(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, defaultFilterVertex, fragment$4, uniforms) || this;
          _this.alpha = 1;
          return _this;
      }
      /**
       * Transforms current matrix and set the new one
       *
       * @param {number[]} matrix - 5x4 matrix
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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;
      };
      /**
       * Multiplies two mat5's
       *
       * @private
       * @param out - 5x4 matrix the receiving matrix
       * @param a - 5x4 matrix the first operand
       * @param b - 5x4 matrix the second operand
       * @returns {number[]} 5x4 matrix
       */
      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;
      };
      /**
       * Create a Float32 Array and normalize the offset component to 0-1
       *
       * @param {number[]} matrix - 5x4 matrix
       * @return {number[]} 5x4 matrix with all values between 0-1
       */
      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;
      };
      /**
       * Adjusts brightness
       *
       * @param b - value of the brigthness (0-1, where 0 is black)
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Sets each channel on the diagonal of the color matrix.
       * This can be used to achieve a tinting effect on Containers similar to the tint field of some
       * display objects like Sprite, Text, Graphics, and Mesh.
       *
       * @param color - Color of the tint. This is a hex value.
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      ColorMatrixFilter.prototype.tint = function (color, multiply) {
          var r = (color >> 16) & 0xff;
          var g = (color >> 8) & 0xff;
          var b = color & 0xff;
          var matrix = [
              r / 255, 0, 0, 0, 0,
              0, g / 255, 0, 0, 0,
              0, 0, b / 255, 0, 0,
              0, 0, 0, 1, 0 ];
          this._loadMatrix(matrix, multiply);
      };
      /**
       * Set the matrices in grey scales
       *
       * @param scale - value of the grey (0-1, where 0 is black)
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Set the black and white matrice.
       *
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Set the hue property of the color
       *
       * @param rotation - in degrees
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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

           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
       *
       * @param amount - value of the contrast (0-1)
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Set the saturation matrix, increase the separation between colors
       * Increase saturation : increase contrast, brightness, and sharpness
       *
       * @param amount - The saturation amount (0-1)
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Desaturate image (remove color)
       *
       * Call the saturate function
       */
      ColorMatrixFilter.prototype.desaturate = function () {
          this.saturate(-1);
      };
      /**
       * Negative image (inverse of classic rgb matrix)
       *
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Sepia image
       *
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Color motion picture process invented in 1916 (thanks Dominic Szablewski)
       *
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Polaroid filter
       *
       * @param 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);
      };
      /**
       * Filter who transforms : Red -> Blue and Blue -> Red
       *
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski)
       *
       * @param 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);
      };
      /**
       * Brown delicious browni filter (thanks Dominic Szablewski)
       *
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Vintage filter (thanks Dominic Szablewski)
       *
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * We don't know exactly what it does, kind of gradient map, but funny to play with!
       *
       * @param desaturation - Tone values.
       * @param toned - Tone values.
       * @param lightColor - Tone values, example: `0xFFE580`
       * @param darkColor - Tone values, example: `0xFFE580`
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Night effect
       *
       * @param intensity - The intensity of the night effect.
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * Predator effect
       *
       * Erase the current matrix by setting a new indepent one
       *
       * @param amount - how much the predator feels his future victim
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /**
       * LSD effect
       *
       * Multiply the current matrix
       *
       * @param multiply - if true, current matrix and matrix are multiplied. If false,
       *  just set the current matrix with @param matrix
       */
      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);
      };
      /** Erase the current matrix by setting the default one. */
      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.
           *
           * @default 1
           */
          get: function () {
              return this.uniforms.uAlpha;
          },
          set: function (value) {
              this.uniforms.uAlpha = value;
          },
          enumerable: false,
          configurable: true
      });
      return ColorMatrixFilter;
  }(Filter));
  // Americanized alias
  ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale;

  /*!
   * @pixi/filter-displacement - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/filter-displacement is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$f = function(d, b) {
      extendStatics$f = 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$f(d, b);
  };

  function __extends$f(d, b) {
      extendStatics$f(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  var fragment$5 = "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$3 = "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";

  /**
   * 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.
   *
   * @memberof PIXI.filters
   */
  var DisplacementFilter = /** @class */ (function (_super) {
      __extends$f(DisplacementFilter, _super);
      /**
       * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!)
       * @param scale - The scale of the displacement
       */
      function DisplacementFilter(sprite, scale) {
          var _this = this;
          var maskMatrix = new Matrix();
          sprite.renderable = false;
          _this = _super.call(this, vertex$3, fragment$5, {
              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 Point(scale, scale);
          return _this;
      }
      /**
       * Applies the filter.
       *
       * @param filterManager - The manager.
       * @param input - The input target.
       * @param output - The output target.
       * @param 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. */
          get: function () {
              return this.uniforms.mapSampler;
          },
          set: function (value) {
              this.uniforms.mapSampler = value;
          },
          enumerable: false,
          configurable: true
      });
      return DisplacementFilter;
  }(Filter));

  /*!
   * @pixi/filter-fxaa - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/filter-fxaa is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$g = function(d, b) {
      extendStatics$g = 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$g(d, b);
  };

  function __extends$g(d, b) {
      extendStatics$g(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  var vertex$4 = "\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 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\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, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n";

  var fragment$6 = "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 inputSize;\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, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n      gl_FragColor = color;\n}\n";

  /**
   * 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
   *
   * @memberof PIXI.filters
   */
  var FXAAFilter = /** @class */ (function (_super) {
      __extends$g(FXAAFilter, _super);
      function FXAAFilter() {
          // TODO - needs work
          return _super.call(this, vertex$4, fragment$6) || this;
      }
      return FXAAFilter;
  }(Filter));

  /*!
   * @pixi/filter-noise - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/filter-noise is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$h = function(d, b) {
      extendStatics$h = 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$h(d, b);
  };

  function __extends$h(d, b) {
      extendStatics$h(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  var fragment$7 = "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";

  /**
   * A Noise effect filter.
   *
   * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js
   *
   * @memberof PIXI.filters
   * @author Vico @vicocotea
   */
  var NoiseFilter = /** @class */ (function (_super) {
      __extends$h(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, defaultFilterVertex, fragment$7, {
              uNoise: 0,
              uSeed: 0,
          }) || this;
          _this.noise = noise;
          _this.seed = seed;
          return _this;
      }
      Object.defineProperty(NoiseFilter.prototype, "noise", {
          /**
           * The amount of noise to apply, this value should be in the range (0, 1].
           *
           * @default 0.5
           */
          get: function () {
              return this.uniforms.uNoise;
          },
          set: function (value) {
              this.uniforms.uNoise = value;
          },
          enumerable: false,
          configurable: true
      });
      Object.defineProperty(NoiseFilter.prototype, "seed", {
          /** A seed value to apply to the random noise generation. `Math.random()` is a good value to use. */
          get: function () {
              return this.uniforms.uSeed;
          },
          set: function (value) {
              this.uniforms.uSeed = value;
          },
          enumerable: false,
          configurable: true
      });
      return NoiseFilter;
  }(Filter));

  /*!
   * @pixi/mixin-cache-as-bitmap - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/mixin-cache-as-bitmap is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*!
   * @pixi/constants - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/constants is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */
  /**
   * 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$3;
  (function (ENV) {
      ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY";
      ENV[ENV["WEBGL"] = 1] = "WEBGL";
      ENV[ENV["WEBGL2"] = 2] = "WEBGL2";
  })(ENV$3 || (ENV$3 = {}));
  /**
   * 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$3;
  (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$3 || (RENDERER_TYPE$3 = {}));
  /**
   * 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$3;
  (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$3 || (BUFFER_BITS$3 = {}));
  /**
   * 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$3;
  (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$3 || (BLEND_MODES$3 = {}));
  /**
   * 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$3;
  (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$3 || (DRAW_MODES$3 = {}));
  /**
   * Various GL texture/resources formats.
   *
   * @memberof PIXI
   * @static
   * @name FORMATS
   * @enum {number}
   * @property {number} RGBA=6408
   * @property {number} RGB=6407
   * @property {number} RG=33319
   * @property {number} RED=6403
   * @property {number} RGBA_INTEGER=36249
   * @property {number} RGB_INTEGER=36248
   * @property {number} RG_INTEGER=33320
   * @property {number} RED_INTEGER=36244
   * @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$3;
  (function (FORMATS) {
      FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
      FORMATS[FORMATS["RGB"] = 6407] = "RGB";
      FORMATS[FORMATS["RG"] = 33319] = "RG";
      FORMATS[FORMATS["RED"] = 6403] = "RED";
      FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
      FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
      FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
      FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
      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$3 || (FORMATS$3 = {}));
  /**
   * 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$3;
  (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$3 || (TARGETS$3 = {}));
  /**
   * 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} UNSIGNED_INT=5125
   * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
   * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
   * @property {number} UNSIGNED_INT_24_8=34042
   * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
   * @property {number} BYTE=5120
   * @property {number} SHORT=5122
   * @property {number} INT=5124
   * @property {number} FLOAT=5126
   * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
   * @property {number} HALF_FLOAT=36193
   */
  var TYPES$3;
  (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["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
      TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
      TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
      TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
      TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
      TYPES[TYPES["BYTE"] = 5120] = "BYTE";
      TYPES[TYPES["SHORT"] = 5122] = "SHORT";
      TYPES[TYPES["INT"] = 5124] = "INT";
      TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
      TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
      TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
  })(TYPES$3 || (TYPES$3 = {}));
  /**
   * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
   * WebGL1 works only with FLOAT.
   *
   * @memberof PIXI
   * @static
   * @name SAMPLER_TYPES
   * @enum {number}
   * @property {number} FLOAT=0
   * @property {number} INT=1
   * @property {number} UINT=2
   */
  var SAMPLER_TYPES$3;
  (function (SAMPLER_TYPES) {
      SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
      SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
      SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
  })(SAMPLER_TYPES$3 || (SAMPLER_TYPES$3 = {}));
  /**
   * 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$3;
  (function (SCALE_MODES) {
      SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
      SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
  })(SCALE_MODES$3 || (SCALE_MODES$3 = {}));
  /**
   * 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$3;
  (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$3 || (WRAP_MODES$3 = {}));
  /**
   * 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
   * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
   *   that supports buffering each level-of-detail.
   */
  var MIPMAP_MODES$3;
  (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["ON_MANUAL"] = 3] = "ON_MANUAL";
  })(MIPMAP_MODES$3 || (MIPMAP_MODES$3 = {}));
  /**
   * 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$3;
  (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["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
  })(ALPHA_MODES$3 || (ALPHA_MODES$3 = {}));
  /**
   * Configure whether filter textures are cleared after binding.
   *
   * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
   * this and skip clearing as an optimization.
   *
   * @name CLEAR_MODES
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
   * @property {number} CLEAR - Always clear the filter texture.
   * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
   * @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$3;
  (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$3 || (CLEAR_MODES$3 = {}));
  /**
   * 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$3;
  (function (GC_MODES) {
      GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
      GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
  })(GC_MODES$3 || (GC_MODES$3 = {}));
  /**
   * 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$3;
  (function (PRECISION) {
      PRECISION["LOW"] = "lowp";
      PRECISION["MEDIUM"] = "mediump";
      PRECISION["HIGH"] = "highp";
  })(PRECISION$3 || (PRECISION$3 = {}));
  /**
   * 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$3;
  (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$3 || (MASK_TYPES$3 = {}));
  /**
   * 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$3;
  (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$3 || (MSAA_QUALITY$3 = {}));
  /**
   * Constants for various buffer types in Pixi
   *
   * @see PIXI.BUFFER_TYPE
   *
   * @name BUFFER_TYPE
   * @memberof PIXI
   * @static
   * @enum {number}
   * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
   * @property {number} ARRAY_BUFFER - buffer type for using attribute data
   * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
   */
  var BUFFER_TYPE$3;
  (function (BUFFER_TYPE) {
      BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
      BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
      // NOT YET SUPPORTED
      BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
  })(BUFFER_TYPE$3 || (BUFFER_TYPE$3 = {}));

  var _tempMatrix = new Matrix();
  DisplayObject.prototype._cacheAsBitmap = false;
  DisplayObject.prototype._cacheData = null;
  DisplayObject.prototype._cacheAsBitmapResolution = null;
  DisplayObject.prototype._cacheAsBitmapMultisample = MSAA_QUALITY$3.NONE;
  // 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.
  /**
   * @class
   * @ignore
   * @private
   */
  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(DisplayObject.prototype, {
      /**
       * The resolution to use for cacheAsBitmap. By default this will use the renderer's resolution
       * but can be overriden for performance. Lower values will reduce memory usage at the expense
       * of render quality. A falsey value of `null` or `0` will default to the renderer's resolution.
       * If `cacheAsBitmap` is set to `true`, this will re-render with the new resolution.
       *
       * @member {number} cacheAsBitmapResolution
       * @memberof PIXI.DisplayObject#
       * @default null
       */
      cacheAsBitmapResolution: {
          get: function () {
              return this._cacheAsBitmapResolution;
          },
          set: function (resolution) {
              if (resolution === this._cacheAsBitmapResolution) {
                  return;
              }
              this._cacheAsBitmapResolution = resolution;
              if (this.cacheAsBitmap) {
                  // Toggle to re-render at the new resolution
                  this.cacheAsBitmap = false;
                  this.cacheAsBitmap = true;
              }
          },
      },
      /**
       * The number of samples to use for cacheAsBitmap. If set to `null`, the renderer's
       * sample count is used.
       * If `cacheAsBitmap` is set to `true`, this will re-render with the new number of samples.
       *
       * @member {number} cacheAsBitmapMultisample
       * @memberof PIXI.DisplayObject#
       * @default PIXI.MSAA_QUALITY.NONE
       */
      cacheAsBitmapMultisample: {
          get: function () {
              return this._cacheAsBitmapMultisample;
          },
          set: function (multisample) {
              if (multisample === this._cacheAsBitmapMultisample) {
                  return;
              }
              this._cacheAsBitmapMultisample = multisample;
              if (this.cacheAsBitmap) {
                  // Toggle to re-render with new multisample
                  this.cacheAsBitmap = false;
                  this.cacheAsBitmap = true;
              }
          },
      },
      /**
       * 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 () {
              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;
              }
          },
      },
  });
  /**
   * Renders a cached version of the sprite with WebGL
   *
   * @private
   * @method _renderCached
   * @memberof PIXI.DisplayObject#
   * @param {PIXI.Renderer} renderer - the WebGL renderer
   */
  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);
  };
  /**
   * Prepares the WebGL renderer to cache the sprite
   *
   * @private
   * @method _initCachedDisplayObject
   * @memberof PIXI.DisplayObject#
   * @param {PIXI.Renderer} renderer - the WebGL renderer
   */
  DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) {
      var _a;
      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 && this.filters.length) {
          var padding = this.filters[0].padding;
          bounds.pad(padding);
      }
      bounds.ceil(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 cachedDestinationFrame = renderer.renderTexture.destinationFrame.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 = RenderTexture.create({
          width: bounds.width,
          height: bounds.height,
          resolution: this.cacheAsBitmapResolution || renderer.resolution,
          multisample: (_a = this.cacheAsBitmapMultisample) !== null && _a !== void 0 ? _a : renderer.multisample,
      });
      var textureCacheId = "cacheAsBitmap_" + uid();
      this._cacheData.textureCacheId = textureCacheId;
      BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId);
      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: renderTexture, clear: true, transform: m, skipUpdateTransform: false });
      renderer.framebuffer.blit();
      // now restore the state be setting the new properties
      renderer.projection.transform = cachedProjectionTransform;
      renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame, cachedDestinationFrame);
      // 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;
      this.alpha = cacheAlpha;
      // create our cached sprite
      var cachedSprite = new 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);
  };
  /**
   * Renders a cached version of the sprite with canvas
   *
   * @private
   * @method _renderCachedCanvas
   * @memberof PIXI.DisplayObject#
   * @param {PIXI.CanvasRenderer} renderer - The canvas renderer
   */
  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);
  };
  // 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
   * @method _initCachedDisplayObjectCanvas
   * @memberof PIXI.DisplayObject#
   * @param {PIXI.CanvasRenderer} renderer - The canvas renderer
   */
  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(null, true);
      var cacheAlpha = this.alpha;
      this.alpha = 1;
      var cachedRenderTarget = renderer.context;
      var cachedProjectionTransform = renderer._projTransform;
      bounds.ceil(settings.RESOLUTION);
      var renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height });
      var textureCacheId = "cacheAsBitmap_" + uid();
      this._cacheData.textureCacheId = textureCacheId;
      BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId);
      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: renderTexture, clear: true, transform: m, skipUpdateTransform: 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;
      this.alpha = cacheAlpha;
      // create our cached sprite
      var cachedSprite = new 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);
  };
  /**
   * Calculates the bounds of the cached sprite
   *
   * @private
   * @method
   */
  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;
  };
  /**
   * Gets the bounds of the cached sprite.
   *
   * @private
   * @method
   * @return {Rectangle} The local bounds.
   */
  DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() {
      return this._cacheData.sprite.getLocalBounds(null);
  };
  /**
   * Destroys the cached sprite.
   *
   * @private
   * @method
   */
  DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() {
      this._cacheData.sprite._texture.destroy(true);
      this._cacheData.sprite = null;
      BaseTexture.removeFromCache(this._cacheData.textureCacheId);
      Texture.removeFromCache(this._cacheData.textureCacheId);
      this._cacheData.textureCacheId = null;
  };
  /**
   * Destroys the cached object.
   *
   * @private
   * @method
   * @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.
   */
  DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) {
      this.cacheAsBitmap = false;
      this.destroy(options);
  };

  /*!
   * @pixi/mixin-get-child-by-name - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/mixin-get-child-by-name is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * The instance name of the object.
   *
   * @memberof PIXI.DisplayObject#
   * @member {string} name
   */
  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.
   */
  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;
  };

  /*!
   * @pixi/mixin-get-global-position - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/mixin-get-global-position is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /**
   * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot.
   *
   * @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.
   */
  DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) {
      if (point === void 0) { point = new 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;
  };

  /*!
   * @pixi/mesh-extras - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/mesh-extras is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$i = function(d, b) {
      extendStatics$i = 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$i(d, b);
  };

  function __extends$i(d, b) {
      extendStatics$i(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  /**
   * @memberof PIXI
   */
  var PlaneGeometry = /** @class */ (function (_super) {
      __extends$i(PlaneGeometry, _super);
      /**
       * @param width - The width of the plane.
       * @param height - The height of the plane.
       * @param segWidth - Number of horizontal segments.
       * @param segHeight - Number of vertical segments.
       */
      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);
          }
          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);
          }
          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;
  }(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);
   * ```
   *
   * @memberof PIXI
   */
  var RopeGeometry = /** @class */ (function (_super) {
      __extends$i(RopeGeometry, _super);
      /**
       * @param width - The width (i.e., thickness) of the rope.
       * @param points - An array of {@link PIXI.Point} objects to construct this rope.
       * @param textureScale - 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.
       */
      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;
          _this.points = points;
          _this._width = width;
          _this.textureScale = textureScale;
          _this.build();
          return _this;
      }
      Object.defineProperty(RopeGeometry.prototype, "width", {
          /**
           * The width (i.e., thickness) of the rope.
           *
           * @readOnly
           */
          get: function () {
              return this._width;
          },
          enumerable: false,
          configurable: true
      });
      /** Refreshes Rope indices and uvs */
      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;
          }
          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();
      };
      /**
       * refreshes vertices of Rope mesh
       */
      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 {
                  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();
      };
      RopeGeometry.prototype.update = function () {
          if (this.textureScale > 0) {
              this.build(); // we need to update UVs
          }
          else {
              this.updateVertices();
          }
      };
      return RopeGeometry;
  }(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);
   *  ```
   *
   * @memberof PIXI
   */
  var SimpleRope = /** @class */ (function (_super) {
      __extends$i(SimpleRope, _super);
      /**
       * @param texture - The texture to use on the rope.
       * @param points - An array of {@link PIXI.Point} objects to construct this rope.
       * @param {number} textureScale - 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 stretched instead.
       */
      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 MeshMaterial(texture);
          if (textureScale > 0) {
              // attempt to set UV wrapping, will fail on non-power of two textures
              texture.baseTexture.wrapMode = exports.WRAP_MODES.REPEAT;
          }
          _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();
          }
          _super.prototype._render.call(this, renderer);
      };
      return SimpleRope;
  }(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);
   *  ```
   *
   * @memberof PIXI
   */
  var SimplePlane = /** @class */ (function (_super) {
      __extends$i(SimplePlane, _super);
      /**
       * @param texture - The texture to use on the SimplePlane.
       * @param verticesX - The number of vertices in the x-axis
       * @param verticesY - The number of vertices in the y-axis
       */
      function SimplePlane(texture, verticesX, verticesY) {
          var _this = this;
          var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY);
          var meshMaterial = new MeshMaterial(Texture.WHITE);
          _this = _super.call(this, planeGeometry, meshMaterial) || this;
          // lets call the setter to ensure all necessary updates are performed
          _this.texture = texture;
          _this.autoResize = true;
          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;
          var _a = this.shader.texture, width = _a.width, height = _a.height;
          if (this.autoResize && (geometry.width !== width || geometry.height !== height)) {
              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();
          }
          _super.prototype._render.call(this, renderer);
      };
      SimplePlane.prototype.destroy = function (options) {
          this.shader.texture.off('update', this.textureUpdated, this);
          _super.prototype.destroy.call(this, options);
      };
      return SimplePlane;
  }(Mesh));

  /**
   * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments.
   * For more robust customization, use {@link PIXI.Mesh}.
   *
   * @memberof PIXI
   */
  var SimpleMesh = /** @class */ (function (_super) {
      __extends$i(SimpleMesh, _super);
      /**
       * @param texture - 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 drawMode - the drawMode, can be any of the Mesh.DRAW_MODES consts
       */
      function SimpleMesh(texture, vertices, uvs, indices, drawMode) {
          if (texture === void 0) { texture = Texture.EMPTY; }
          var _this = this;
          var geometry = new MeshGeometry(vertices, uvs, indices);
          geometry.getBuffer('aVertexPosition').static = false;
          var meshMaterial = new MeshMaterial(texture);
          _this = _super.call(this, geometry, meshMaterial, null, drawMode) || this;
          _this.autoUpdate = true;
          return _this;
      }
      Object.defineProperty(SimpleMesh.prototype, "vertices", {
          /**
           * Collection of vertices data.
           * @type {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();
          }
          _super.prototype._render.call(this, renderer);
      };
      return SimpleMesh;
  }(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);
   *  ```
   * <pre>
   *      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
   * </pre>
   *
   * @memberof PIXI
   */
  var NineSlicePlane = /** @class */ (function (_super) {
      __extends$i(NineSlicePlane, _super);
      /**
       * @param 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)
       */
      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, 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. */
          _this._width = _this._origWidth;
          /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
          _this._height = _this._origHeight;
          _this._leftWidth = leftWidth;
          _this._rightWidth = rightWidth;
          _this._topHeight = topHeight;
          _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
      });
      /** Updates the horizontal vertices. */
      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;
      };
      /** Updates the vertical vertices. */
      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;
      };
      /**
       * Returns the smaller of a set of vertical and horizontal scale of nine slice corners.
       *
       * @return Smaller number of vertical and horizontal scale.
       */
      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. */
          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. */
          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. */
          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. */
          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. */
          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. */
          get: function () {
              return this._bottomHeight;
          },
          set: function (value) {
              this._bottomHeight = value;
              this._refresh();
          },
          enumerable: false,
          configurable: true
      });
      /** Refreshes NineSlicePlane coords. All of them. */
      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));

  /*!
   * @pixi/sprite-animated - v6.3.0
   * Compiled Wed, 23 Mar 2022 18:58:56 UTC
   *
   * @pixi/sprite-animated is licensed under the MIT License.
   * http://www.opensource.org/licenses/mit-license
   */

  /*! *****************************************************************************
  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$j = function(d, b) {
      extendStatics$j = 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$j(d, b);
  };

  function __extends$j(d, b) {
      extendStatics$j(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  }

  /**
   * 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:
   *
   * ```js
   * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup);
   *
   * function setup() {
   *   let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet;
   *   animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]);
   *   ...
   * }
   * ```
   *
   * @memberof PIXI
   */
  var AnimatedSprite = /** @class */ (function (_super) {
      __extends$j(AnimatedSprite, _super);
      /**
       * @param 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 Texture ? textures[0] : textures[0].texture) || this;
          _this._textures = null;
          _this._durations = null;
          _this._autoUpdate = autoUpdate;
          _this._isConnectedToTicker = false;
          _this.animationSpeed = 1;
          _this.loop = true;
          _this.updateAnchor = false;
          _this.onComplete = null;
          _this.onFrameChange = null;
          _this.onLoop = null;
          _this._currentTime = 0;
          _this._playing = false;
          _this._previousFrame = null;
          _this.textures = textures;
          return _this;
      }
      /** Stops the AnimatedSprite. */
      AnimatedSprite.prototype.stop = function () {
          if (!this._playing) {
              return;
          }
          this._playing = false;
          if (this._autoUpdate && this._isConnectedToTicker) {
              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.shared.add(this.update, this, exports.UPDATE_PRIORITY.HIGH);
              this._isConnectedToTicker = true;
          }
      };
      /**
       * Stops the AnimatedSprite and goes to a specific frame.
       *
       * @param 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 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 deltaTime - Time since last tick.
       */
      AnimatedSprite.prototype.update = function (deltaTime) {
          if (!this._playing) {
              return;
          }
          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. */
      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);
          }
      };
      /**
       * 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.
       *
       * @param frames - The array of frames ids the AnimatedSprite will use as its texture frames.
       * @return - The new animated sprite with the specified frames.
       */
      AnimatedSprite.fromFrames = function (frames) {
          var textures = [];
          for (var i = 0; i < frames.length; ++i) {
              textures.push(Texture.from(frames[i]));
          }
          return new AnimatedSprite(textures);
      };
      /**
       * A short hand way of creating an AnimatedSprite from an array of image ids.
       *
       * @param images - The array of image urls the AnimatedSprite will use as its texture frames.
       * @return 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(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
           * @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. */
          get: function () {
              return this._textures;
          },
          set: function (value) {
              if (value[0] instanceof 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.
           *
           * @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.
           *
           * @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. */
          get: function () {
              return this._autoUpdate;
          },
          set: function (value) {
              if (value !== this._autoUpdate) {
                  this._autoUpdate = value;
                  if (!this._autoUpdate && this._isConnectedToTicker) {
                      Ticker.shared.remove(this.update, this);
                      this._isConnectedToTicker = false;
                  }
                  else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) {
                      Ticker.shared.add(this.update, this);
                      this._isConnectedToTicker = true;
                  }
              }
          },
          enumerable: false,
          configurable: true
      });
      return AnimatedSprite;
  }(Sprite));

  // Install renderer plugins
  Renderer.registerPlugin('accessibility', AccessibilityManager);
  Renderer.registerPlugin('extract', Extract);
  Renderer.registerPlugin('interaction', InteractionManager);
  Renderer.registerPlugin('particle', ParticleRenderer);
  Renderer.registerPlugin('prepare', Prepare);
  Renderer.registerPlugin('batch', BatchRenderer);
  Renderer.registerPlugin('tilingSprite', TilingSpriteRenderer);
  // Install loader plugins
  Loader.registerPlugin(BitmapFontLoader);
  Loader.registerPlugin(CompressedTextureLoader);
  Loader.registerPlugin(DDSLoader);
  Loader.registerPlugin(KTXLoader);
  Loader.registerPlugin(SpritesheetLoader);
  // Install application plugins
  Application.registerPlugin(TickerPlugin);
  Application.registerPlugin(AppLoaderPlugin);
  /**
   * String of the current PIXI version.
   *
   * @static
   * @constant
   * @memberof PIXI
   * @name VERSION
   * @type {string}
   */
  var VERSION$1 = '6.3.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: AlphaFilter,
      BlurFilter: BlurFilter,
      BlurFilterPass: BlurFilterPass,
      ColorMatrixFilter: ColorMatrixFilter,
      DisplacementFilter: DisplacementFilter,
      FXAAFilter: FXAAFilter,
      NoiseFilter: NoiseFilter,
  };

  exports.AbstractBatchRenderer = AbstractBatchRenderer;
  exports.AbstractMultiResource = AbstractMultiResource;
  exports.AbstractRenderer = AbstractRenderer;
  exports.AccessibilityManager = AccessibilityManager;
  exports.AnimatedSprite = AnimatedSprite;
  exports.AppLoaderPlugin = AppLoaderPlugin;
  exports.Application = Application;
  exports.ArrayResource = ArrayResource;
  exports.Attribute = Attribute;
  exports.BaseImageResource = BaseImageResource;
  exports.BasePrepare = BasePrepare;
  exports.BaseRenderTexture = BaseRenderTexture;
  exports.BaseTexture = BaseTexture;
  exports.BatchDrawCall = BatchDrawCall;
  exports.BatchGeometry = BatchGeometry;
  exports.BatchPluginFactory = BatchPluginFactory;
  exports.BatchRenderer = BatchRenderer;
  exports.BatchShaderGenerator = BatchShaderGenerator;
  exports.BatchSystem = BatchSystem;
  exports.BatchTextureArray = BatchTextureArray;
  exports.BitmapFont = BitmapFont;
  exports.BitmapFontData = BitmapFontData;
  exports.BitmapFontLoader = BitmapFontLoader;
  exports.BitmapText = BitmapText;
  exports.BlobResource = BlobResource;
  exports.Bounds = Bounds;
  exports.Buffer = Buffer;
  exports.BufferResource = BufferResource;
  exports.CanvasResource = CanvasResource;
  exports.Circle = Circle;
  exports.CompressedTextureLoader = CompressedTextureLoader;
  exports.CompressedTextureResource = CompressedTextureResource;
  exports.Container = Container;
  exports.ContextSystem = ContextSystem;
  exports.CountLimiter = CountLimiter;
  exports.CubeResource = CubeResource;
  exports.DDSLoader = DDSLoader;
  exports.DEG_TO_RAD = DEG_TO_RAD;
  exports.DisplayObject = DisplayObject;
  exports.Ellipse = Ellipse;
  exports.Extract = Extract;
  exports.FORMATS_TO_COMPONENTS = FORMATS_TO_COMPONENTS;
  exports.FillStyle = FillStyle;
  exports.Filter = Filter;
  exports.FilterState = FilterState;
  exports.FilterSystem = FilterSystem;
  exports.Framebuffer = Framebuffer;
  exports.FramebufferSystem = FramebufferSystem;
  exports.GLFramebuffer = GLFramebuffer;
  exports.GLProgram = GLProgram;
  exports.GLTexture = GLTexture;
  exports.GRAPHICS_CURVES = GRAPHICS_CURVES;
  exports.Geometry = Geometry;
  exports.GeometrySystem = GeometrySystem;
  exports.Graphics = Graphics;
  exports.GraphicsData = GraphicsData;
  exports.GraphicsGeometry = GraphicsGeometry;
  exports.IGLUniformData = IGLUniformData;
  exports.INSTALLED = INSTALLED;
  exports.INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL;
  exports.ImageBitmapResource = ImageBitmapResource;
  exports.ImageResource = ImageResource;
  exports.InteractionData = InteractionData;
  exports.InteractionEvent = InteractionEvent;
  exports.InteractionManager = InteractionManager;
  exports.InteractionTrackingData = InteractionTrackingData;
  exports.KTXLoader = KTXLoader;
  exports.LineStyle = LineStyle;
  exports.Loader = Loader;
  exports.MaskData = MaskData;
  exports.MaskSystem = MaskSystem;
  exports.Matrix = Matrix;
  exports.Mesh = Mesh;
  exports.MeshBatchUvs = MeshBatchUvs;
  exports.MeshGeometry = MeshGeometry;
  exports.MeshMaterial = MeshMaterial;
  exports.NineSlicePlane = NineSlicePlane;
  exports.ObjectRenderer = ObjectRenderer;
  exports.ObservablePoint = ObservablePoint;
  exports.PI_2 = PI_2;
  exports.ParticleContainer = ParticleContainer;
  exports.ParticleRenderer = ParticleRenderer;
  exports.PlaneGeometry = PlaneGeometry;
  exports.Point = Point;
  exports.Polygon = Polygon;
  exports.Prepare = Prepare;
  exports.Program = Program;
  exports.ProjectionSystem = ProjectionSystem;
  exports.Quad = Quad;
  exports.QuadUv = QuadUv;
  exports.RAD_TO_DEG = RAD_TO_DEG;
  exports.Rectangle = Rectangle;
  exports.RenderTexture = RenderTexture;
  exports.RenderTexturePool = RenderTexturePool;
  exports.RenderTextureSystem = RenderTextureSystem;
  exports.Renderer = Renderer;
  exports.Resource = Resource;
  exports.RopeGeometry = RopeGeometry;
  exports.RoundedRectangle = RoundedRectangle;
  exports.Runner = Runner;
  exports.SVGResource = SVGResource;
  exports.ScissorSystem = ScissorSystem;
  exports.Shader = Shader;
  exports.ShaderSystem = ShaderSystem;
  exports.SimpleMesh = SimpleMesh;
  exports.SimplePlane = SimplePlane;
  exports.SimpleRope = SimpleRope;
  exports.Sprite = Sprite;
  exports.SpriteMaskFilter = SpriteMaskFilter;
  exports.Spritesheet = Spritesheet;
  exports.SpritesheetLoader = SpritesheetLoader;
  exports.State = State;
  exports.StateSystem = StateSystem;
  exports.StencilSystem = StencilSystem;
  exports.System = System;
  exports.TYPES_TO_BYTES_PER_COMPONENT = TYPES_TO_BYTES_PER_COMPONENT;
  exports.TYPES_TO_BYTES_PER_PIXEL = TYPES_TO_BYTES_PER_PIXEL;
  exports.TemporaryDisplayObject = TemporaryDisplayObject;
  exports.Text = Text;
  exports.TextMetrics = TextMetrics;
  exports.TextStyle = TextStyle;
  exports.Texture = Texture;
  exports.TextureGCSystem = TextureGCSystem;
  exports.TextureLoader = TextureLoader;
  exports.TextureMatrix = TextureMatrix;
  exports.TextureSystem = TextureSystem;
  exports.TextureUvs = TextureUvs;
  exports.Ticker = Ticker;
  exports.TickerPlugin = TickerPlugin;
  exports.TilingSprite = TilingSprite;
  exports.TilingSpriteRenderer = TilingSpriteRenderer;
  exports.TimeLimiter = TimeLimiter;
  exports.Transform = Transform;
  exports.UniformGroup = UniformGroup;
  exports.VERSION = VERSION$1;
  exports.VideoResource = VideoResource;
  exports.ViewableBuffer = ViewableBuffer;
  exports.accessibleTarget = accessibleTarget;
  exports.autoDetectRenderer = autoDetectRenderer;
  exports.autoDetectResource = autoDetectResource;
  exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader;
  exports.createUBOElements = createUBOElements;
  exports.defaultFilterVertex = defaultFilterVertex;
  exports.defaultVertex = defaultVertex$2;
  exports.filters = filters;
  exports.generateProgram = generateProgram;
  exports.generateUniformBufferSync = generateUniformBufferSync;
  exports.getTestContext = getTestContext;
  exports.getUBOData = getUBOData;
  exports.graphicsUtils = graphicsUtils;
  exports.groupD8 = groupD8;
  exports.interactiveTarget = interactiveTarget;
  exports.isMobile = isMobile$1;
  exports.resources = resources;
  exports.settings = settings;
  exports.systems = systems;
  exports.uniformParsers = uniformParsers;
  exports.utils = utils;

  return exports;

}({}));
//# sourceMappingURL=pixi.js.map
