(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(["exports", "three"], factory);
  } else if (typeof exports !== "undefined") {
    factory(exports, require("three"));
  } else {
    var mod = {
      exports: {}
    };
    factory(mod.exports, global.three);
    global.BasisTextureLoader = mod.exports;
  }
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _three) {
  "use strict";

  Object.defineProperty(_exports, "__esModule", {
    value: true
  });
  _exports.BasisTextureLoader = void 0;

  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

  function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

  function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

  function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } Object.defineProperty(subClass, "prototype", { value: Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }), writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

  function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

  function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

  function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

  function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

  function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

  function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

  /**
   * Loader for Basis Universal GPU Texture Codec.
   *
   * Basis Universal is a "supercompressed" GPU texture and texture video
   * compression system that outputs a highly compressed intermediate file format
   * (.basis) that can be quickly transcoded to a wide variety of GPU texture
   * compression formats.
   *
   * This loader parallelizes the transcoding process across a configurable number
   * of web workers, before transferring the transcoded compressed texture back
   * to the main thread.
   */
  var _taskCache = new WeakMap();

  var BasisTextureLoader = /*#__PURE__*/function (_Loader) {
    _inherits(BasisTextureLoader, _Loader);

    var _super = _createSuper(BasisTextureLoader);

    function BasisTextureLoader(manager) {
      var _this;

      _classCallCheck(this, BasisTextureLoader);

      _this = _super.call(this, manager);
      _this.transcoderPath = '';
      _this.transcoderBinary = null;
      _this.transcoderPending = null;
      _this.workerLimit = 4;
      _this.workerPool = [];
      _this.workerNextTaskID = 1;
      _this.workerSourceURL = '';
      _this.workerConfig = null;
      return _this;
    }

    _createClass(BasisTextureLoader, [{
      key: "setTranscoderPath",
      value: function setTranscoderPath(path) {
        this.transcoderPath = path;
        return this;
      }
    }, {
      key: "setWorkerLimit",
      value: function setWorkerLimit(workerLimit) {
        this.workerLimit = workerLimit;
        return this;
      }
    }, {
      key: "detectSupport",
      value: function detectSupport(renderer) {
        this.workerConfig = {
          astcSupported: renderer.extensions.has('WEBGL_compressed_texture_astc'),
          etc1Supported: renderer.extensions.has('WEBGL_compressed_texture_etc1'),
          etc2Supported: renderer.extensions.has('WEBGL_compressed_texture_etc'),
          dxtSupported: renderer.extensions.has('WEBGL_compressed_texture_s3tc'),
          bptcSupported: renderer.extensions.has('EXT_texture_compression_bptc'),
          pvrtcSupported: renderer.extensions.has('WEBGL_compressed_texture_pvrtc') || renderer.extensions.has('WEBKIT_WEBGL_compressed_texture_pvrtc')
        };
        return this;
      }
    }, {
      key: "load",
      value: function load(url, onLoad, onProgress, onError) {
        var _this2 = this;

        var loader = new _three.FileLoader(this.manager);
        loader.setResponseType('arraybuffer');
        loader.setWithCredentials(this.withCredentials);
        var texture = new _three.CompressedTexture();
        loader.load(url, function (buffer) {
          // Check for an existing task using this buffer. A transferred buffer cannot be transferred
          // again from this thread.
          if (_taskCache.has(buffer)) {
            var cachedTask = _taskCache.get(buffer);

            return cachedTask.promise.then(onLoad).catch(onError);
          }

          _this2._createTexture([buffer]).then(function (_texture) {
            texture.copy(_texture);
            texture.needsUpdate = true;
            if (onLoad) onLoad(texture);
          }).catch(onError);
        }, onProgress, onError);
        return texture;
      }
      /** Low-level transcoding API, exposed for use by KTX2Loader. */

    }, {
      key: "parseInternalAsync",
      value: function parseInternalAsync(options) {
        var levels = options.levels;
        var buffers = new Set();

        for (var i = 0; i < levels.length; i++) {
          buffers.add(levels[i].data.buffer);
        }

        return this._createTexture(Array.from(buffers), _objectSpread(_objectSpread({}, options), {}, {
          lowLevel: true
        }));
      }
      /**
       * @param {ArrayBuffer[]} buffers
       * @param {object?} config
       * @return {Promise<CompressedTexture>}
       */

    }, {
      key: "_createTexture",
      value: function _createTexture(buffers) {
        var _this3 = this;

        var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
        var worker;
        var taskID;
        var taskConfig = config;
        var taskCost = 0;

        for (var i = 0; i < buffers.length; i++) {
          taskCost += buffers[i].byteLength;
        }

        var texturePending = this._allocateWorker(taskCost).then(function (_worker) {
          worker = _worker;
          taskID = _this3.workerNextTaskID++;
          return new Promise(function (resolve, reject) {
            worker._callbacks[taskID] = {
              resolve: resolve,
              reject: reject
            };
            worker.postMessage({
              type: 'transcode',
              id: taskID,
              buffers: buffers,
              taskConfig: taskConfig
            }, buffers);
          });
        }).then(function (message) {
          var mipmaps = message.mipmaps,
              width = message.width,
              height = message.height,
              format = message.format;
          var texture = new _three.CompressedTexture(mipmaps, width, height, format, _three.UnsignedByteType);
          texture.minFilter = mipmaps.length === 1 ? _three.LinearFilter : _three.LinearMipmapLinearFilter;
          texture.magFilter = _three.LinearFilter;
          texture.generateMipmaps = false;
          texture.needsUpdate = true;
          return texture;
        }); // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)


        texturePending.catch(function () {
          return true;
        }).then(function () {
          if (worker && taskID) {
            worker._taskLoad -= taskCost;
            delete worker._callbacks[taskID];
          }
        }); // Cache the task result.

        _taskCache.set(buffers[0], {
          promise: texturePending
        });

        return texturePending;
      }
    }, {
      key: "_initTranscoder",
      value: function _initTranscoder() {
        var _this4 = this;

        if (!this.transcoderPending) {
          // Load transcoder wrapper.
          var jsLoader = new _three.FileLoader(this.manager);
          jsLoader.setPath(this.transcoderPath);
          jsLoader.setWithCredentials(this.withCredentials);
          var jsContent = new Promise(function (resolve, reject) {
            jsLoader.load('basis_transcoder.js', resolve, undefined, reject);
          }); // Load transcoder WASM binary.

          var binaryLoader = new _three.FileLoader(this.manager);
          binaryLoader.setPath(this.transcoderPath);
          binaryLoader.setResponseType('arraybuffer');
          binaryLoader.setWithCredentials(this.withCredentials);
          var binaryContent = new Promise(function (resolve, reject) {
            binaryLoader.load('basis_transcoder.wasm', resolve, undefined, reject);
          });
          this.transcoderPending = Promise.all([jsContent, binaryContent]).then(function (_ref) {
            var _ref2 = _slicedToArray(_ref, 2),
                jsContent = _ref2[0],
                binaryContent = _ref2[1];

            var fn = BasisTextureLoader.BasisWorker.toString();
            var body = ['/* constants */', 'let _EngineFormat = ' + JSON.stringify(BasisTextureLoader.EngineFormat), 'let _TranscoderFormat = ' + JSON.stringify(BasisTextureLoader.TranscoderFormat), 'let _BasisFormat = ' + JSON.stringify(BasisTextureLoader.BasisFormat), '/* basis_transcoder.js */', jsContent, '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n');
            _this4.workerSourceURL = URL.createObjectURL(new Blob([body]));
            _this4.transcoderBinary = binaryContent;
          });
        }

        return this.transcoderPending;
      }
    }, {
      key: "_allocateWorker",
      value: function _allocateWorker(taskCost) {
        var _this5 = this;

        return this._initTranscoder().then(function () {
          if (_this5.workerPool.length < _this5.workerLimit) {
            var _worker2 = new Worker(_this5.workerSourceURL);

            _worker2._callbacks = {};
            _worker2._taskLoad = 0;

            _worker2.postMessage({
              type: 'init',
              config: _this5.workerConfig,
              transcoderBinary: _this5.transcoderBinary
            });

            _worker2.onmessage = function (e) {
              var message = e.data;

              switch (message.type) {
                case 'transcode':
                  _worker2._callbacks[message.id].resolve(message);

                  break;

                case 'error':
                  _worker2._callbacks[message.id].reject(message);

                  break;

                default:
                  console.error('THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"');
              }
            };

            _this5.workerPool.push(_worker2);
          } else {
            _this5.workerPool.sort(function (a, b) {
              return a._taskLoad > b._taskLoad ? -1 : 1;
            });
          }

          var worker = _this5.workerPool[_this5.workerPool.length - 1];
          worker._taskLoad += taskCost;
          return worker;
        });
      }
    }, {
      key: "dispose",
      value: function dispose() {
        for (var i = 0; i < this.workerPool.length; i++) {
          this.workerPool[i].terminate();
        }

        this.workerPool.length = 0;
        return this;
      }
    }]);

    return BasisTextureLoader;
  }(_three.Loader);
  /* CONSTANTS */


  _exports.BasisTextureLoader = BasisTextureLoader;
  BasisTextureLoader.BasisFormat = {
    ETC1S: 0,
    UASTC_4x4: 1
  };
  BasisTextureLoader.TranscoderFormat = {
    ETC1: 0,
    ETC2: 1,
    BC1: 2,
    BC3: 3,
    BC4: 4,
    BC5: 5,
    BC7_M6_OPAQUE_ONLY: 6,
    BC7_M5: 7,
    PVRTC1_4_RGB: 8,
    PVRTC1_4_RGBA: 9,
    ASTC_4x4: 10,
    ATC_RGB: 11,
    ATC_RGBA_INTERPOLATED_ALPHA: 12,
    RGBA32: 13,
    RGB565: 14,
    BGR565: 15,
    RGBA4444: 16
  };
  BasisTextureLoader.EngineFormat = {
    RGBAFormat: _three.RGBAFormat,
    RGBA_ASTC_4x4_Format: _three.RGBA_ASTC_4x4_Format,
    RGBA_BPTC_Format: _three.RGBA_BPTC_Format,
    RGBA_ETC2_EAC_Format: _three.RGBA_ETC2_EAC_Format,
    RGBA_PVRTC_4BPPV1_Format: _three.RGBA_PVRTC_4BPPV1_Format,
    RGBA_S3TC_DXT5_Format: _three.RGBA_S3TC_DXT5_Format,
    RGB_ETC1_Format: _three.RGB_ETC1_Format,
    RGB_ETC2_Format: _three.RGB_ETC2_Format,
    RGB_PVRTC_4BPPV1_Format: _three.RGB_PVRTC_4BPPV1_Format,
    RGB_S3TC_DXT1_Format: _three.RGB_S3TC_DXT1_Format
  };
  /* WEB WORKER */

  BasisTextureLoader.BasisWorker = function () {
    var config;
    var transcoderPending;
    var BasisModule;
    var EngineFormat = _EngineFormat; // eslint-disable-line no-undef

    var TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef

    var BasisFormat = _BasisFormat; // eslint-disable-line no-undef

    onmessage = function onmessage(e) {
      var message = e.data;

      switch (message.type) {
        case 'init':
          config = message.config;
          init(message.transcoderBinary);
          break;

        case 'transcode':
          transcoderPending.then(function () {
            try {
              var _ref3 = message.taskConfig.lowLevel ? transcodeLowLevel(message.taskConfig) : transcode(message.buffers[0]),
                  width = _ref3.width,
                  height = _ref3.height,
                  hasAlpha = _ref3.hasAlpha,
                  mipmaps = _ref3.mipmaps,
                  format = _ref3.format;

              var buffers = [];

              for (var i = 0; i < mipmaps.length; ++i) {
                buffers.push(mipmaps[i].data.buffer);
              }

              self.postMessage({
                type: 'transcode',
                id: message.id,
                width: width,
                height: height,
                hasAlpha: hasAlpha,
                mipmaps: mipmaps,
                format: format
              }, buffers);
            } catch (error) {
              console.error(error);
              self.postMessage({
                type: 'error',
                id: message.id,
                error: error.message
              });
            }
          });
          break;
      }
    };

    function init(wasmBinary) {
      transcoderPending = new Promise(function (resolve) {
        BasisModule = {
          wasmBinary: wasmBinary,
          onRuntimeInitialized: resolve
        };
        BASIS(BasisModule); // eslint-disable-line no-undef
      }).then(function () {
        BasisModule.initializeBasis();
      });
    }

    function transcodeLowLevel(taskConfig) {
      var basisFormat = taskConfig.basisFormat,
          width = taskConfig.width,
          height = taskConfig.height,
          hasAlpha = taskConfig.hasAlpha;

      var _getTranscoderFormat = getTranscoderFormat(basisFormat, width, height, hasAlpha),
          transcoderFormat = _getTranscoderFormat.transcoderFormat,
          engineFormat = _getTranscoderFormat.engineFormat;

      var blockByteLength = BasisModule.getBytesPerBlockOrPixel(transcoderFormat);
      assert(BasisModule.isFormatSupported(transcoderFormat), 'THREE.BasisTextureLoader: Unsupported format.');
      var mipmaps = [];

      if (basisFormat === BasisFormat.ETC1S) {
        var transcoder = new BasisModule.LowLevelETC1SImageTranscoder();
        var _taskConfig$globalDat = taskConfig.globalData,
            endpointCount = _taskConfig$globalDat.endpointCount,
            endpointsData = _taskConfig$globalDat.endpointsData,
            selectorCount = _taskConfig$globalDat.selectorCount,
            selectorsData = _taskConfig$globalDat.selectorsData,
            tablesData = _taskConfig$globalDat.tablesData;

        try {
          var ok;
          ok = transcoder.decodePalettes(endpointCount, endpointsData, selectorCount, selectorsData);
          assert(ok, 'THREE.BasisTextureLoader: decodePalettes() failed.');
          ok = transcoder.decodeTables(tablesData);
          assert(ok, 'THREE.BasisTextureLoader: decodeTables() failed.');

          for (var i = 0; i < taskConfig.levels.length; i++) {
            var level = taskConfig.levels[i];
            var imageDesc = taskConfig.globalData.imageDescs[i];
            var dstByteLength = getTranscodedImageByteLength(transcoderFormat, level.width, level.height);
            var dst = new Uint8Array(dstByteLength);
            ok = transcoder.transcodeImage(transcoderFormat, dst, dstByteLength / blockByteLength, level.data, getWidthInBlocks(transcoderFormat, level.width), getHeightInBlocks(transcoderFormat, level.height), level.width, level.height, level.index, imageDesc.rgbSliceByteOffset, imageDesc.rgbSliceByteLength, imageDesc.alphaSliceByteOffset, imageDesc.alphaSliceByteLength, imageDesc.imageFlags, hasAlpha, false, 0, 0);
            assert(ok, 'THREE.BasisTextureLoader: transcodeImage() failed for level ' + level.index + '.');
            mipmaps.push({
              data: dst,
              width: level.width,
              height: level.height
            });
          }
        } finally {
          transcoder.delete();
        }
      } else {
        for (var _i2 = 0; _i2 < taskConfig.levels.length; _i2++) {
          var _level = taskConfig.levels[_i2];

          var _dstByteLength = getTranscodedImageByteLength(transcoderFormat, _level.width, _level.height);

          var _dst = new Uint8Array(_dstByteLength);

          var _ok = BasisModule.transcodeUASTCImage(transcoderFormat, _dst, _dstByteLength / blockByteLength, _level.data, getWidthInBlocks(transcoderFormat, _level.width), getHeightInBlocks(transcoderFormat, _level.height), _level.width, _level.height, _level.index, 0, _level.data.byteLength, 0, hasAlpha, false, 0, 0, -1, -1);

          assert(_ok, 'THREE.BasisTextureLoader: transcodeUASTCImage() failed for level ' + _level.index + '.');
          mipmaps.push({
            data: _dst,
            width: _level.width,
            height: _level.height
          });
        }
      }

      return {
        width: width,
        height: height,
        hasAlpha: hasAlpha,
        mipmaps: mipmaps,
        format: engineFormat
      };
    }

    function transcode(buffer) {
      var basisFile = new BasisModule.BasisFile(new Uint8Array(buffer));
      var basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
      var width = basisFile.getImageWidth(0, 0);
      var height = basisFile.getImageHeight(0, 0);
      var levels = basisFile.getNumLevels(0);
      var hasAlpha = basisFile.getHasAlpha();

      function cleanup() {
        basisFile.close();
        basisFile.delete();
      }

      var _getTranscoderFormat2 = getTranscoderFormat(basisFormat, width, height, hasAlpha),
          transcoderFormat = _getTranscoderFormat2.transcoderFormat,
          engineFormat = _getTranscoderFormat2.engineFormat;

      if (!width || !height || !levels) {
        cleanup();
        throw new Error('THREE.BasisTextureLoader:	Invalid texture');
      }

      if (!basisFile.startTranscoding()) {
        cleanup();
        throw new Error('THREE.BasisTextureLoader: .startTranscoding failed');
      }

      var mipmaps = [];

      for (var mip = 0; mip < levels; mip++) {
        var mipWidth = basisFile.getImageWidth(0, mip);
        var mipHeight = basisFile.getImageHeight(0, mip);
        var dst = new Uint8Array(basisFile.getImageTranscodedSizeInBytes(0, mip, transcoderFormat));
        var status = basisFile.transcodeImage(dst, 0, mip, transcoderFormat, 0, hasAlpha);

        if (!status) {
          cleanup();
          throw new Error('THREE.BasisTextureLoader: .transcodeImage failed.');
        }

        mipmaps.push({
          data: dst,
          width: mipWidth,
          height: mipHeight
        });
      }

      cleanup();
      return {
        width: width,
        height: height,
        hasAlpha: hasAlpha,
        mipmaps: mipmaps,
        format: engineFormat
      };
    } //
    // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
    // device capabilities, and texture dimensions. The list below ranks the formats separately
    // for ETC1S and UASTC.
    //
    // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
    // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
    // chooses RGBA32 only as a last resort and does not expose that option to the caller.


    var FORMAT_OPTIONS = [{
      if: 'astcSupported',
      basisFormat: [BasisFormat.UASTC_4x4],
      transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4],
      engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format],
      priorityETC1S: Infinity,
      priorityUASTC: 1,
      needsPowerOfTwo: false
    }, {
      if: 'bptcSupported',
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
      transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5],
      engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format],
      priorityETC1S: 3,
      priorityUASTC: 2,
      needsPowerOfTwo: false
    }, {
      if: 'dxtSupported',
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
      transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3],
      engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format],
      priorityETC1S: 4,
      priorityUASTC: 5,
      needsPowerOfTwo: false
    }, {
      if: 'etc2Supported',
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
      transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2],
      engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format],
      priorityETC1S: 1,
      priorityUASTC: 3,
      needsPowerOfTwo: false
    }, {
      if: 'etc1Supported',
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
      transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC1],
      engineFormat: [EngineFormat.RGB_ETC1_Format, EngineFormat.RGB_ETC1_Format],
      priorityETC1S: 2,
      priorityUASTC: 4,
      needsPowerOfTwo: false
    }, {
      if: 'pvrtcSupported',
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
      transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA],
      engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format],
      priorityETC1S: 5,
      priorityUASTC: 6,
      needsPowerOfTwo: true
    }];
    var ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) {
      return a.priorityETC1S - b.priorityETC1S;
    });
    var UASTC_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) {
      return a.priorityUASTC - b.priorityUASTC;
    });

    function getTranscoderFormat(basisFormat, width, height, hasAlpha) {
      var transcoderFormat;
      var engineFormat;
      var options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;

      for (var i = 0; i < options.length; i++) {
        var opt = options[i];
        if (!config[opt.if]) continue;
        if (!opt.basisFormat.includes(basisFormat)) continue;
        if (opt.needsPowerOfTwo && !(isPowerOfTwo(width) && isPowerOfTwo(height))) continue;
        transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0];
        engineFormat = opt.engineFormat[hasAlpha ? 1 : 0];
        return {
          transcoderFormat: transcoderFormat,
          engineFormat: engineFormat
        };
      }

      console.warn('THREE.BasisTextureLoader: No suitable compressed texture format found. Decoding to RGBA32.');
      transcoderFormat = TranscoderFormat.RGBA32;
      engineFormat = EngineFormat.RGBAFormat;
      return {
        transcoderFormat: transcoderFormat,
        engineFormat: engineFormat
      };
    }

    function assert(ok, message) {
      if (!ok) throw new Error(message);
    }

    function getWidthInBlocks(transcoderFormat, width) {
      return Math.ceil(width / BasisModule.getFormatBlockWidth(transcoderFormat));
    }

    function getHeightInBlocks(transcoderFormat, height) {
      return Math.ceil(height / BasisModule.getFormatBlockHeight(transcoderFormat));
    }

    function getTranscodedImageByteLength(transcoderFormat, width, height) {
      var blockByteLength = BasisModule.getBytesPerBlockOrPixel(transcoderFormat);

      if (BasisModule.formatIsUncompressed(transcoderFormat)) {
        return width * height * blockByteLength;
      }

      if (transcoderFormat === TranscoderFormat.PVRTC1_4_RGB || transcoderFormat === TranscoderFormat.PVRTC1_4_RGBA) {
        // GL requires extra padding for very small textures:
        // https://www.khronos.org/registry/OpenGL/extensions/IMG/IMG_texture_compression_pvrtc.txt
        var paddedWidth = width + 3 & ~3;
        var paddedHeight = height + 3 & ~3;
        return (Math.max(8, paddedWidth) * Math.max(8, paddedHeight) * 4 + 7) / 8;
      }

      return getWidthInBlocks(transcoderFormat, width) * getHeightInBlocks(transcoderFormat, height) * blockByteLength;
    }

    function isPowerOfTwo(value) {
      if (value <= 2) return true;
      return (value & value - 1) === 0 && value !== 0;
    }
  };
});