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

  Object.defineProperty(_exports, "__esModule", {
    value: true
  });
  _exports.KTX2Transfer = _exports.KTX2SupercompressionScheme = _exports.KTX2Primaries = _exports.KTX2Model = _exports.KTX2Flags = _exports.KTX2DescriptorType = _exports.KTX2Container = _exports.KTX2ChannelUASTC = _exports.KTX2ChannelETC1S = void 0;
  _exports.read = p;
  _exports.write = y;

  function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e8) { throw _e8; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e9) { didErr = true; err = _e9; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

  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 _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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  var t = new Uint8Array([0]),
      e = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10];
  var n, i, s, a, r, o, l, f;
  _exports.KTX2ChannelUASTC = f;
  _exports.KTX2ChannelETC1S = l;
  _exports.KTX2Flags = o;
  _exports.KTX2Transfer = r;
  _exports.KTX2Primaries = a;
  _exports.KTX2Model = s;
  _exports.KTX2DescriptorType = i;
  _exports.KTX2SupercompressionScheme = n;
  !function (t) {
    t[t.NONE = 0] = "NONE", t[t.BASISLZ = 1] = "BASISLZ", t[t.ZSTD = 2] = "ZSTD", t[t.ZLIB = 3] = "ZLIB";
  }(n || (_exports.KTX2SupercompressionScheme = n = {})), function (t) {
    t[t.BASICFORMAT = 0] = "BASICFORMAT";
  }(i || (_exports.KTX2DescriptorType = i = {})), function (t) {
    t[t.UNSPECIFIED = 0] = "UNSPECIFIED", t[t.ETC1S = 163] = "ETC1S", t[t.UASTC = 166] = "UASTC";
  }(s || (_exports.KTX2Model = s = {})), function (t) {
    t[t.UNSPECIFIED = 0] = "UNSPECIFIED", t[t.SRGB = 1] = "SRGB";
  }(a || (_exports.KTX2Primaries = a = {})), function (t) {
    t[t.UNSPECIFIED = 0] = "UNSPECIFIED", t[t.LINEAR = 1] = "LINEAR", t[t.SRGB = 2] = "SRGB", t[t.ITU = 3] = "ITU", t[t.NTSC = 4] = "NTSC", t[t.SLOG = 5] = "SLOG", t[t.SLOG2 = 6] = "SLOG2";
  }(r || (_exports.KTX2Transfer = r = {})), function (t) {
    t[t.ALPHA_STRAIGHT = 0] = "ALPHA_STRAIGHT", t[t.ALPHA_PREMULTIPLIED = 1] = "ALPHA_PREMULTIPLIED";
  }(o || (_exports.KTX2Flags = o = {})), function (t) {
    t[t.RGB = 0] = "RGB", t[t.RRR = 3] = "RRR", t[t.GGG = 4] = "GGG", t[t.AAA = 15] = "AAA";
  }(l || (_exports.KTX2ChannelETC1S = l = {})), function (t) {
    t[t.RGB = 0] = "RGB", t[t.RGBA = 3] = "RGBA", t[t.RRR = 4] = "RRR", t[t.RRRG = 5] = "RRRG";
  }(f || (_exports.KTX2ChannelUASTC = f = {}));

  var U = /*#__PURE__*/_createClass(function U() {
    _classCallCheck(this, U);

    this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = n.NONE, this.levels = [], this.dataFormatDescriptor = [{
      vendorId: 0,
      descriptorType: i.BASICFORMAT,
      versionNumber: 2,
      descriptorBlockSize: 40,
      colorModel: s.UNSPECIFIED,
      colorPrimaries: a.SRGB,
      transferFunction: a.SRGB,
      flags: o.ALPHA_STRAIGHT,
      texelBlockDimension: {
        x: 4,
        y: 4,
        z: 1,
        w: 1
      },
      bytesPlane: [],
      samples: []
    }], this.keyValue = {}, this.globalData = null;
  });

  _exports.KTX2Container = U;

  var c = /*#__PURE__*/function () {
    function c(t, e, n, i) {
      _classCallCheck(this, c);

      this._dataView = new DataView(t.buffer, t.byteOffset + e, n), this._littleEndian = i, this._offset = 0;
    }

    _createClass(c, [{
      key: "_nextUint8",
      value: function _nextUint8() {
        var t = this._dataView.getUint8(this._offset);

        return this._offset += 1, t;
      }
    }, {
      key: "_nextUint16",
      value: function _nextUint16() {
        var t = this._dataView.getUint16(this._offset, this._littleEndian);

        return this._offset += 2, t;
      }
    }, {
      key: "_nextUint32",
      value: function _nextUint32() {
        var t = this._dataView.getUint32(this._offset, this._littleEndian);

        return this._offset += 4, t;
      }
    }, {
      key: "_nextUint64",
      value: function _nextUint64() {
        var t = this._dataView.getUint32(this._offset, this._littleEndian) + Math.pow(2, 32) * this._dataView.getUint32(this._offset + 4, this._littleEndian);

        return this._offset += 8, t;
      }
    }, {
      key: "_skip",
      value: function _skip(t) {
        return this._offset += t, this;
      }
    }, {
      key: "_scan",
      value: function _scan(t) {
        var e = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
        var n = this._offset;
        var i = 0;

        for (; this._dataView.getUint8(this._offset) !== e && i < t;) {
          i++, this._offset++;
        }

        return i < t && this._offset++, new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + n, i);
      }
    }]);

    return c;
  }();

  function h(t) {
    return "undefined" != typeof TextEncoder ? new TextEncoder().encode(t) : Buffer.from(t);
  }

  function _(t) {
    return "undefined" != typeof TextDecoder ? new TextDecoder().decode(t) : Buffer.from(t).toString("utf8");
  }

  function g(t) {
    var e = 0;

    var _iterator = _createForOfIteratorHelper(t),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _n = _step.value;
        e += _n.byteLength;
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    var n = new Uint8Array(e);
    var i = 0;

    var _iterator2 = _createForOfIteratorHelper(t),
        _step2;

    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var _e = _step2.value;
        n.set(new Uint8Array(_e), i), i += _e.byteLength;
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }

    return n;
  }

  function p(t) {
    var n = new Uint8Array(t.buffer, t.byteOffset, e.length);
    if (n[0] !== e[0] || n[1] !== e[1] || n[2] !== e[2] || n[3] !== e[3] || n[4] !== e[4] || n[5] !== e[5] || n[6] !== e[6] || n[7] !== e[7] || n[8] !== e[8] || n[9] !== e[9] || n[10] !== e[10] || n[11] !== e[11]) throw new Error("Missing KTX 2.0 identifier.");
    var i = new U(),
        s = 17 * Uint32Array.BYTES_PER_ELEMENT,
        a = new c(t, e.length, s, !0);
    i.vkFormat = a._nextUint32(), i.typeSize = a._nextUint32(), i.pixelWidth = a._nextUint32(), i.pixelHeight = a._nextUint32(), i.pixelDepth = a._nextUint32(), i.layerCount = a._nextUint32(), i.faceCount = a._nextUint32();

    var r = a._nextUint32();

    i.supercompressionScheme = a._nextUint32();

    var o = a._nextUint32(),
        l = a._nextUint32(),
        f = a._nextUint32(),
        h = a._nextUint32(),
        g = a._nextUint64(),
        p = a._nextUint64(),
        x = new c(t, e.length + s, 3 * r * 8, !0);

    for (var _e2 = 0; _e2 < r; _e2++) {
      i.levels.push({
        levelData: new Uint8Array(t.buffer, t.byteOffset + x._nextUint64(), x._nextUint64()),
        uncompressedByteLength: x._nextUint64()
      });
    }

    var u = new c(t, o, l, !0),
        y = {
      vendorId: u._skip(4)._nextUint16(),
      descriptorType: u._nextUint16(),
      versionNumber: u._nextUint16(),
      descriptorBlockSize: u._nextUint16(),
      colorModel: u._nextUint8(),
      colorPrimaries: u._nextUint8(),
      transferFunction: u._nextUint8(),
      flags: u._nextUint8(),
      texelBlockDimension: {
        x: u._nextUint8() + 1,
        y: u._nextUint8() + 1,
        z: u._nextUint8() + 1,
        w: u._nextUint8() + 1
      },
      bytesPlane: [u._nextUint8(), u._nextUint8(), u._nextUint8(), u._nextUint8(), u._nextUint8(), u._nextUint8(), u._nextUint8(), u._nextUint8()],
      samples: []
    },
        D = (y.descriptorBlockSize / 4 - 6) / 4;

    for (var _t = 0; _t < D; _t++) {
      y.samples[_t] = {
        bitOffset: u._nextUint16(),
        bitLength: u._nextUint8(),
        channelID: u._nextUint8(),
        samplePosition: [u._nextUint8(), u._nextUint8(), u._nextUint8(), u._nextUint8()],
        sampleLower: u._nextUint32(),
        sampleUpper: u._nextUint32()
      };
    }

    i.dataFormatDescriptor.length = 0, i.dataFormatDescriptor.push(y);
    var b = new c(t, f, h, !0);

    for (; b._offset < h;) {
      var _t2 = b._nextUint32(),
          _e3 = b._scan(_t2),
          _n2 = _(_e3),
          _s = b._scan(_t2 - _e3.byteLength);

      i.keyValue[_n2] = _n2.match(/^ktx/i) ? _(_s) : _s, b._offset % 4 && b._skip(4 - b._offset % 4);
    }

    if (p <= 0) return i;

    var d = new c(t, g, p, !0),
        B = d._nextUint16(),
        w = d._nextUint16(),
        A = d._nextUint32(),
        S = d._nextUint32(),
        m = d._nextUint32(),
        L = d._nextUint32(),
        I = [];

    for (var _t3 = 0; _t3 < r; _t3++) {
      I.push({
        imageFlags: d._nextUint32(),
        rgbSliceByteOffset: d._nextUint32(),
        rgbSliceByteLength: d._nextUint32(),
        alphaSliceByteOffset: d._nextUint32(),
        alphaSliceByteLength: d._nextUint32()
      });
    }

    var R = g + d._offset,
        E = R + A,
        T = E + S,
        O = T + m,
        P = new Uint8Array(t.buffer, t.byteOffset + R, A),
        C = new Uint8Array(t.buffer, t.byteOffset + E, S),
        F = new Uint8Array(t.buffer, t.byteOffset + T, m),
        G = new Uint8Array(t.buffer, t.byteOffset + O, L);
    return i.globalData = {
      endpointCount: B,
      selectorCount: w,
      imageDescs: I,
      endpointsData: P,
      selectorsData: C,
      tablesData: F,
      extendedData: G
    }, i;
  }

  function x() {
    return (x = Object.assign || function (t) {
      for (var e = 1; e < arguments.length; e++) {
        var n = arguments[e];

        for (var i in n) {
          Object.prototype.hasOwnProperty.call(n, i) && (t[i] = n[i]);
        }
      }

      return t;
    }).apply(this, arguments);
  }

  var u = {
    keepWriter: !1
  };

  function y(n) {
    var s = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    s = x({}, u, s);
    var a = new ArrayBuffer(0);

    if (n.globalData) {
      var _t4 = new ArrayBuffer(20 + 5 * n.globalData.imageDescs.length * 4),
          _e4 = new DataView(_t4);

      _e4.setUint16(0, n.globalData.endpointCount, !0), _e4.setUint16(2, n.globalData.selectorCount, !0), _e4.setUint32(4, n.globalData.endpointsData.byteLength, !0), _e4.setUint32(8, n.globalData.selectorsData.byteLength, !0), _e4.setUint32(12, n.globalData.tablesData.byteLength, !0), _e4.setUint32(16, n.globalData.extendedData.byteLength, !0);

      for (var _t5 = 0; _t5 < n.globalData.imageDescs.length; _t5++) {
        var _i = n.globalData.imageDescs[_t5];
        _e4.setUint32(20 + 5 * _t5 * 4 + 0, _i.imageFlags, !0), _e4.setUint32(20 + 5 * _t5 * 4 + 4, _i.rgbSliceByteOffset, !0), _e4.setUint32(20 + 5 * _t5 * 4 + 8, _i.rgbSliceByteLength, !0), _e4.setUint32(20 + 5 * _t5 * 4 + 12, _i.alphaSliceByteOffset, !0), _e4.setUint32(20 + 5 * _t5 * 4 + 16, _i.alphaSliceByteLength, !0);
      }

      a = g([_t4, n.globalData.endpointsData, n.globalData.selectorsData, n.globalData.tablesData, n.globalData.extendedData]);
    }

    var r = [];
    var o = n.keyValue;
    s.keepWriter || (o = x({}, n.keyValue, {
      KTXwriter: "KTX-Parse v0.2.1"
    }));

    for (var _e5 in o) {
      var _n3 = o[_e5],
          _i2 = h(_e5),
          _s2 = "string" == typeof _n3 ? h(_n3) : _n3,
          _a = _i2.byteLength + 1 + _s2.byteLength + 1,
          _l = _a % 4 ? 4 - _a % 4 : 0;

      r.push(g([new Uint32Array([_a]), _i2, t, _s2, t, new Uint8Array(_l).fill(0)]));
    }

    var l = g(r),
        f = new ArrayBuffer(44),
        U = new DataView(f);
    if (1 !== n.dataFormatDescriptor.length || n.dataFormatDescriptor[0].descriptorType !== i.BASICFORMAT) throw new Error("Only BASICFORMAT Data Format Descriptor output supported.");
    var c = n.dataFormatDescriptor[0];
    U.setUint32(0, 44, !0), U.setUint16(4, c.vendorId, !0), U.setUint16(6, c.descriptorType, !0), U.setUint16(8, c.versionNumber, !0), U.setUint16(10, c.descriptorBlockSize, !0), U.setUint8(12, c.colorModel), U.setUint8(13, c.colorPrimaries), U.setUint8(14, c.transferFunction), U.setUint8(15, c.flags), U.setUint8(16, c.texelBlockDimension.x - 1), U.setUint8(17, c.texelBlockDimension.y - 1), U.setUint8(18, c.texelBlockDimension.z - 1), U.setUint8(19, c.texelBlockDimension.w - 1);

    for (var _t6 = 0; _t6 < 8; _t6++) {
      U.setUint8(20 + _t6, c.bytesPlane[_t6]);
    }

    for (var _t7 = 0; _t7 < c.samples.length; _t7++) {
      var _e6 = c.samples[_t7],
          _n4 = 28 + 16 * _t7;

      U.setUint16(_n4 + 0, _e6.bitOffset, !0), U.setUint8(_n4 + 2, _e6.bitLength), U.setUint8(_n4 + 3, _e6.channelID), U.setUint8(_n4 + 4, _e6.samplePosition[0]), U.setUint8(_n4 + 5, _e6.samplePosition[1]), U.setUint8(_n4 + 6, _e6.samplePosition[2]), U.setUint8(_n4 + 7, _e6.samplePosition[3]), U.setUint32(_n4 + 8, _e6.sampleLower, !0), U.setUint32(_n4 + 12, _e6.sampleUpper, !0);
    }

    var _ = e.length + 68 + 3 * n.levels.length * 8,
        p = _ + f.byteLength;

    var y = p + l.byteLength;
    y % 8 && (y += 8 - y % 8);
    var D = [],
        b = new DataView(new ArrayBuffer(3 * n.levels.length * 8));
    var d = y + a.byteLength;

    for (var _t8 = 0; _t8 < n.levels.length; _t8++) {
      var _e7 = n.levels[_t8];
      D.push(_e7.levelData), b.setBigUint64(24 * _t8 + 0, BigInt(d), !0), b.setBigUint64(24 * _t8 + 8, BigInt(_e7.levelData.byteLength), !0), b.setBigUint64(24 * _t8 + 16, BigInt(_e7.uncompressedByteLength), !0), d += _e7.levelData.byteLength;
    }

    var B = new ArrayBuffer(68),
        w = new DataView(B);
    return w.setUint32(0, n.vkFormat, !0), w.setUint32(4, n.typeSize, !0), w.setUint32(8, n.pixelWidth, !0), w.setUint32(12, n.pixelHeight, !0), w.setUint32(16, n.pixelDepth, !0), w.setUint32(20, n.layerCount, !0), w.setUint32(24, n.faceCount, !0), w.setUint32(28, n.levels.length, !0), w.setUint32(32, n.supercompressionScheme, !0), w.setUint32(36, _, !0), w.setUint32(40, f.byteLength, !0), w.setUint32(44, p, !0), w.setUint32(48, l.byteLength, !0), w.setBigUint64(52, BigInt(y), !0), w.setBigUint64(60, BigInt(a.byteLength), !0), new Uint8Array(g([new Uint8Array(e).buffer, B, b.buffer, f, l, new ArrayBuffer(y - (p + l.byteLength)), a].concat(D)));
  }
});