"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.KTX2Loader = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _three = require("three");
var _WorkerPool = require("../utils/WorkerPool.js");
var _ktxParseModule = require("../libs/ktx-parse.module.js");
var _zstddecModule = require("../libs/zstddec.module.js");
var _FORMAT_MAP, _TYPE_MAP, _COLOR_SPACE_MAP;
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
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; } } /**
                                                                                                                                                                                                                                                                                                                                           * Loader for KTX 2.0 GPU Texture containers.
                                                                                                                                                                                                                                                                                                                                           *
                                                                                                                                                                                                                                                                                                                                           * KTX 2.0 is a container format for various GPU texture formats. The loader
                                                                                                                                                                                                                                                                                                                                           * supports Basis Universal GPU textures, which can be quickly transcoded to
                                                                                                                                                                                                                                                                                                                                           * a wide variety of GPU texture compression formats, as well as some
                                                                                                                                                                                                                                                                                                                                           * uncompressed DataTexture and Data3DTexture formats.
                                                                                                                                                                                                                                                                                                                                           *
                                                                                                                                                                                                                                                                                                                                           * References:
                                                                                                                                                                                                                                                                                                                                           * - KTX: http://github.khronos.org/KTX-Specification/
                                                                                                                                                                                                                                                                                                                                           * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
                                                                                                                                                                                                                                                                                                                                           */
var _taskCache = new WeakMap();
var _activeLoaders = 0;
var _zstd;
var KTX2Loader = /*#__PURE__*/function (_Loader) {
  (0, _inherits2["default"])(KTX2Loader, _Loader);
  var _super = _createSuper(KTX2Loader);
  function KTX2Loader(manager) {
    var _this;
    (0, _classCallCheck2["default"])(this, KTX2Loader);
    _this = _super.call(this, manager);
    _this.transcoderPath = '';
    _this.transcoderBinary = null;
    _this.transcoderPending = null;
    _this.workerPool = new _WorkerPool.WorkerPool();
    _this.workerSourceURL = '';
    _this.workerConfig = null;
    if (typeof MSC_TRANSCODER !== 'undefined') {
      console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder".' + ' "msc_basis_transcoder" is no longer supported in three.js r125+.');
    }
    return _this;
  }
  (0, _createClass2["default"])(KTX2Loader, [{
    key: "setTranscoderPath",
    value: function setTranscoderPath(path) {
      this.transcoderPath = path;
      return this;
    }
  }, {
    key: "setWorkerLimit",
    value: function setWorkerLimit(num) {
      this.workerPool.setWorkerLimit(num);
      return this;
    }
  }, {
    key: "detectSupport",
    value: function detectSupport(renderer) {
      if (renderer.isWebGPURenderer === true) {
        this.workerConfig = {
          astcSupported: renderer.hasFeature('texture-compression-astc'),
          etc1Supported: false,
          etc2Supported: renderer.hasFeature('texture-compression-etc2'),
          dxtSupported: renderer.hasFeature('texture-compression-bc'),
          bptcSupported: false,
          pvrtcSupported: false
        };
      } else {
        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')
        };
        if (renderer.capabilities.isWebGL2) {
          // https://github.com/mrdoob/three.js/pull/22928
          this.workerConfig.etc1Supported = false;
        }
      }
      return this;
    }
  }, {
    key: "init",
    value: function init() {
      var _this2 = this;
      if (!this.transcoderPending) {
        // Load transcoder wrapper.
        var jsLoader = new _three.FileLoader(this.manager);
        jsLoader.setPath(this.transcoderPath);
        jsLoader.setWithCredentials(this.withCredentials);
        var jsContent = jsLoader.loadAsync('basis_transcoder.js');

        // Load transcoder WASM binary.
        var binaryLoader = new _three.FileLoader(this.manager);
        binaryLoader.setPath(this.transcoderPath);
        binaryLoader.setResponseType('arraybuffer');
        binaryLoader.setWithCredentials(this.withCredentials);
        var binaryContent = binaryLoader.loadAsync('basis_transcoder.wasm');
        this.transcoderPending = Promise.all([jsContent, binaryContent]).then(function (_ref) {
          var _ref2 = (0, _slicedToArray2["default"])(_ref, 2),
            jsContent = _ref2[0],
            binaryContent = _ref2[1];
          var fn = KTX2Loader.BasisWorker.toString();
          var body = ['/* constants */', 'let _EngineFormat = ' + JSON.stringify(KTX2Loader.EngineFormat), 'let _TranscoderFormat = ' + JSON.stringify(KTX2Loader.TranscoderFormat), 'let _BasisFormat = ' + JSON.stringify(KTX2Loader.BasisFormat), '/* basis_transcoder.js */', jsContent, '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n');
          _this2.workerSourceURL = URL.createObjectURL(new Blob([body]));
          _this2.transcoderBinary = binaryContent;
          _this2.workerPool.setWorkerCreator(function () {
            var worker = new Worker(_this2.workerSourceURL);
            var transcoderBinary = _this2.transcoderBinary.slice(0);
            worker.postMessage({
              type: 'init',
              config: _this2.workerConfig,
              transcoderBinary: transcoderBinary
            }, [transcoderBinary]);
            return worker;
          });
        });
        if (_activeLoaders > 0) {
          // Each instance loads a transcoder and allocates workers, increasing network and memory cost.

          console.warn('THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.' + ' Use a single KTX2Loader instance, or call .dispose() on old instances.');
        }
        _activeLoaders++;
      }
      return this.transcoderPending;
    }
  }, {
    key: "load",
    value: function load(url, onLoad, onProgress, onError) {
      var _this3 = this;
      if (this.workerConfig === null) {
        throw new Error('THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.');
      }
      var loader = new _three.FileLoader(this.manager);
      loader.setResponseType('arraybuffer');
      loader.setWithCredentials(this.withCredentials);
      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);
        }
        _this3._createTexture(buffer).then(function (texture) {
          return onLoad ? onLoad(texture) : null;
        })["catch"](onError);
      }, onProgress, onError);
    }
  }, {
    key: "_createTextureFrom",
    value: function _createTextureFrom(transcodeResult, container) {
      var faces = transcodeResult.faces,
        width = transcodeResult.width,
        height = transcodeResult.height,
        format = transcodeResult.format,
        type = transcodeResult.type,
        error = transcodeResult.error,
        dfdTransferFn = transcodeResult.dfdTransferFn,
        dfdFlags = transcodeResult.dfdFlags;
      if (type === 'error') return Promise.reject(error);
      var texture;
      if (container.faceCount === 6) {
        texture = new _three.CompressedTexture();
        texture.image = faces;
        texture.format = format;
        texture.type = _three.UnsignedByteType;
      } else {
        var mipmaps = faces[0].mipmaps;
        texture = container.layerCount > 1 ? new _three.CompressedArrayTexture(mipmaps, width, height, container.layerCount, format, _three.UnsignedByteType) : new _three.CompressedTexture(mipmaps, width, height, format, _three.UnsignedByteType);
      }
      texture.minFilter = faces[0].mipmaps.length === 1 ? _three.LinearFilter : _three.LinearMipmapLinearFilter;
      texture.magFilter = _three.LinearFilter;
      texture.generateMipmaps = false;
      texture.needsUpdate = true;
      // TODO: Detect NoColorSpace vs. LinearSRGBColorSpace based on primaries.
      texture.colorSpace = dfdTransferFn === _ktxParseModule.KHR_DF_TRANSFER_SRGB ? _three.SRGBColorSpace : _three.NoColorSpace;
      texture.premultiplyAlpha = !!(dfdFlags & _ktxParseModule.KHR_DF_FLAG_ALPHA_PREMULTIPLIED);
      return texture;
    }

    /**
     * @param {ArrayBuffer} buffer
     * @param {object?} config
     * @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
     */
  }, {
    key: "_createTexture",
    value: function () {
      var _createTexture2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(buffer) {
        var _this4 = this;
        var config,
          container,
          mipmaps,
          pendings,
          _loop,
          levelIndex,
          texture,
          taskConfig,
          texturePending,
          _args2 = arguments;
        return _regenerator["default"].wrap(function (_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              config = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {};
              container = (0, _ktxParseModule.read)(new Uint8Array(buffer));
              if (!(container.vkFormat !== _ktxParseModule.VK_FORMAT_UNDEFINED)) {
                _context2.next = 17;
                break;
              }
              mipmaps = [];
              pendings = [];
              _loop = /*#__PURE__*/_regenerator["default"].mark(function (levelIndex) {
                return _regenerator["default"].wrap(function (_context) {
                  while (1) switch (_context.prev = _context.next) {
                    case 0:
                      pendings.push(createDataTexture(container, levelIndex).then(function (dataTexture) {
                        mipmaps[levelIndex] = dataTexture;
                      }));
                    case 1:
                    case "end":
                      return _context.stop();
                  }
                }, _loop);
              });
              levelIndex = 0;
            case 7:
              if (!(levelIndex < container.levels.length)) {
                _context2.next = 12;
                break;
              }
              return _context2.delegateYield(_loop(levelIndex), "t0", 9);
            case 9:
              levelIndex++;
              _context2.next = 7;
              break;
            case 12:
              _context2.next = 14;
              return Promise.all(pendings);
            case 14:
              texture = mipmaps[0];
              texture.mipmaps = mipmaps.map(function (dt) {
                return {
                  data: dt.source.data,
                  width: dt.source.data.width,
                  height: dt.source.data.height,
                  depth: dt.source.data.depth
                };
              });
              return _context2.abrupt("return", texture);
            case 17:
              //
              taskConfig = config;
              texturePending = this.init().then(function () {
                return _this4.workerPool.postMessage({
                  type: 'transcode',
                  buffer: buffer,
                  taskConfig: taskConfig
                }, [buffer]);
              }).then(function (e) {
                return _this4._createTextureFrom(e.data, container);
              }); // Cache the task result.
              _taskCache.set(buffer, {
                promise: texturePending
              });
              return _context2.abrupt("return", texturePending);
            case 21:
            case "end":
              return _context2.stop();
          }
        }, _callee, this);
      }));
      function _createTexture() {
        return _createTexture2.apply(this, arguments);
      }
      return _createTexture;
    }()
  }, {
    key: "dispose",
    value: function dispose() {
      this.workerPool.dispose();
      if (this.workerSourceURL) URL.revokeObjectURL(this.workerSourceURL);
      _activeLoaders--;
      return this;
    }
  }]);
  return KTX2Loader;
}(_three.Loader);
/* CONSTANTS */
exports.KTX2Loader = KTX2Loader;
KTX2Loader.BasisFormat = {
  ETC1S: 0,
  UASTC_4x4: 1
};
KTX2Loader.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
};
KTX2Loader.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 */

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

  self.addEventListener('message', function (e) {
    var message = e.data;
    switch (message.type) {
      case 'init':
        config = message.config;
        init(message.transcoderBinary);
        break;
      case 'transcode':
        transcoderPending.then(function () {
          try {
            var _transcode = transcode(message.buffer),
              faces = _transcode.faces,
              buffers = _transcode.buffers,
              width = _transcode.width,
              height = _transcode.height,
              hasAlpha = _transcode.hasAlpha,
              format = _transcode.format,
              dfdTransferFn = _transcode.dfdTransferFn,
              dfdFlags = _transcode.dfdFlags;
            self.postMessage({
              type: 'transcode',
              id: message.id,
              faces: faces,
              width: width,
              height: height,
              hasAlpha: hasAlpha,
              format: format,
              dfdTransferFn: dfdTransferFn,
              dfdFlags: dfdFlags
            }, 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();
      if (BasisModule.KTX2File === undefined) {
        console.warn('THREE.KTX2Loader: Please update Basis Universal transcoder.');
      }
    });
  }
  function transcode(buffer) {
    var ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer));
    function cleanup() {
      ktx2File.close();
      ktx2File["delete"]();
    }
    if (!ktx2File.isValid()) {
      cleanup();
      throw new Error('THREE.KTX2Loader:	Invalid or unsupported .ktx2 file');
    }
    var basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
    var width = ktx2File.getWidth();
    var height = ktx2File.getHeight();
    var layerCount = ktx2File.getLayers() || 1;
    var levelCount = ktx2File.getLevels();
    var faceCount = ktx2File.getFaces();
    var hasAlpha = ktx2File.getHasAlpha();
    var dfdTransferFn = ktx2File.getDFDTransferFunc();
    var dfdFlags = ktx2File.getDFDFlags();
    var _getTranscoderFormat = getTranscoderFormat(basisFormat, width, height, hasAlpha),
      transcoderFormat = _getTranscoderFormat.transcoderFormat,
      engineFormat = _getTranscoderFormat.engineFormat;
    if (!width || !height || !levelCount) {
      cleanup();
      throw new Error('THREE.KTX2Loader:	Invalid texture');
    }
    if (!ktx2File.startTranscoding()) {
      cleanup();
      throw new Error('THREE.KTX2Loader: .startTranscoding failed');
    }
    var faces = [];
    var buffers = [];
    for (var face = 0; face < faceCount; face++) {
      var mipmaps = [];
      for (var mip = 0; mip < levelCount; mip++) {
        var layerMips = [];
        var mipWidth = void 0,
          mipHeight = void 0;
        for (var layer = 0; layer < layerCount; layer++) {
          var levelInfo = ktx2File.getImageLevelInfo(mip, layer, face);
          if (face === 0 && mip === 0 && layer === 0 && (levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0)) {
            console.warn('THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.');
          }
          if (levelCount > 1) {
            mipWidth = levelInfo.origWidth;
            mipHeight = levelInfo.origHeight;
          } else {
            // Handles non-multiple-of-four dimensions in textures without mipmaps. Textures with
            // mipmaps must use multiple-of-four dimensions, for some texture formats and APIs.
            // See mrdoob/three.js#25908.
            mipWidth = levelInfo.width;
            mipHeight = levelInfo.height;
          }
          var dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, layer, 0, transcoderFormat));
          var status = ktx2File.transcodeImage(dst, mip, layer, face, transcoderFormat, 0, -1, -1);
          if (!status) {
            cleanup();
            throw new Error('THREE.KTX2Loader: .transcodeImage failed.');
          }
          layerMips.push(dst);
        }
        var mipData = concat(layerMips);
        mipmaps.push({
          data: mipData,
          width: mipWidth,
          height: mipHeight
        });
        buffers.push(mipData.buffer);
      }
      faces.push({
        mipmaps: mipmaps,
        width: width,
        height: height,
        format: engineFormat
      });
    }
    cleanup();
    return {
      faces: faces,
      buffers: buffers,
      width: width,
      height: height,
      hasAlpha: hasAlpha,
      format: engineFormat,
      dfdTransferFn: dfdTransferFn,
      dfdFlags: dfdFlags
    };
  }

  //

  // 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],
    engineFormat: [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 (hasAlpha && opt.transcoderFormat.length < 2) 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.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.');
    transcoderFormat = TranscoderFormat.RGBA32;
    engineFormat = EngineFormat.RGBAFormat;
    return {
      transcoderFormat: transcoderFormat,
      engineFormat: engineFormat
    };
  }
  function isPowerOfTwo(value) {
    if (value <= 2) return true;
    return (value & value - 1) === 0 && value !== 0;
  }

  /** Concatenates N byte arrays. */
  function concat(arrays) {
    if (arrays.length === 1) return arrays[0];
    var totalByteLength = 0;
    for (var i = 0; i < arrays.length; i++) {
      var array = arrays[i];
      totalByteLength += array.byteLength;
    }
    var result = new Uint8Array(totalByteLength);
    var byteOffset = 0;
    for (var _i = 0; _i < arrays.length; _i++) {
      var _array = arrays[_i];
      result.set(_array, byteOffset);
      byteOffset += _array.byteLength;
    }
    return result;
  }
};

//
// DataTexture and Data3DTexture parsing.

var FORMAT_MAP = (_FORMAT_MAP = {}, (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R32G32B32A32_SFLOAT, _three.RGBAFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R16G16B16A16_SFLOAT, _three.RGBAFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R8G8B8A8_UNORM, _three.RGBAFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R8G8B8A8_SRGB, _three.RGBAFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R32G32_SFLOAT, _three.RGFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R16G16_SFLOAT, _three.RGFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R8G8_UNORM, _three.RGFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R8G8_SRGB, _three.RGFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R32_SFLOAT, _three.RedFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R16_SFLOAT, _three.RedFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R8_SRGB, _three.RedFormat), (0, _defineProperty2["default"])(_FORMAT_MAP, _ktxParseModule.VK_FORMAT_R8_UNORM, _three.RedFormat), _FORMAT_MAP);
var TYPE_MAP = (_TYPE_MAP = {}, (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R32G32B32A32_SFLOAT, _three.FloatType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R16G16B16A16_SFLOAT, _three.HalfFloatType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R8G8B8A8_UNORM, _three.UnsignedByteType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R8G8B8A8_SRGB, _three.UnsignedByteType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R32G32_SFLOAT, _three.FloatType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R16G16_SFLOAT, _three.HalfFloatType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R8G8_UNORM, _three.UnsignedByteType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R8G8_SRGB, _three.UnsignedByteType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R32_SFLOAT, _three.FloatType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R16_SFLOAT, _three.HalfFloatType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R8_SRGB, _three.UnsignedByteType), (0, _defineProperty2["default"])(_TYPE_MAP, _ktxParseModule.VK_FORMAT_R8_UNORM, _three.UnsignedByteType), _TYPE_MAP);
var COLOR_SPACE_MAP = (_COLOR_SPACE_MAP = {}, (0, _defineProperty2["default"])(_COLOR_SPACE_MAP, _ktxParseModule.VK_FORMAT_R8G8B8A8_SRGB, _three.SRGBColorSpace), (0, _defineProperty2["default"])(_COLOR_SPACE_MAP, _ktxParseModule.VK_FORMAT_R8G8_SRGB, _three.SRGBColorSpace), (0, _defineProperty2["default"])(_COLOR_SPACE_MAP, _ktxParseModule.VK_FORMAT_R8_SRGB, _three.SRGBColorSpace), _COLOR_SPACE_MAP);
function createDataTexture(_x2) {
  return _createDataTexture.apply(this, arguments);
}
function _createDataTexture() {
  _createDataTexture = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(container) {
    var levelIndex,
      vkFormat,
      pixelWidth,
      pixelHeight,
      pixelDepth,
      level,
      levelData,
      view,
      texture,
      _args4 = arguments;
    return _regenerator["default"].wrap(function _callee3$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          levelIndex = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : 0;
          vkFormat = container.vkFormat;
          pixelWidth = Math.max(1, container.pixelWidth >> levelIndex);
          pixelHeight = Math.max(1, container.pixelHeight >> levelIndex);
          pixelDepth = Math.max(1, container.pixelDepth >> levelIndex);
          if (!(FORMAT_MAP[vkFormat] === undefined)) {
            _context4.next = 7;
            break;
          }
          throw new Error('THREE.KTX2Loader: Unsupported vkFormat.');
        case 7:
          level = container.levels[levelIndex];
          if (!(container.supercompressionScheme === _ktxParseModule.KHR_SUPERCOMPRESSION_NONE)) {
            _context4.next = 12;
            break;
          }
          levelData = level.levelData;
          _context4.next = 20;
          break;
        case 12:
          if (!(container.supercompressionScheme === _ktxParseModule.KHR_SUPERCOMPRESSION_ZSTD)) {
            _context4.next = 19;
            break;
          }
          if (!_zstd) {
            _zstd = new Promise( /*#__PURE__*/function () {
              var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(resolve) {
                var zstd;
                return _regenerator["default"].wrap(function _callee2$(_context3) {
                  while (1) switch (_context3.prev = _context3.next) {
                    case 0:
                      zstd = new _zstddecModule.ZSTDDecoder();
                      _context3.next = 3;
                      return zstd.init();
                    case 3:
                      resolve(zstd);
                    case 4:
                    case "end":
                      return _context3.stop();
                  }
                }, _callee2);
              }));
              return function (_x3) {
                return _ref3.apply(this, arguments);
              };
            }());
          }
          _context4.next = 16;
          return _zstd;
        case 16:
          levelData = _context4.sent.decode(level.levelData, level.uncompressedByteLength);
          _context4.next = 20;
          break;
        case 19:
          throw new Error('THREE.KTX2Loader: Unsupported supercompressionScheme.');
        case 20:
          if (TYPE_MAP[vkFormat] === _three.FloatType) {
            view = new Float32Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Float32Array.BYTES_PER_ELEMENT);
          } else if (TYPE_MAP[vkFormat] === _three.HalfFloatType) {
            view = new Uint16Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT);
          } else {
            view = levelData;
          }
          //
          texture = pixelDepth === 0 ? new _three.DataTexture(view, pixelWidth, pixelHeight) : new _three.Data3DTexture(view, pixelWidth, pixelHeight, pixelDepth);
          texture.type = TYPE_MAP[vkFormat];
          texture.format = FORMAT_MAP[vkFormat];
          texture.colorSpace = COLOR_SPACE_MAP[vkFormat] || _three.NoColorSpace;
          texture.needsUpdate = true;

          //
          return _context4.abrupt("return", Promise.resolve(texture));
        case 27:
        case "end":
          return _context4.stop();
      }
    }, _callee3);
  }));
  return _createDataTexture.apply(this, arguments);
}