import { BufferGeometry as V, Mesh as X, Box3 as pe, Vector3 as A, Sphere as Se, CompressedTexture as Fe, Texture as F, Matrix3 as We, InterleavedBuffer as Ue, InterleavedBufferAttribute as ze, BufferAttribute as Ne, TextureLoader as qe, Matrix4 as Me, Clock as Ee, MeshStandardMaterial as Ve } from "./three.js";
import { DRACOLoader as Xe, KTX2Loader as je, MeshoptDecoder as Ke, GLTFLoader as we } from "./three-examples.js";
const Ye = "";
globalThis.GLTF_PROGRESSIVE_VERSION = Ye;
console.debug("[gltf-progressive] version -");
let I = "https://www.gstatic.com/draco/versioned/decoders/1.5.7/", j = "https://cdn.needle.tools/static/three/0.179.1/basis2/";
const He = I, Qe = j, Pe = new URL(I + "draco_decoder.js");
Pe.searchParams.append("range", "true");
fetch(Pe, {
  method: "GET",
  headers: {
    Range: "bytes=0-1"
  }
}).catch((o) => {
  console.debug(`Failed to fetch remote Draco decoder from ${I} (offline: ${typeof navigator < "u" ? navigator.onLine : "unknown"})`), I === He && Ze("./include/draco/"), j === Qe && et("./include/ktx2/");
}).finally(() => {
  Ce();
});
const Je = () => ({
  dracoDecoderPath: I,
  ktx2TranscoderPath: j
});
function Ze(o) {
  I = o, C && C[me] != I ? (console.debug("Updating Draco decoder path to " + o), C[me] = I, C.setDecoderPath(I), C.preload()) : console.debug("Setting Draco decoder path to " + o);
}
function et(o) {
  j = o, $ && $.transcoderPath != j ? (console.debug("Updating KTX2 transcoder path to " + o), $.setTranscoderPath(j), $.init()) : console.debug("Setting KTX2 transcoder path to " + o);
}
function Le(o) {
  return Ce(), o ? $.detectSupport(o) : o !== null && console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"), { dracoLoader: C, ktx2Loader: $, meshoptDecoder: ne };
}
function Te(o) {
  o.dracoLoader || o.setDRACOLoader(C), o.ktx2Loader || o.setKTX2Loader($), o.meshoptDecoder || o.setMeshoptDecoder(ne);
}
const me = /* @__PURE__ */ Symbol("dracoDecoderPath");
let C, ne, $;
function Ce() {
  C || (C = new Xe(), C[me] = I, C.setDecoderPath(I), C.setDecoderConfig({ type: "js" }), C.preload()), $ || ($ = new je(), $.setTranscoderPath(j), $.init()), ne || (ne = Ke);
}
const ye = /* @__PURE__ */ new WeakMap();
function Ae(o, t) {
  let e = ye.get(o);
  e ? e = Object.assign(e, t) : e = t, ye.set(o, e);
}
const tt = we.prototype.load;
function st(...o) {
  const t = ye.get(this);
  let e = o[0];
  const s = new URL(e, window.location.href);
  if (s.hostname.endsWith("needle.tools")) {
    const i = t?.progressive !== void 0 ? t.progressive : !0, n = t?.usecase ? t.usecase : "default";
    i ? this.requestHeader.Accept = `*/*;progressive=allowed;usecase=${n}` : this.requestHeader.Accept = `*/*;usecase=${n}`, e = s.toString();
  }
  return o[0] = e, tt?.call(this, ...o);
}
we.prototype.load = st;
N("debugprogressive");
function N(o) {
  if (typeof window > "u") return !1;
  const e = new URL(window.location.href).searchParams.get(o);
  return e == null || e === "0" || e === "false" ? !1 : e === "" ? !0 : e;
}
function rt(o, t) {
  if (t === void 0 || o === void 0 || t.startsWith("./") || t.startsWith("http") || t.startsWith("data:") || t.startsWith("blob:"))
    return t;
  const e = o.lastIndexOf("/");
  if (e >= 0) {
    const s = o.substring(0, e + 1);
    for (; s.endsWith("/") && t.startsWith("/"); ) t = t.substring(1);
    return s + t;
  }
  return t;
}
function ke() {
  return H !== void 0 || (H = /iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent), N("debugprogressive") && console.log("[glTF Progressive]: isMobileDevice", H)), H;
}
let H;
function ve() {
  if (typeof window > "u") return !1;
  const o = new URL(window.location.href), t = o.hostname === "localhost" || /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(o.hostname);
  return o.hostname === "127.0.0.1" || t;
}
class it {
  constructor(t = 100, e = {}) {
    this.maxConcurrent = t, this.debug = e.debug ?? !1, window.requestAnimationFrame(this.tick);
  }
  _running = /* @__PURE__ */ new Map();
  _queue = [];
  debug = !1;
  tick = () => {
    this.internalUpdate(), setTimeout(this.tick, 10);
  };
  /**
   * Request a slot for a promise with a specific key. This function returns a promise with a `use` method that can be called to add the promise to the queue.
   */
  slot(t) {
    return this.debug && console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`), new Promise((e) => {
      this._queue.push({ key: t, resolve: e });
    });
  }
  add(t, e) {
    this._running.has(t) || (this._running.set(t, e), e.finally(() => {
      this._running.delete(t), this.debug && console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`);
    }), this.debug && console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`));
  }
  internalUpdate() {
    const t = this.maxConcurrent - this._running.size;
    for (let e = 0; e < t && this._queue.length > 0; e++) {
      this.debug && console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);
      const { key: s, resolve: r } = this._queue.shift();
      r({
        use: (i) => this.add(s, i)
      });
    }
  }
}
function nt(o) {
  const t = o.image?.width ?? 0, e = o.image?.height ?? 0, s = o.image?.depth ?? 1, r = Math.floor(Math.log2(Math.max(t, e, s))) + 1, i = ot(o);
  return t * e * s * i * (1 - Math.pow(0.25, r)) / (1 - 0.25);
}
function ot(o) {
  let t = 4;
  const e = o.format;
  e === 1024 || e === 1025 ? t = 1 : e === 1026 || e === 1027 ? t = 2 : e === 1022 || e === 1029 ? t = 3 : (e === 1023 || e === 1033) && (t = 4);
  let s = 1;
  const r = o.type;
  return r === 1009 || r === 1010 ? s = 1 : r === 1011 || r === 1012 ? s = 2 : r === 1013 || r === 1014 || r === 1015 ? s = 4 : r === 1016 && (s = 2), t * s;
}
const at = typeof window > "u" && typeof document > "u", xe = /* @__PURE__ */ Symbol("needle:raycast-mesh");
function ee(o) {
  return o?.[xe] instanceof V ? o[xe] : null;
}
function lt(o, t) {
  if ((o.type === "Mesh" || o.type === "SkinnedMesh") && !ee(o)) {
    const s = ct(t);
    s.userData = { isRaycastMesh: !0 }, o[xe] = s;
  }
}
function ut(o = !0) {
  if (o) {
    if (Q) return;
    const t = Q = X.prototype.raycast;
    X.prototype.raycast = function(e, s) {
      const r = this, i = ee(r);
      let n;
      i && r.isMesh && (n = r.geometry, r.geometry = i), t.call(this, e, s), n && (r.geometry = n);
    };
  } else {
    if (!Q) return;
    X.prototype.raycast = Q, Q = null;
  }
}
let Q = null;
function ct(o) {
  const t = new V();
  for (const e in o.attributes)
    t.setAttribute(e, o.getAttribute(e));
  return t.setIndex(o.getIndex()), t;
}
const z = new Array(), f = N("debugprogressive");
let Z, E = -1;
if (f) {
  let o = function() {
    E += 1, E >= t && (E = -1), console.log(`Toggle LOD level [${E}]`);
  }, t = 6;
  window.addEventListener("keyup", (e) => {
    e.key === "p" && o(), e.key === "w" && (Z = !Z, console.log(`Toggle wireframe [${Z}]`));
    const s = parseInt(e.key);
    !isNaN(s) && s >= 0 && (E = s, console.log(`Set LOD level to [${E}]`));
  });
}
function Re(o) {
  if (f && Z !== void 0)
    if (Array.isArray(o))
      for (const t of o)
        Re(t);
    else o && "wireframe" in o && (o.wireframe = Z === !0);
}
const J = new Array();
let dt = 0;
const ft = ke() ? 2 : 10;
function ht(o) {
  if (J.length < ft) {
    const s = J.length;
    f && console.warn(`[Worker] Creating new worker #${s}`);
    const r = _e.createWorker(o || {});
    return J.push(r), r;
  }
  const t = dt++ % J.length;
  return J[t];
}
class _e {
  constructor(t, e) {
    this.worker = t, this._debug = e.debug ?? !1, t.onmessage = (s) => {
      const r = s.data;
      switch (this._debug && console.log("[Worker] EVENT", r), r.type) {
        case "loaded-gltf":
          for (const i of this._running)
            if (i.url === r.result.url) {
              gt(r.result), i.resolve(r.result);
              const n = i.url;
              n.startsWith("blob:") && URL.revokeObjectURL(n);
            }
      }
    }, t.onerror = (s) => {
      console.error("[Worker] Error in gltf-progressive worker:", s);
    }, t.postMessage({
      type: "init"
    });
  }
  static async createWorker(t) {
    const e = /* new-worker */ new Worker(URL.createObjectURL(new Blob(["import '" + `${new URL('./loader.worker-BqODMeeW.js', import.meta.url).toString()}` + "';"], { type: 'text/javascript' })), {
      type: "module"
    });
    return new _e(e, t);
  }
  _running = [];
  _webglRenderer = null;
  async load(t, e) {
    const s = Je();
    let r = e?.renderer;
    r || (this._webglRenderer ??= (async () => {
      const { WebGLRenderer: u } = await import("./three.js").then((c) => c.THREE);
      return new u();
    })(), r = await this._webglRenderer);
    const l = Le(r).ktx2Loader.workerConfig;
    t instanceof URL ? t = t.toString() : t.startsWith("file:") ? t = URL.createObjectURL(new Blob([t])) : !t.startsWith("blob:") && !t.startsWith("http:") && !t.startsWith("https:") && (t = new URL(t, window.location.href).toString());
    const a = {
      type: "load",
      url: t,
      dracoDecoderPath: s.dracoDecoderPath,
      ktx2TranscoderPath: s.ktx2TranscoderPath,
      ktx2LoaderConfig: l
    };
    return this._debug && console.debug("[Worker] Sending load request", a), this.worker.postMessage(a), new Promise((u) => {
      this._running.push({
        url: t.toString(),
        resolve: u
      });
    });
  }
  _debug = !1;
}
function gt(o) {
  for (const t of o.geometries) {
    const e = t.geometry, s = new V();
    if (s.name = e.name || "", e.index) {
      const r = e.index;
      s.setIndex(ue(r));
    }
    for (const r in e.attributes) {
      const i = e.attributes[r], n = ue(i);
      s.setAttribute(r, n);
    }
    if (e.morphAttributes)
      for (const r in e.morphAttributes) {
        const n = e.morphAttributes[r].map((l) => ue(l));
        s.morphAttributes[r] = n;
      }
    if (s.morphTargetsRelative = e.morphTargetsRelative ?? !1, s.boundingBox = new pe(), s.boundingBox.min = new A(
      e.boundingBox?.min.x,
      e.boundingBox?.min.y,
      e.boundingBox?.min.z
    ), s.boundingBox.max = new A(
      e.boundingBox?.max.x,
      e.boundingBox?.max.y,
      e.boundingBox?.max.z
    ), s.boundingSphere = new Se(
      new A(
        e.boundingSphere?.center.x,
        e.boundingSphere?.center.y,
        e.boundingSphere?.center.z
      ),
      e.boundingSphere?.radius
    ), e.groups)
      for (const r of e.groups)
        s.addGroup(r.start, r.count, r.materialIndex);
    e.userData && (s.userData = e.userData), t.geometry = s;
  }
  for (const t of o.textures) {
    const e = t.texture;
    let s = null;
    if (e.isCompressedTexture) {
      const r = e.mipmaps, i = e.image?.width || e.source?.data?.width || -1, n = e.image?.height || e.source?.data?.height || -1;
      s = new Fe(
        r,
        i,
        n,
        e.format,
        e.type,
        e.mapping,
        e.wrapS,
        e.wrapT,
        e.magFilter,
        e.minFilter,
        e.anisotropy,
        e.colorSpace
      );
    } else
      s = new F(
        e.image,
        e.mapping,
        e.wrapS,
        e.wrapT,
        e.magFilter,
        e.minFilter,
        e.format,
        e.type,
        e.anisotropy,
        e.colorSpace
      ), s.mipmaps = e.mipmaps, s.channel = e.channel, s.source.data = e.source.data, s.flipY = e.flipY, s.premultiplyAlpha = e.premultiplyAlpha, s.unpackAlignment = e.unpackAlignment, s.matrix = new We(...e.matrix.elements);
    if (!s) {
      console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");
      continue;
    }
    t.texture = s;
  }
  return o;
}
function ue(o) {
  let t = o;
  if ("isInterleavedBufferAttribute" in o && o.isInterleavedBufferAttribute) {
    const e = o.data, s = e.array, r = new Ue(s, e.stride);
    t = new ze(r, o.itemSize, s.byteOffset, o.normalized), t.offset = o.offset;
  } else "isBufferAttribute" in o && o.isBufferAttribute && (t = new Ne(o.array, o.itemSize, o.normalized), t.usage = o.usage, t.gpuType = o.gpuType, t.updateRanges = o.updateRanges);
  return t;
}
const pt = N("gltf-progressive-worker");
N("gltf-progressive-reduce-mipmaps");
const K = N("gltf-progressive-gc"), ce = /* @__PURE__ */ Symbol("needle-progressive-texture"), W = "NEEDLE_progressive";
class y {
  /** The name of the extension */
  get name() {
    return W;
  }
  // #region PUBLIC API
  static getMeshLODExtension(t) {
    const e = this.getAssignedLODInformation(t);
    return e?.key ? this.lodInfos.get(e.key) : null;
  }
  static getPrimitiveIndex(t) {
    const e = this.getAssignedLODInformation(t)?.index;
    return e ?? -1;
  }
  static getMaterialMinMaxLODsCount(t, e) {
    const s = this, r = "LODS:minmax", i = t[r];
    if (i != null) return i;
    if (e || (e = {
      min_count: 1 / 0,
      max_count: 0,
      lods: []
    }), Array.isArray(t)) {
      for (const l of t)
        this.getMaterialMinMaxLODsCount(l, e);
      return t[r] = e, e;
    }
    if (f === "verbose" && console.log("getMaterialMinMaxLODsCount", t), t.type === "ShaderMaterial" || t.type === "RawShaderMaterial") {
      const l = t;
      for (const a of Object.keys(l.uniforms)) {
        const u = l.uniforms[a].value;
        u?.isTexture === !0 && n(u, e);
      }
    } else if (t.isMaterial)
      for (const l of Object.keys(t)) {
        const a = t[l];
        a?.isTexture === !0 && n(a, e);
      }
    else
      f && console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${t.type}`);
    return t[r] = e, e;
    function n(l, a) {
      const u = s.getAssignedLODInformation(l);
      if (u) {
        const c = s.lodInfos.get(u.key);
        if (c && c.lods) {
          a.min_count = Math.min(a.min_count, c.lods.length), a.max_count = Math.max(a.max_count, c.lods.length);
          for (let m = 0; m < c.lods.length; m++) {
            const w = c.lods[m];
            w.width && (a.lods[m] = a.lods[m] || { min_height: 1 / 0, max_height: 0 }, a.lods[m].min_height = Math.min(a.lods[m].min_height, w.height), a.lods[m].max_height = Math.max(a.lods[m].max_height, w.height));
          }
        }
      }
    }
  }
  /** Check if a LOD level is available for a mesh or a texture
   * @param obj the mesh or texture to check
   * @param level the level of detail to check for (0 is the highest resolution). If undefined, the function checks if any LOD level is available
   * @returns true if the LOD level is available (or if any LOD level is available if level is undefined)
   */
  static hasLODLevelAvailable(t, e) {
    if (Array.isArray(t)) {
      for (const i of t)
        if (this.hasLODLevelAvailable(i, e)) return !0;
      return !1;
    }
    if (t.isMaterial === !0) {
      for (const i of Object.keys(t)) {
        const n = t[i];
        if (n && n.isTexture && this.hasLODLevelAvailable(n, e))
          return !0;
      }
      return !1;
    } else if (t.isGroup === !0) {
      for (const i of t.children)
        if (i.isMesh === !0 && this.hasLODLevelAvailable(i, e))
          return !0;
    }
    let s, r;
    if (t.isMesh ? s = t.geometry : (t.isBufferGeometry || t.isTexture) && (s = t), s && s?.userData?.LODS) {
      const i = s.userData.LODS;
      if (r = this.lodInfos.get(i.key), e === void 0) return r != null;
      if (r)
        return Array.isArray(r.lods) ? e < r.lods.length : e === 0;
    }
    return !1;
  }
  /** Load a different resolution of a mesh (if available)
   * @param context the context
   * @param source the sourceid of the file from which the mesh is loaded (this is usually the component's sourceId)
   * @param mesh the mesh to load the LOD for
   * @param level the level of detail to load (0 is the highest resolution)
   * @returns a promise that resolves to the mesh with the requested LOD level
   * @example
   * ```javascript
   * const mesh = this.gameObject as Mesh;
   * NEEDLE_progressive.assignMeshLOD(context, sourceId, mesh, 1).then(mesh => {
   *    console.log("Mesh with LOD level 1 loaded", mesh);
   * });
   * ```
   */
  static assignMeshLOD(t, e) {
    if (!t) return Promise.resolve(null);
    if (t instanceof X || t.isMesh === !0) {
      const s = t.geometry, r = this.getAssignedLODInformation(s);
      if (!r)
        return Promise.resolve(null);
      for (const i of z)
        i.onBeforeGetLODMesh?.(t, e);
      return t["LOD:requested level"] = e, y.getOrLoadLOD(s, e).then((i) => {
        if (Array.isArray(i)) {
          const n = r.index || 0;
          i = i[n];
        }
        return t["LOD:requested level"] === e && (delete t["LOD:requested level"], i && s != i && (i?.isBufferGeometry ? t.geometry = i : f && console.error("Invalid LOD geometry", i))), i;
      }).catch((i) => (console.error("Error loading mesh LOD", t, i), null));
    } else f && console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh", t);
    return Promise.resolve(null);
  }
  static assignTextureLOD(t, e = 0) {
    if (!t) return Promise.resolve(null);
    if (t.isMesh === !0) {
      const s = t;
      if (Array.isArray(s.material)) {
        const r = new Array();
        for (const i of s.material) {
          const n = this.assignTextureLOD(i, e);
          r.push(n);
        }
        return Promise.all(r).then((i) => {
          const n = new Array();
          for (const l of i)
            Array.isArray(l) && n.push(...l);
          return n;
        });
      } else
        return this.assignTextureLOD(s.material, e);
    }
    if (t.isMaterial === !0) {
      const s = t, r = [], i = new Array();
      if (s.uniforms && (s.isRawShaderMaterial || s.isShaderMaterial === !0)) {
        const n = s;
        for (const l of Object.keys(n.uniforms)) {
          const a = n.uniforms[l].value;
          if (a?.isTexture === !0) {
            const u = this.assignTextureLODForSlot(a, e, s, l).then((c) => (c && n.uniforms[l].value != c && (n.uniforms[l].value = c, n.uniformsNeedUpdate = !0), c));
            r.push(u), i.push(l);
          }
        }
      } else
        for (const n of Object.keys(s)) {
          const l = s[n];
          if (l?.isTexture === !0) {
            const a = this.assignTextureLODForSlot(l, e, s, n);
            r.push(a), i.push(n);
          }
        }
      return Promise.all(r).then((n) => {
        const l = new Array();
        for (let a = 0; a < n.length; a++) {
          const u = n[a], c = i[a];
          u && u.isTexture === !0 ? l.push({ material: s, slot: c, texture: u, level: e }) : l.push({ material: s, slot: c, texture: null, level: e });
        }
        return l;
      });
    }
    if (t instanceof F || t.isTexture === !0) {
      const s = t;
      return this.assignTextureLODForSlot(s, e, null, null);
    }
    return Promise.resolve(null);
  }
  // #region INTERNAL
  static assignTextureLODForSlot(t, e, s, r) {
    return t?.isTexture !== !0 ? Promise.resolve(null) : r === "glyphMap" ? Promise.resolve(t) : y.getOrLoadLOD(t, e).then((i) => {
      if (Array.isArray(i))
        return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."), null;
      if (i?.isTexture === !0) {
        if (i != t && s && r) {
          const n = s[r];
          if (n && !f) {
            const l = this.getAssignedLODInformation(n);
            if (l && l?.level < e)
              return f === "verbose" && console.warn("Assigned texture level is already higher: ", l.level, e, s, n, i), i && i !== n && ((f || K) && console.log(`[gltf-progressive] Disposing rejected lower-quality texture LOD ${e} (assigned is ${l.level})`, i.uuid), i.dispose()), null;
          }
          if (this.trackTextureUsage(i), n && n !== i && this.untrackTextureUsage(n) && (f || K)) {
            const a = this.getAssignedLODInformation(n);
            console.log(`[gltf-progressive] Disposed old texture LOD ${a?.level ?? "?"} → ${e} for ${s.name || s.type}.${r}`, n.uuid);
          }
          s[r] = i;
        }
        return i;
      } else f == "verbose" && console.warn("No LOD found for", t, e);
      return null;
    }).catch((i) => (console.error("Error loading LOD", t, i), null));
  }
  parser;
  url;
  constructor(t) {
    const e = t.options.path;
    f && console.log("Progressive extension registered for", e), this.parser = t, this.url = e;
  }
  _isLoadingMesh;
  loadMesh = (t) => {
    if (this._isLoadingMesh) return null;
    const e = this.parser.json.meshes[t]?.extensions?.[W];
    return e ? (this._isLoadingMesh = !0, this.parser.getDependency("mesh", t).then((s) => (this._isLoadingMesh = !1, s && y.registerMesh(this.url, e.guid, s, e.lods?.length, 0, e), s))) : null;
  };
  // private _isLoadingTexture;
  // loadTexture = (textureIndex: number) => {
  //     if (this._isLoadingTexture) return null;
  //     const ext = this.parser.json.textures[textureIndex]?.extensions?.[EXTENSION_NAME] as NEEDLE_ext_progressive_texture;
  //     if (!ext) return null;
  //     this._isLoadingTexture = true;
  //     return this.parser.getDependency("texture", textureIndex).then(tex => {
  //         this._isLoadingTexture = false;
  //         if (tex) {
  //             NEEDLE_progressive.registerTexture(this.url, tex as Texture, ext.lods?.length, textureIndex, ext);
  //         }
  //         return tex;
  //     });
  // }
  afterRoot(t) {
    return f && console.log("AFTER", this.url, t), this.parser.json.textures?.forEach((e, s) => {
      if (e?.extensions) {
        const r = e?.extensions[W];
        if (r) {
          if (!r.lods) {
            f && console.warn("Texture has no LODs", r);
            return;
          }
          let i = !1;
          for (const n of this.parser.associations.keys())
            n.isTexture === !0 && this.parser.associations.get(n)?.textures === s && (i = !0, y.registerTexture(this.url, n, r.lods?.length, s, r));
          i || this.parser.getDependency("texture", s).then((n) => {
            n && y.registerTexture(this.url, n, r.lods?.length, s, r);
          });
        }
      }
    }), this.parser.json.meshes?.forEach((e, s) => {
      if (e?.extensions) {
        const r = e?.extensions[W];
        if (r && r.lods) {
          for (const i of this.parser.associations.keys())
            if (i.isMesh) {
              const n = this.parser.associations.get(i);
              n?.meshes === s && y.registerMesh(this.url, r.guid, i, r.lods.length, n.primitives, r);
            }
        }
      }
    }), null;
  }
  /**
   * Register a texture with LOD information
   */
  static registerTexture = (t, e, s, r, i) => {
    if (!e) {
      f && console.error("!! gltf-progressive: Called register texture without texture");
      return;
    }
    if (f) {
      const l = e.image?.width || e.source?.data?.width || 0, a = e.image?.height || e.source?.data?.height || 0;
      console.log(`> gltf-progressive: register texture[${r}] "${e.name || e.uuid}", Current: ${l}x${a}, Max: ${i.lods[0]?.width}x${i.lods[0]?.height}, uuid: ${e.uuid}`, i, e);
    }
    e.source && (e.source[ce] = i);
    const n = i.guid;
    y.assignLODInformation(t, e, n, s, r), y.lodInfos.set(n, i), y.lowresCache.set(n, new WeakRef(e));
  };
  /**
   * Register a mesh with LOD information
   */
  static registerMesh = (t, e, s, r, i, n) => {
    const l = s.geometry;
    if (!l) {
      f && console.warn("gltf-progressive: Register mesh without geometry");
      return;
    }
    l.userData || (l.userData = {}), f && console.log("> Progressive: register mesh " + s.name, { index: i, uuid: s.uuid }, n, s), y.assignLODInformation(t, l, e, r, i), y.lodInfos.set(e, n);
    let u = y.lowresCache.get(e)?.deref();
    u ? u.push(s.geometry) : u = [s.geometry], y.lowresCache.set(e, new WeakRef(u)), r > 0 && !ee(s) && lt(s, l);
    for (const c of z)
      c.onRegisteredNewMesh?.(s, n);
  };
  /**
   * Dispose cached resources to free memory.
   * Call this when a model is removed from the scene to allow garbage collection of its LOD resources.
   * Calls three.js `.dispose()` on cached Textures and BufferGeometries to free GPU memory.
   * Also clears reference counts for disposed textures.
   * @param guid Optional GUID to dispose resources for a specific model. If omitted, all cached resources are cleared.
   */
  static dispose(t) {
    if (t) {
      this.lodInfos.delete(t);
      const e = this.lowresCache.get(t);
      if (e) {
        const s = e.deref();
        if (s) {
          if (s.isTexture) {
            const r = s;
            this.textureRefCounts.delete(r.uuid), r.dispose();
          } else if (Array.isArray(s))
            for (const r of s) r.dispose();
        }
        this.lowresCache.delete(t);
      }
      for (const [s, r] of this.cache)
        s.includes(t) && (this._disposeCacheEntry(r), this.cache.delete(s));
    } else {
      this.lodInfos.clear();
      for (const [, e] of this.lowresCache) {
        const s = e.deref();
        if (s) {
          if (s.isTexture) {
            const r = s;
            this.textureRefCounts.delete(r.uuid), r.dispose();
          } else if (Array.isArray(s))
            for (const r of s) r.dispose();
        }
      }
      this.lowresCache.clear();
      for (const [, e] of this.cache)
        this._disposeCacheEntry(e);
      this.cache.clear(), this.textureRefCounts.clear();
    }
  }
  /** Dispose a single cache entry's three.js resource(s) to free GPU memory. */
  static _disposeCacheEntry(t) {
    if (t instanceof WeakRef) {
      const e = t.deref();
      e && (e.isTexture && this.textureRefCounts.delete(e.uuid), e.dispose());
    } else
      t.then((e) => {
        if (e)
          if (Array.isArray(e))
            for (const s of e) s.dispose();
          else
            e.isTexture && this.textureRefCounts.delete(e.uuid), e.dispose();
      }).catch(() => {
      });
  }
  /** A map of key = asset uuid and value = LOD information */
  static lodInfos = /* @__PURE__ */ new Map();
  /** cache of already loaded mesh lods. Uses WeakRef for single resources to allow garbage collection when unused. */
  static cache = /* @__PURE__ */ new Map();
  /** this contains the geometry/textures that were originally loaded. Uses WeakRef to allow garbage collection when unused. */
  static lowresCache = /* @__PURE__ */ new Map();
  /** Reference counting for textures to track usage across multiple materials/objects */
  static textureRefCounts = /* @__PURE__ */ new Map();
  /**
   * FinalizationRegistry to automatically clean up `previouslyLoaded` cache entries
   * when their associated three.js resources are garbage collected by the browser.
   * The held value is the cache key string used in `previouslyLoaded`.
   */
  static _resourceRegistry = new FinalizationRegistry((t) => {
    const e = y.cache.get(t);
    (f || K) && console.debug(`[gltf-progressive] Memory: Resource GC'd
${t}`), e instanceof WeakRef && (e.deref() || (y.cache.delete(t), (f || K) && console.log("[gltf-progressive] ↪ Cache entry deleted (GC)")));
  });
  /**
   * Track texture usage by incrementing reference count
   */
  static trackTextureUsage(t) {
    const e = t.uuid, s = this.textureRefCounts.get(e) || 0;
    this.textureRefCounts.set(e, s + 1), f === "verbose" && console.log(`[gltf-progressive] Track texture ${e}, refCount: ${s} → ${s + 1}`);
  }
  /**
   * Untrack texture usage by decrementing reference count.
   * Automatically disposes the texture when reference count reaches zero.
   * @returns true if the texture was disposed, false otherwise
   */
  static untrackTextureUsage(t) {
    const e = t.uuid, s = this.textureRefCounts.get(e);
    if (!s)
      return (f === "verbose" || K) && i("[gltf-progressive] Memory: Untrack untracked texture (dispose immediately)", 0), t.dispose(), !0;
    const r = s - 1;
    if (r <= 0)
      return this.textureRefCounts.delete(e), (f || K) && i("[gltf-progressive] Memory: Dispose texture", r), t.dispose(), !0;
    return this.textureRefCounts.set(e, r), f === "verbose" && i("[gltf-progressive] Memory: Untrack texture", r), !1;
    function i(n, l) {
      let a = t.image?.width || t.source?.data?.width || 0, u = t.image?.height || t.source?.data?.height || 0;
      const c = a && u ? `${a}x${u}` : "N/A";
      let m = "N/A";
      a && u && (m = `~${(nt(t) / (1024 * 1024)).toFixed(2)} MB`), console.log(`${n} — ${t.name} ${c} (${m}), refCount: ${s} → ${l}
${e}`);
    }
  }
  static workers = [];
  static _workersIndex = 0;
  static async getOrLoadLOD(t, e) {
    const s = f == "verbose", r = this.getAssignedLODInformation(t);
    if (!r)
      return f && console.warn(`[gltf-progressive] No LOD information found: ${t.name}, uuid: ${t.uuid}, type: ${t.type}`, t), null;
    const i = r?.key;
    let n;
    if (t.isTexture === !0) {
      const a = t;
      a.source && a.source[ce] && (n = a.source[ce]);
    }
    if (n || (n = y.lodInfos.get(i)), !n)
      f && console.warn(`Can not load LOD ${e}: no LOD info found for "${i}" ${t.name}`, t.type, y.lodInfos);
    else {
      if (e > 0) {
        let c = !1;
        const m = Array.isArray(n.lods);
        if (m && e >= n.lods.length ? c = !0 : m || (c = !0), c) {
          const w = this.lowresCache.get(i);
          if (w) {
            const L = w.deref();
            if (L) return L;
            this.lowresCache.delete(i), f && console.log(`[gltf-progressive] Lowres cache entry was GC'd: ${i}`);
          }
          return null;
        }
      }
      const a = Array.isArray(n.lods) ? n.lods[e]?.path : n.lods;
      if (!a)
        return f && !n["missing:uri"] && (n["missing:uri"] = !0, console.warn("Missing uri for progressive asset for LOD " + e, n)), null;
      const u = rt(r.url, a);
      if (u.endsWith(".glb") || u.endsWith(".gltf")) {
        if (!n.guid)
          return console.warn("missing pointer for glb/gltf texture", n), null;
        const c = u + "_" + n.guid, m = await this.queue.slot(u), w = this.cache.get(c);
        if (w !== void 0)
          if (s && console.log(`LOD ${e} was already loading/loaded: ${c}`), w instanceof WeakRef) {
            const d = w.deref();
            if (d) {
              let g = d, M = !1;
              if (g instanceof F && t instanceof F ? g.image?.data || g.source?.data ? g = this.copySettings(t, g) : M = !0 : g instanceof V && t instanceof V && (g.attributes.position?.array || (M = !0)), !M)
                return g;
            }
            this.cache.delete(c), f && console.log(`[gltf-progressive] Re-loading GC'd/disposed resource: ${c}`);
          } else {
            let d = await w.catch((M) => (console.error(`Error loading LOD ${e} from ${u}
`, M), null)), g = !1;
            if (d == null || (d instanceof F && t instanceof F ? d.image?.data || d.source?.data ? d = this.copySettings(t, d) : (g = !0, this.cache.delete(c)) : d instanceof V && t instanceof V && (d.attributes.position?.array || (g = !0, this.cache.delete(c)))), !g)
              return d;
          }
        if (!m.use)
          return f && console.log(`LOD ${e} was aborted: ${u}`), null;
        const L = n, k = new Promise(async (d, g) => {
          if (pt) {
            const x = await (await ht({})).load(u);
            if (x.textures.length > 0)
              for (const h of x.textures) {
                let p = h.texture;
                return y.assignLODInformation(r.url, p, i, e, void 0), t instanceof F && (p = this.copySettings(t, p)), p && (p.guid = L.guid), d(p);
              }
            if (x.geometries.length > 0) {
              const h = new Array();
              for (const p of x.geometries) {
                const b = p.geometry;
                y.assignLODInformation(r.url, b, i, e, p.primitiveIndex), h.push(b);
              }
              return d(h);
            }
            return d(null);
          }
          const M = new we();
          Te(M), f && (await new Promise((_) => setTimeout(_, 1e3)), s && console.warn("Start loading (delayed) " + u, L.guid));
          let B = u;
          if (L && Array.isArray(L.lods)) {
            const _ = L.lods[e];
            _.hash && (B += "?v=" + _.hash);
          }
          const D = await M.loadAsync(B).catch((_) => (console.error(`Error loading LOD ${e} from ${u}
`, _), d(null)));
          if (!D)
            return d(null);
          const q = D.parser;
          s && console.log("Loading finished " + u, L.guid);
          let P = 0;
          if (D.parser.json.textures) {
            let _ = !1;
            for (const x of D.parser.json.textures) {
              if (x?.extensions) {
                const h = x?.extensions[W];
                if (h?.guid && h.guid === L.guid) {
                  _ = !0;
                  break;
                }
              }
              P++;
            }
            if (_) {
              let x = await q.getDependency("texture", P);
              return x && y.assignLODInformation(r.url, x, i, e, void 0), s && console.log('change "' + t.name + '" → "' + x.name + '"', u, P, x, c), t instanceof F && (x = this.copySettings(t, x)), x && (x.guid = L.guid), d(x);
            } else f && console.warn("Could not find texture with guid", L.guid, D.parser.json);
          }
          if (P = 0, D.parser.json.meshes) {
            let _ = !1;
            for (const x of D.parser.json.meshes) {
              if (x?.extensions) {
                const h = x?.extensions[W];
                if (h?.guid && h.guid === L.guid) {
                  _ = !0;
                  break;
                }
              }
              P++;
            }
            if (_) {
              const x = await q.getDependency("mesh", P);
              if (s && console.log(`Loaded Mesh "${x.name}"`, u, P, x, c), x.isMesh === !0) {
                const h = x.geometry;
                return y.assignLODInformation(r.url, h, i, e, 0), d(h);
              } else {
                const h = new Array();
                for (let p = 0; p < x.children.length; p++) {
                  const b = x.children[p];
                  if (b.isMesh === !0) {
                    const S = b.geometry;
                    y.assignLODInformation(r.url, S, i, e, p), h.push(S);
                  }
                }
                return d(h);
              }
            } else f && console.warn("Could not find mesh with guid", L.guid, D.parser.json);
          }
          return d(null);
        });
        this.cache.set(c, k), m.use(k);
        const v = await k;
        return v != null ? v instanceof F ? (this.cache.set(c, new WeakRef(v)), y._resourceRegistry.register(v, c)) : Array.isArray(v) ? this.cache.set(c, Promise.resolve(v)) : this.cache.set(c, Promise.resolve(v)) : this.cache.set(c, Promise.resolve(null)), v;
      } else if (t instanceof F) {
        s && console.log("Load texture from uri: " + u);
        const m = await new qe().loadAsync(u);
        return m ? (m.guid = n.guid, m.flipY = !1, m.needsUpdate = !0, m.colorSpace = t.colorSpace, s && console.log(n, m)) : f && console.warn("failed loading", u), m;
      }
    }
    return null;
  }
  static maxConcurrent = 50;
  static queue = new it(y.maxConcurrent, { debug: f != !1 });
  static assignLODInformation(t, e, s, r, i) {
    if (!e) return;
    e.userData || (e.userData = {});
    const n = new mt(t, s, r, i);
    e.userData.LODS = n, "source" in e && typeof e.source == "object" && (e.source.LODS = n);
  }
  static getAssignedLODInformation(t) {
    return t ? t.userData?.LODS ? t.userData.LODS : "source" in t && t.source?.LODS ? t.source.LODS : null : null;
  }
  // private static readonly _copiedTextures: WeakMap<Texture, Texture> = new Map();
  static copySettings(t, e) {
    return e ? (f === "verbose" && console.debug(`Copy texture settings
`, t.uuid, `
`, e.uuid), e = e.clone(), e.offset = t.offset, e.repeat = t.repeat, e.colorSpace = t.colorSpace, e.magFilter = t.magFilter, e.minFilter = t.minFilter, e.wrapS = t.wrapS, e.wrapT = t.wrapT, e.flipY = t.flipY, e.anisotropy = t.anisotropy, e.mipmaps || (e.generateMipmaps = t.generateMipmaps), e) : t;
  }
}
class mt {
  url;
  /** the key to lookup the LOD information */
  key;
  level;
  /** For multi objects (e.g. a group of meshes) this is the index of the object */
  index;
  constructor(t, e, s, r) {
    this.url = t, this.key = e, this.level = s, r != null && (this.index = r);
  }
}
class de {
  static addPromise = (t, e, s, r) => {
    r.forEach((i) => {
      i.add(t, e, s);
    });
  };
  ready;
  /** The number of promises that have been added to this group so far */
  get awaitedCount() {
    return this._addedCount;
  }
  /** The number of promises that have been resolved */
  get resolvedCount() {
    return this._resolvedCount;
  }
  /** The number of promises that are in-flight */
  get currentlyAwaiting() {
    return this._awaiting.length;
  }
  _resolve;
  _signal;
  /** start frame can be undefined if the user configured this group to wait for the first promise.
   * Then the start frame will be set when the first promise has been added to the group */
  _frame_start;
  /** How many frames to capture since the start frame */
  _frames_to_capture;
  _resolved = !1;
  _addedCount = 0;
  _resolvedCount = 0;
  /** These promises are currently being awaited */
  _awaiting = [];
  _maxPromisesPerObject = 1;
  constructor(t, e) {
    const r = Math.max(e.frames ?? 2, 2);
    this._frame_start = e.waitForFirstCapture ? void 0 : t, this._frames_to_capture = r, this.ready = new Promise((i) => {
      this._resolve = i;
    }), this.ready.finally(() => {
      this._resolved = !0, this._awaiting.length = 0;
    }), this._signal = e.signal, this._signal?.addEventListener("abort", () => {
      this.resolveNow();
    }), this._maxPromisesPerObject = Math.max(1, e.maxPromisesPerObject ?? 1);
  }
  _currentFrame = 0;
  update(t) {
    this._currentFrame = t, this._frame_start === void 0 && this._addedCount > 0 && (this._frame_start = t), (this._signal?.aborted || this._awaiting.length === 0 && this._frame_start !== void 0 && t > this._frame_start + this._frames_to_capture) && this.resolveNow();
  }
  _seen = /* @__PURE__ */ new WeakMap();
  add(t, e, s) {
    if (this._resolved) {
      f && console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");
      return;
    }
    if (!(this._frame_start !== void 0 && this._currentFrame > this._frame_start + this._frames_to_capture)) {
      if (this._maxPromisesPerObject >= 1)
        if (this._seen.has(e)) {
          let r = this._seen.get(e);
          if (r >= this._maxPromisesPerObject) {
            f && console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");
            return;
          }
          this._seen.set(e, r + 1);
        } else
          this._seen.set(e, 1);
      this._awaiting.push(s), this._addedCount++, s.finally(() => {
        this._resolvedCount++, this._awaiting.splice(this._awaiting.indexOf(s), 1);
      });
    }
  }
  resolveNow() {
    this._resolved || this._resolve?.({
      awaited_count: this._addedCount,
      resolved_count: this._resolvedCount,
      cancelled: this._signal?.aborted ?? !1
    });
  }
}
const R = N("debugprogressive"), yt = N("noprogressive"), fe = /* @__PURE__ */ Symbol("Needle:LODSManager"), he = /* @__PURE__ */ Symbol("Needle:LODState"), U = /* @__PURE__ */ Symbol("Needle:CurrentLOD"), T = { mesh_lod: -1, texture_lod: -1 };
let oe = class O {
  /** 
   * Assign a function to draw debug lines for the LODs. This function will be called with the start and end position of the line and the color of the line when the `debugprogressive` query parameter is set.
   */
  static debugDrawLine;
  /** @internal */
  static getObjectLODState(t) {
    return t[he];
  }
  static addPlugin(t) {
    z.push(t);
  }
  static removePlugin(t) {
    const e = z.indexOf(t);
    e >= 0 && z.splice(e, 1);
  }
  /**
   * Gets the LODsManager for the given renderer. If the LODsManager does not exist yet, it will be created.  
   * @param renderer The renderer to get the LODsManager for.
   * @returns The LODsManager instance.
   */
  static get(t, e) {
    if (t[fe])
      return console.debug("[gltf-progressive] LODsManager already exists for this renderer"), t[fe];
    const s = new O(t, {
      engine: "unknown",
      ...e
    });
    return t[fe] = s, s;
  }
  renderer;
  context;
  projectionScreenMatrix = new Me();
  /** @deprecated use static `LODsManager.addPlugin()` method. This getter will be removed in later versions */
  get plugins() {
    return z;
  }
  /**
   * Force override the LOD level for all objects (meshes + textures) rendered in the scene
   * @default undefined automatically calculate LOD level
   */
  overrideLodLevel = void 0;
  /**
   * The target triangle density is the desired max amount of triangles on screen when the mesh is filling the screen.  
   * @default 200_000
   */
  targetTriangleDensity = 2e5;
  /**
   * The interval in frames to automatically update the bounds of skinned meshes.   
   * Set to 0 or a negative value to disable automatic bounds updates. 
   * @default 30
   */
  skinnedMeshAutoUpdateBoundsInterval = 30;
  /**
   * The update interval in frames. If set to 0, the LODs will be updated every frame. If set to 2, the LODs will be updated every second frame, etc.
   * @default "auto"
   */
  updateInterval = "auto";
  #e = 1;
  /**
   * If set to true, the LODsManager will not update the LODs.
   * @default false
   */
  pause = !1;
  /**
   * When set to true the LODsManager will not update the LODs. This can be used to manually update the LODs using the `update` method.  
   * Otherwise the LODs will be updated automatically when the renderer renders the scene.
   * @default false
   */
  manual = !1;
  _newPromiseGroups = [];
  _promiseGroupIds = 0;
  /**
   * Call to await LODs loading during the next render cycle.
   */
  awaitLoading(t) {
    const e = this._promiseGroupIds++, s = new de(this.#r, { ...t });
    this._newPromiseGroups.push(s);
    const r = performance.now();
    return s.ready.finally(() => {
      const i = this._newPromiseGroups.indexOf(s);
      i >= 0 && (this._newPromiseGroups.splice(i, 1), ve() && performance.measure("LODsManager:awaitLoading", {
        start: r,
        detail: { id: e, name: t?.name, awaited: s.awaitedCount, resolved: s.resolvedCount }
      }));
    }), s.ready;
  }
  _postprocessPromiseGroups() {
    if (this._newPromiseGroups.length !== 0)
      for (let t = this._newPromiseGroups.length - 1; t >= 0; t--)
        this._newPromiseGroups[t].update(this.#r);
  }
  _lodchangedlisteners = [];
  addEventListener(t, e) {
    t === "changed" && this._lodchangedlisteners.push(e);
  }
  removeEventListener(t, e) {
    if (t === "changed") {
      const s = this._lodchangedlisteners.indexOf(e);
      s >= 0 && this._lodchangedlisteners.splice(s, 1);
    }
  }
  // readonly plugins: NEEDLE_progressive_plugin[] = [];
  constructor(t, e) {
    this.renderer = t, this.context = { ...e };
  }
  #t;
  #n = new Ee();
  #r = 0;
  #i = 0;
  #o = 0;
  #s = 0;
  _fpsBuffer = [60, 60, 60, 60, 60];
  /**
   * Enable the LODsManager. This will replace the render method of the renderer with a method that updates the LODs.
   */
  enable() {
    if (this.#t) return;
    console.debug("[gltf-progressive] Enabling LODsManager for renderer");
    let t = 0;
    this.#t = this.renderer.render;
    const e = this;
    Le(this.renderer), this.renderer.render = function(s, r) {
      const i = e.renderer.getRenderTarget();
      (i == null || "isXRRenderTarget" in i && i.isXRRenderTarget) && (t = 0, e.#r += 1, e.#i = e.#n.getDelta(), e.#o += e.#i, e._fpsBuffer.shift(), e._fpsBuffer.push(1 / e.#i), e.#s = e._fpsBuffer.reduce((l, a) => l + a) / e._fpsBuffer.length, R && e.#r % 200 === 0 && console.log("FPS", Math.round(e.#s), "Interval:", e.#e));
      const n = t++;
      e.#t.call(this, s, r), e.onAfterRender(s, r, n);
    };
  }
  disable() {
    this.#t && (console.debug("[gltf-progressive] Disabling LODsManager for renderer"), this.renderer.render = this.#t, this.#t = void 0);
  }
  update(t, e) {
    this.internalUpdate(t, e);
  }
  onAfterRender(t, e, s) {
    if (this.pause) return;
    const i = this.renderer.renderLists.get(t, 0).opaque;
    let n = !0;
    if (i.length === 1) {
      const l = i[0].material;
      (l.name === "EffectMaterial" || l.name === "CopyShader") && (n = !1);
    }
    if ((e.parent && e.parent.type === "CubeCamera" || s >= 1 && e.type === "OrthographicCamera") && (n = !1), n) {
      if (yt || (this.updateInterval === "auto" ? this.#s < 40 && this.#e < 10 ? (this.#e += 1, R && console.warn("↓ Reducing LOD updates", this.#e, this.#s.toFixed(0))) : this.#s >= 60 && this.#e > 1 && (this.#e -= 1, R && console.warn("↑ Increasing LOD updates", this.#e, this.#s.toFixed(0))) : this.#e = this.updateInterval, this.#e > 0 && this.#r % this.#e != 0))
        return;
      this.internalUpdate(t, e), this._postprocessPromiseGroups();
    }
  }
  /**
   * Update LODs in a scene
   */
  internalUpdate(t, e) {
    const s = this.renderer.renderLists.get(t, 0), r = s.opaque;
    this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix, e.matrixWorldInverse);
    const i = this.targetTriangleDensity;
    for (const a of r) {
      if (a.material && (a.geometry?.type === "BoxGeometry" || a.geometry?.type === "BufferGeometry") && (a.material.name === "SphericalGaussianBlur" || a.material.name == "BackgroundCubeMaterial" || a.material.name === "CubemapFromEquirect" || a.material.name === "EquirectangularToCubeUV")) {
        R && (a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] || (a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] = !0, console.warn("Ignoring skybox or BLIT object", a, a.material.name, a.material.type)));
        continue;
      }
      switch (a.material.type) {
        case "LineBasicMaterial":
        case "LineDashedMaterial":
        case "PointsMaterial":
        case "ShadowMaterial":
        case "MeshDistanceMaterial":
        case "MeshDepthMaterial":
          continue;
      }
      if (R === "color" && a.material && !a.object.progressive_debug_color) {
        a.object.progressive_debug_color = !0;
        const c = Math.random() * 16777215, m = new Ve({ color: c });
        a.object.material = m;
      }
      const u = a.object;
      (u instanceof X || u.isMesh) && this.updateLODs(t, e, u, i);
    }
    const n = s.transparent;
    for (const a of n) {
      const u = a.object;
      (u instanceof X || u.isMesh) && this.updateLODs(t, e, u, i);
    }
    const l = s.transmissive;
    for (const a of l) {
      const u = a.object;
      (u instanceof X || u.isMesh) && this.updateLODs(t, e, u, i);
    }
  }
  /** Update the LOD levels for the renderer. */
  updateLODs(t, e, s, r) {
    s.userData || (s.userData = {});
    let i = s[he];
    if (i || (i = new xt(), s[he] = i), i.frames++ < 2)
      return;
    for (const l of z)
      l.onBeforeUpdateLOD?.(this.renderer, t, e, s);
    const n = this.overrideLodLevel !== void 0 ? this.overrideLodLevel : E;
    n >= 0 ? (T.mesh_lod = n, T.texture_lod = n) : (this.calculateLodLevel(e, s, i, r, T), T.mesh_lod = Math.round(T.mesh_lod), T.texture_lod = Math.round(T.texture_lod)), T.mesh_lod >= 0 && this.loadProgressiveMeshes(s, T.mesh_lod), s.material && T.texture_lod >= 0 && this.loadProgressiveTextures(s.material, T.texture_lod, n), f && s.material && !s.isGizmo && Re(s.material);
    for (const l of z)
      l.onAfterUpdatedLOD?.(this.renderer, t, e, s, T);
    i.lastLodLevel_Mesh = T.mesh_lod, i.lastLodLevel_Texture = T.texture_lod;
  }
  /** Load progressive textures for the given material
   * @param material the material to load the textures for
   * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
   * @returns Promise with true if the LOD was loaded, false if not
   */
  loadProgressiveTextures(t, e, s) {
    if (!t) return;
    if (Array.isArray(t)) {
      for (const i of t)
        this.loadProgressiveTextures(i, e);
      return;
    }
    let r = !1;
    if ((t[U] === void 0 || e < t[U]) && (r = !0), s !== void 0 && s >= 0 && (r = t[U] != s, e = s), r) {
      t[U] = e;
      const i = y.assignTextureLOD(t, e).then((n) => {
        this._lodchangedlisteners.forEach((l) => l({ type: "texture", level: e, object: t }));
      });
      de.addPromise("texture", t, i, this._newPromiseGroups);
    }
  }
  /** Load progressive meshes for the given mesh
   * @param mesh the mesh to load the LOD for
   * @param index the index of the mesh if it's part of a group
   * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
   * @returns Promise with true if the LOD was loaded, false if not
   */
  loadProgressiveMeshes(t, e) {
    if (!t) return Promise.resolve(null);
    let s = t[U] !== e;
    const r = t["DEBUG:LOD"];
    if (r != null && (s = t[U] != r, e = r), s) {
      t[U] = e;
      const i = t.geometry, n = y.assignMeshLOD(t, e).then((l) => (l && t[U] == e && i != t.geometry && this._lodchangedlisteners.forEach((a) => a({ type: "mesh", level: e, object: t })), l));
      return de.addPromise("mesh", t, n, this._newPromiseGroups), n;
    }
    return Promise.resolve(null);
  }
  // private testIfLODLevelsAreAvailable() {
  _sphere = new Se();
  _tempBox = new pe();
  _tempBox2 = new pe();
  tempMatrix = new Me();
  _tempWorldPosition = new A();
  _tempBoxSize = new A();
  _tempBox2Size = new A();
  static corner0 = new A();
  static corner1 = new A();
  static corner2 = new A();
  static corner3 = new A();
  static _tempPtInside = new A();
  static isInside(t, e) {
    const s = t.min, r = t.max, i = (s.x + r.x) * 0.5, n = (s.y + r.y) * 0.5;
    return this._tempPtInside.set(i, n, s.z).applyMatrix4(e).z < 0;
  }
  static skinnedMeshBoundsFrameOffsetCounter = 0;
  static $skinnedMeshBoundsOffset = /* @__PURE__ */ Symbol("gltf-progressive-skinnedMeshBoundsOffset");
  // #region calculateLodLevel
  calculateLodLevel(t, e, s, r, i) {
    if (!e) {
      i.mesh_lod = -1, i.texture_lod = -1;
      return;
    }
    if (!t) {
      i.mesh_lod = -1, i.texture_lod = -1;
      return;
    }
    let l = 10 + 1, a = !1;
    if (R && e["DEBUG:LOD"] != null)
      return e["DEBUG:LOD"];
    const u = y.getMeshLODExtension(e.geometry)?.lods, c = y.getPrimitiveIndex(e.geometry), m = u && u.length > 0, w = y.getMaterialMinMaxLODsCount(e.material), L = w.min_count !== 1 / 0 && w.min_count >= 0 && w.max_count >= 0;
    if (!m && !L) {
      i.mesh_lod = 0, i.texture_lod = 0;
      return;
    }
    m || (a = !0, l = 0);
    const k = this.renderer.domElement.clientHeight || this.renderer.domElement.height;
    let v = e.geometry.boundingBox;
    if (e.type === "SkinnedMesh") {
      const d = e;
      if (!d.boundingBox)
        d.computeBoundingBox();
      else if (this.skinnedMeshAutoUpdateBoundsInterval > 0) {
        if (!d[O.$skinnedMeshBoundsOffset]) {
          const M = O.skinnedMeshBoundsFrameOffsetCounter++;
          d[O.$skinnedMeshBoundsOffset] = M;
        }
        const g = d[O.$skinnedMeshBoundsOffset];
        if ((s.frames + g) % this.skinnedMeshAutoUpdateBoundsInterval === 0) {
          const M = ee(d), B = d.geometry;
          M && (d.geometry = M), d.computeBoundingBox(), d.geometry = B;
        }
      }
      v = d.boundingBox;
    }
    if (v) {
      const d = t;
      if (e.geometry.attributes.color && e.geometry.attributes.color.count < 100 && e.geometry.boundingSphere) {
        this._sphere.copy(e.geometry.boundingSphere), this._sphere.applyMatrix4(e.matrixWorld);
        const h = t.getWorldPosition(this._tempWorldPosition);
        if (this._sphere.containsPoint(h)) {
          i.mesh_lod = 0, i.texture_lod = 0;
          return;
        }
      }
      if (this._tempBox.copy(v), this._tempBox.applyMatrix4(e.matrixWorld), d.isPerspectiveCamera && O.isInside(this._tempBox, this.projectionScreenMatrix)) {
        i.mesh_lod = 0, i.texture_lod = 0;
        return;
      }
      if (this._tempBox.applyMatrix4(this.projectionScreenMatrix), this.renderer.xr.enabled && d.isPerspectiveCamera && d.fov > 70) {
        const h = this._tempBox.min, p = this._tempBox.max;
        let b = h.x, S = h.y, G = p.x, Y = p.y;
        const te = 2, ae = 1.5, se = (h.x + p.x) * 0.5, re = (h.y + p.y) * 0.5;
        b = (b - se) * te + se, S = (S - re) * te + re, G = (G - se) * te + se, Y = (Y - re) * te + re;
        const Be = b < 0 && G > 0 ? 0 : Math.min(Math.abs(h.x), Math.abs(p.x)), Ge = S < 0 && Y > 0 ? 0 : Math.min(Math.abs(h.y), Math.abs(p.y)), le = Math.max(Be, Ge);
        s.lastCentrality = (ae - le) * (ae - le) * (ae - le);
      } else
        s.lastCentrality = 1;
      const g = this._tempBox.getSize(this._tempBoxSize);
      g.multiplyScalar(0.5), screen.availHeight > 0 && k > 0 && g.multiplyScalar(k / screen.availHeight), t.isPerspectiveCamera ? g.x *= t.aspect : t.isOrthographicCamera;
      const M = t.matrixWorldInverse, B = this._tempBox2;
      B.copy(v), B.applyMatrix4(e.matrixWorld), B.applyMatrix4(M);
      const D = B.getSize(this._tempBox2Size), q = Math.max(D.x, D.y);
      if (Math.max(g.x, g.y) != 0 && q != 0 && (g.z = D.z / Math.max(D.x, D.y) * Math.max(g.x, g.y)), s.lastScreenCoverage = Math.max(g.x, g.y, g.z), s.lastScreenspaceVolume.copy(g), s.lastScreenCoverage *= s.lastCentrality, R && O.debugDrawLine) {
        const h = this.tempMatrix.copy(this.projectionScreenMatrix);
        h.invert();
        const p = O.corner0, b = O.corner1, S = O.corner2, G = O.corner3;
        p.copy(this._tempBox.min), b.copy(this._tempBox.max), b.x = p.x, S.copy(this._tempBox.max), S.y = p.y, G.copy(this._tempBox.max);
        const Y = (p.z + G.z) * 0.5;
        p.z = b.z = S.z = G.z = Y, p.applyMatrix4(h), b.applyMatrix4(h), S.applyMatrix4(h), G.applyMatrix4(h), O.debugDrawLine(p, b, 255), O.debugDrawLine(p, S, 255), O.debugDrawLine(b, G, 255), O.debugDrawLine(S, G, 255);
      }
      let _ = 999;
      if (u && s.lastScreenCoverage > 0)
        for (let h = 0; h < u.length; h++) {
          const p = u[h], S = (p.densities?.[c] || p.density || 1e-5) / s.lastScreenCoverage;
          if (c > 0 && ve() && !p.densities && !globalThis["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"] && (window["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"] = !0, console.warn("[Needle Progressive] Detected usage of mesh without primitive densities. This might cause incorrect LOD level selection: Consider re-optimizing your model by updating your Needle Integration, Needle glTF Pipeline or running optimization again on Needle Cloud.")), S < r) {
            _ = h;
            break;
          }
        }
      _ < l && (l = _, a = !0);
    }
    if (a ? i.mesh_lod = l : i.mesh_lod = s.lastLodLevel_Mesh, R && i.mesh_lod != s.lastLodLevel_Mesh) {
      const g = u?.[i.mesh_lod];
      g && console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} → ${i.mesh_lod} (density: ${g.densities?.[c].toFixed(0)}) | ${e.name}`);
    }
    if (L) {
      const d = "saveData" in globalThis.navigator && globalThis.navigator.saveData === !0;
      if (s.lastLodLevel_Texture < 0) {
        if (i.texture_lod = w.max_count - 1, R) {
          const g = w.lods[w.max_count - 1];
          R && console.log(`First Texture LOD ${i.texture_lod} (${g.max_height}px) - ${e.name}`);
        }
      } else {
        const g = s.lastScreenspaceVolume.x + s.lastScreenspaceVolume.y + s.lastScreenspaceVolume.z;
        let M = s.lastScreenCoverage * 4;
        this.context?.engine === "model-viewer" && (M *= 1.5);
        const D = k / window.devicePixelRatio * M;
        let q = !1;
        for (let P = w.lods.length - 1; P >= 0; P--) {
          const _ = w.lods[P];
          if (!(d && _.max_height >= 2048) && !(ke() && _.max_height > 4096) && (_.max_height > D || !q && P === 0)) {
            if (q = !0, i.texture_lod = P, R && i.texture_lod < s.lastLodLevel_Texture) {
              const x = _.max_height;
              console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} → ${i.texture_lod} = ${x}px 
Screensize: ${D.toFixed(0)}px, Coverage: ${(100 * s.lastScreenCoverage).toFixed(2)}%, Volume ${g.toFixed(1)} 
${e.name}`);
            }
            break;
          }
        }
      }
    } else
      i.texture_lod = 0;
  }
};
class xt {
  frames = 0;
  lastLodLevel_Mesh = -1;
  lastLodLevel_Texture = -1;
  lastScreenCoverage = 0;
  lastScreenspaceVolume = new A();
  lastCentrality = 0;
}
const De = /* @__PURE__ */ Symbol("NEEDLE_mesh_lod"), ie = /* @__PURE__ */ Symbol("NEEDLE_texture_lod");
let ge = null;
function Ie() {
  const o = wt();
  o && (o.mapURLs(function(t) {
    return be(), t;
  }), be(), ge?.disconnect(), ge = new MutationObserver((t) => {
    t.forEach((e) => {
      e.addedNodes.forEach((s) => {
        s instanceof HTMLElement && s.tagName.toLowerCase() === "model-viewer" && $e(s);
      });
    });
  }), ge.observe(document, { childList: !0, subtree: !0 }));
}
function wt() {
  if (typeof customElements > "u") return null;
  const o = customElements.get("model-viewer");
  return o || (customElements.whenDefined("model-viewer").then(() => {
    console.debug("[gltf-progressive] model-viewer defined"), Ie();
  }), null);
}
function be() {
  if (typeof document > "u") return;
  document.querySelectorAll("model-viewer").forEach((t) => {
    $e(t);
  });
}
const Oe = /* @__PURE__ */ new WeakSet();
let Lt = 0;
function $e(o) {
  if (!o || Oe.has(o))
    return null;
  Oe.add(o), console.debug("[gltf-progressive] found new model-viewer..." + ++Lt + `
`, o.getAttribute("src"));
  let t = null, e = null, s = null;
  for (let r = o; r != null; r = Object.getPrototypeOf(r)) {
    const i = Object.getOwnPropertySymbols(r), n = i.find((u) => u.toString() == "Symbol(renderer)"), l = i.find((u) => u.toString() == "Symbol(scene)"), a = i.find((u) => u.toString() == "Symbol(needsRender)");
    !t && n != null && (t = o[n].threeRenderer), !e && l != null && (e = o[l]), !s && a != null && (s = o[a]);
  }
  if (t && e) {
    let r = function() {
      if (s) {
        let n = 0, l = setInterval(() => {
          if (n++ > 5) {
            clearInterval(l);
            return;
          }
          s?.call(o);
        }, 300);
      }
    };
    console.debug("[gltf-progressive] setup model-viewer");
    const i = oe.get(t, { engine: "model-viewer" });
    return oe.addPlugin(new _t()), i.enable(), i.addEventListener("changed", () => {
      s?.call(o);
    }), o.addEventListener("model-visibility", (n) => {
      n.detail.visible && s?.call(o);
    }), o.addEventListener("load", () => {
      r();
    }), () => {
      i.disable();
    };
  }
  return null;
}
class _t {
  _didWarnAboutMissingUrl = !1;
  onBeforeUpdateLOD(t, e, s, r) {
    this.tryParseMeshLOD(e, r), this.tryParseTextureLOD(e, r);
  }
  getUrl(t) {
    if (!t)
      return null;
    let e = t.getAttribute("src");
    return e || (e = t.src), e || (this._didWarnAboutMissingUrl || console.warn("No url found in modelviewer", t), this._didWarnAboutMissingUrl = !0), e;
  }
  tryGetCurrentGLTF(t) {
    return t._currentGLTF;
  }
  tryGetCurrentModelViewer(t) {
    return t.element;
  }
  tryParseTextureLOD(t, e) {
    if (e[ie] == !0) return;
    e[ie] = !0;
    const s = this.tryGetCurrentGLTF(t), r = this.tryGetCurrentModelViewer(t), i = this.getUrl(r);
    if (i && s && e.material) {
      let n = function(a) {
        if (a[ie] == !0) return;
        a[ie] = !0, a.userData && (a.userData.LOD = -1);
        const u = Object.keys(a);
        for (let c = 0; c < u.length; c++) {
          const m = u[c], w = a[m];
          if (w?.isTexture === !0) {
            const L = w.userData?.associations?.textures;
            if (L == null) continue;
            const k = s.parser.json.textures[L];
            if (!k) {
              console.warn("Texture data not found for texture index " + L);
              continue;
            }
            if (k?.extensions?.[W]) {
              const v = k.extensions[W];
              v && i && y.registerTexture(i, w, v.lods.length, L, v);
            }
          }
        }
      };
      const l = e.material;
      if (Array.isArray(l)) for (const a of l) n(a);
      else n(l);
    }
  }
  tryParseMeshLOD(t, e) {
    if (e[De] == !0) return;
    e[De] = !0;
    const s = this.tryGetCurrentModelViewer(t), r = this.getUrl(s);
    if (!r)
      return;
    const i = e.userData?.gltfExtensions?.[W];
    if (i && r) {
      const n = e.uuid;
      y.registerMesh(r, n, e, 0, i.lods.length, i);
    }
  }
}
function Mt(...o) {
  let t, e, s, r;
  switch (o.length) {
    case 2:
      [s, e] = o, r = {};
      break;
    case 3:
      [s, e, r] = o;
      break;
    case 4:
      [t, e, s, r] = o;
      break;
    default:
      throw new Error("Invalid arguments");
  }
  Le(e), Te(s), Ae(s, {
    progressive: !0,
    ...r?.hints
  }), s.register((n) => new y(n));
  const i = oe.get(e);
  return r?.enableLODsManager !== !1 && i.enable(), i;
}
Ie();
if (!at) {
  const o = {
    gltfProgressive: {
      useNeedleProgressive: Mt,
      LODsManager: oe,
      configureLoader: Ae,
      getRaycastMesh: ee,
      useRaycastMeshes: ut
    }
  };
  if (!globalThis.Needle)
    globalThis.Needle = o;
  else
    for (const t in o)
      globalThis.Needle[t] = o[t];
}
export {
  oe as LODsManager,
  y as NEEDLE_progressive,
  Te as addDracoAndKTX2Loaders,
  Ae as configureLoader,
  Le as createLoaders,
  ee as getRaycastMesh,
  Ze as setDracoDecoderLocation,
  et as setKTX2TranscoderLocation
};
